Difference between : and = [duplicate] - swift

This question already has answers here:
What is the difference between ":" and "=" in Swift?
(3 answers)
Closed 7 years ago.
I have been programming in Swift for quite a while. But still I haven't got down the whole of the basics and haven't understood the difference between '=' and ':'. We use these to declare variables. But what is the difference between equal to and a colon while programming in Swift? Any help will be appreciated!

With : you are declaring a type and with = you are assigning a value.
Check out the section "Type Annotations" in the Apple Swift guide.
In response to the comment:
when we use = also while declaring the type. For example- var anyVariable = Int. In this we are declaring the type, isn't it? Pardon me if I am wrong. – ojassethi
This is because the type will automatically recognized.
For example all Strings are declared with quotation marks
let myString = "Hello" // The right Value is a String, so the variable is of the type string
While on the other hand it could mistake a value if you are not precisely using =
let myDouble = 1 // myDouble is an Int! not a Double, because for the compiler 1 is an Int
let myDouble: Double = 1 // Now myDouble is a Double
let myDouble = 1.0 // Now myDouble also is a Double

Related

do we need to explicitly case type when converting? [duplicate]

This question already has answers here:
How does Swift's int literal to float inference work?
(3 answers)
Closed 4 years ago.
when I read the doc of swift
https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html
let anotherPi = 3 + 0.14159
// anotherPi is also inferred to be of type Double
this works, however if I delete the "Double" in the following case, it does not work.
let three = 3
let pointOneFourOneFiveNine = 0.14159
let pi = Double(three) + pointOneFourOneFiveNine
May I ask why do we need to explicitly convert the type in second case? what is the difference?
It is because of Swift's automatic type inference.
let three = 3 // Here **three** is inferred as Int
let pointOneFourOneFiveNine = 0.14159 // Here **pointOneFourOneFiveNine** is inferred as Double
let pi = Double(three) + pointOneFourOneFiveNine
And since you cannot add a Double to an Int, it’s the reason that you have to wrap the three as Double(three).
let anotherPi = 3 + 0.14159
// anotherPi is also inferred to be of type Double
The reason the above code works because the compiler finds that both the summing inputs can be represented as Double, so it assigns the type Double to anotherPi. Hope this clears your doubt.

Swift-Binary operator cannot be applied to two "Double" operands [duplicate]

This question already has answers here:
binary operator '/' cannot be applied to two 'Double' operands
(3 answers)
Closed 6 years ago.
I'm receiving what appears to be a relatively common error in my code, but examples of solutions to it on other questions didn't appear to be quite relevant to my situation. For example; (binary operator '/' cannot be applied to two 'Double' operands)
let variable1 = Double()
let variable2 = Double()
let array = [5, 10]
var variable3 = Double()
func function() {
let variable1 = 50 / variable2
let variable3 = Double(arc4random_uniform(UInt32(Double(array.count))))
let scaleAction = SKAction.scale(by: variable1 * variable3, duration: 1)
That's all the relevant code anyway. For whatever reason I receive an error, focused on the multiplication star in the last line, saying that the "Binary operator "*" cannot be applied to two "Double" operands. Why can't it? And is there a way I can fix this?
Thanks in advance.
The error message is a bit misleading. The real problem is that scale(by:duration:) takes a CGFloat as the scale:
open class func scale(by scale: CGFloat, duration sec: TimeInterval) -> SKAction
So, you need to pass a CGFloat. You can either work to make sure variable1 and variable3 are CGFloats, or you can use the CGFloat constructor to convert it from a Double:
let scaleAction = SKAction.scale(by: CGFloat(variable1 * variable3), duration: 1)

How do I convert Float to Int When Necessary? [duplicate]

This question already has answers here:
Swift - How to remove a decimal from a float if the decimal is equal to 0?
(15 answers)
Closed 6 years ago.
So, I'm pretty new to swift and Xcode and might be missing something obvious, but I've done a bit of research, and can't find my answer.
My code is:
for number in currentList {
listPreview.text = "\(listPreview.text!) \(String(number))"
}
The problem is, the Numbers in currentList are Floats. But if my user were to input a number that isn't a float, it will display as:
"UsersNumber".0
I want it to display as just:
"UsersNumber"
However, if the number the user gave me was a float, say... 1.2, I would still want it to display as 1.2 .
is there some kind of extension that can do this?
Like an if-statement saying
if number.isUselessFloat {
code
}
Thanks in advance,
-Another Nooby user
let number1 = 1.0
let number2 = 1.2
let str = String(format: number1 == floor(number1) ? "%.0f":"%.1f", number1)
print(str)
//prints 1
let str2 = String(format: number2 == floor(number2) ? "%.0f":"%.1f", number2)
print(str2)
//prints 1.2

binary operator / cannot be applied to operands of type Int and Double [duplicate]

This question already has answers here:
Multiplying variables and doubles in swift
(2 answers)
So if string is not NilLiteralConvertible... what do some string functions return?
(1 answer)
Closed 7 years ago.
Hello brand new to Swift, and programming in general. Going through an exercise the code given is exactly:
//: Playground - noun: a place where people can play
import UIKit
let height = 12
let width = 10
let area = height * width
let areaInMeters = area / 10.762
But I get the error, "binary operator / cannot be applied to operands of type Int and Double".
After some digging around I found you can't operate on both an Integer and a Double. So I changed the last line to:
let areaInMeters = (Double)area / 10.762
Then I get the error, "Consecutive statements on a line must be separated by a ;" and it wants me to put the ; after area. None of this is making any sense to me.
Using El Capitan beta and Xcode 7 beta.
height and width will both be inferred as of type Int. Therefore area is also of type Int whilst 10.762 is a Double.
And in Swift safety is paramount so you'll need to have both operands of same type.
Solution is (as Eric D. suggested) is to convert area to a Double:
let areaInMeters = Double(area) / 10.762
Try instead adding a decimal point and a zero to the end of your height and width.
Like so:
let height = 12.0
let width = 10.0
And you won't have to worry about having to deal with an Integer.
Hope this helps. Happy Coding!

Increment number in Dictionary

I have a Dictionary [String:AnyObject] which contains some keys and values.
I want to increment a key to which value is of type Double.
I can do it this way:
let nr = dict["number"] as! Double
dict["number"] = nr + 10
But I dont like that way so Im wondering if there is another way
I tried this:
(dict["number"] as! Double) += 10
But that gives me an error:
Binary operator '+=' cannot be applied to operands of type '(Double)' and 'Double'
Why isn't this working?
Following is an alternative. If you want to avoid force unwrapping an optional:
dict["number"] = (dict["number"] ?? 0) + 10
You are close and in fact you can write to a dictionary using +=, the problem is your cast. For example we can do:
var dict = ["number" : 2]
dict["number"]! += 10
and now dict["number"] returns 12. Now this is creating a new value (12) and replacing it into the dictionary, it is just a clean way of looking at it.
The problem with your code is that the left side (dict["number"] as! Double) gives you a Double. So you have say (12), then the right side is a Double too (10). So your code ends up looking like (12) += 10 which you can clearly see as problematic, since this is equivalent to 12 = 12 + 10, yikes!
So that being said, you can use the my first solution if you are working with native Swift dictionaries, otherwise your solved solution above works too, just a bit longer.
Lastly, if you are really looking for a one liner that works with your exact situation you should be able to do something like:
dict["number"] = (dict["number"] as! Double) + 10
Another option:
dict["number", default: 0] += 10
The safe way of casting would be:
if let num = dict["number"] as? Double {
dict["number"] = num + 10
}