swift


can't do division function in swift


I'm making the average function assignment from swift tutorial.
When I write code like this:
func AVG(numbers: Int...) -> Double {
var i=0, sum=0; var avg: Double
for number in numbers {
i+=1
sum+=number
avg = sum/i
}
return avg
}
let Average = AVG(numbers: 3,4,5)
print (Average)
It displays an error message showing binary operator "/" cannot be applied to two int operands.
when i perform a simple division like
let x = 5
let y = 2
let quo = x/y
it works.
What am I doing wrong in the function?
There are two issues in the AVG function – btw. function names are supposed to start with a lowercase letter.
A playground displays clear error messages
variable 'avg' used before being initialized
Solution:
var avg = 0.0
cannot assign value of type 'Int' to type 'Double'
Solution:
avg = Double(sum) / Double(i)
PS: An alternative using the key-value coding operator #avg
func avg(numbers: Int...) -> Double {
return (numbers as NSArray).value(forKeyPath: "#avg.self") as! Double
}
You declared avg as Double type.
numbers has Int as type, and i=0 makes it Int as well.
When you are doing sum/i it's Int/Int and you try to assign it to Double.
Swift is not doing conversion automatically - it forces you to convert data types manually.
You can fix it by simply converting both those variables to Double.
Keep in mind that you need to convert Int before doing division - otherwise result will cut the reminder as Int cannot have them. Credits to #martin
Also another problem is that if your numbers array is empty, you may try to return not initialized variable avg.
Working code below:
func AVG(numbers: Int...) -> Double {
var i=0, sum=0; var avg: Double = 0
for number in numbers {
i+=1
sum+=number
avg = Double(sum)/Double(i)
}
return avg
}
let Average = AVG(numbers: 3,4,5)
print (Average)

Related Links

NSURLSession receive data every X seconds
Swift 2 + Parse How to select all user into Users class [closed]
Is it possible to retrieve an exception inside a guard-statement with “try?”?
Confused with the NOT operator when used in if-statements?
Using textFieldDidendEditing to enable/disable a button swift
compare two NSObject in Swift
How to declare / implement a Swift function with a nullable pointer argument in Objective-c?
Can it be non rootviewcontroller?
NSTextField string with newlines
Swift GameplayKit pause GKAgent without pausing scene
Why doesn't Swift allow setting value of an optional constant after object initialization?
Swift what is the difference when unwrapping optional property using ? and?
How can I get my menu bar app to launch at login?
UITapGestureRecognizer won't connect directly to assistant editor?
How do you use a switch statement with a nested enum?
Decrement index in a loop after Swift C-style loops deprecated

Categories

HOME
laravel-5
ember.js
scipy
system-verilog
nuxeo
qpython3
actionscript
ruby-on-rails-3
zend-framework2
apollo
rocketmq
bro
data-science-experience
sudo
jframe
actionscript-2
openwrt
deeplearning4j
eclipse-cdt
jboss7.x
data-synchronization
mongodb-query
webmethods
scala-native
zope
bar-chart
android-toolbar
pyephem
attask
styles
ip-camera
ng2-dragula
google-ima
countif
npm-install
compare-and-swap
rhandsontable
interrupt-handling
pyscripter
rhomobile
salesforce-chatter
node-horseman
ios-ui-automation
openpgp
xen
ksoap
agent
polyfills
android-preferences
jrules
microdata
email-parsing
recycle-bin
tuleap
pinvoke
photography
ebtables
cfeclipse
manifest.mf
uistackview
glkit
mailcatcher
wcf-ria-services
visible
freetype2
spark-cassandra-connector
database-backups
gemini
remoteapp
financial
uialertview
base32
stream-framework
on-duplicate-key
leadtools-sdk
graphical-logo
criteria-api
code-first-migrations
pl-i
pgagent
cpu-speed
mser
adcolony
suffix-array
dto
eclipse-classpath
db4o
edit-in-place
operations
cilk-plus
nsmatrix
astyanax
entity-framework-4.1
sharpmap
vt100
trailing-slash
ubuntu-11.10
radchart
unions
ubuntu-11.04
cross-domain-policy
datamember
carbide
clients
code-design
usergroups

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App