Xcode6 beta 4 downcast to float - swift

I have a Dictionary with a String and AnyObject, so [String: AnyObject].
In a function I want to check the type of the dict value. So this code worked in Xcode6-Beta 3:
for (key, value: AnyObject) in contents {
...
} else if value is Float {
stringValue = String(value as Float) + ","
Now I get the error: AnyObject is not convertible to Float
stringValue = String(Float(value)) + "," doesn't work as well.
Any ideas?

There is no problem with casting AnyObject to Float.
Converting AnyObject to Float has no problem as you can see below instruction will execute without errors.
var f:Float = value as Float
As swift String has no intializer to convert for Float
If you do
var str:String = String(f) //This will show error as swift has no intializer for Float
But Swift has only added intializer to String for Int to convert directly.There is not intializer for Float.
var i:Int = value as Int
var str:String = String(i) //this will run fine
Now to solve your problem you can do
for (key, value: AnyObject) in contents {
if(value is Int){
}else if value is Float {
//Take this in var and use
var stringValue = "\(value as Float),"
}
}
In future swift may add the intializer for Float but currently there is no intializer.

Replace "as" with "as!" to force downcast.
Please, remember that you can use the forced form of the type cast operator (as!) only when you are sure that the downcast will always succeed, otherwise a runtime error will be triggered. In your particular case there will be no problem since there is a previous checking (if value is Float).

You can't cast to float because:
AnyObject can represent an instance of any class type.
From Swift Programming Guide
But float isn't a class. You will have to use Any instead:
Any can represent an instance of any type at all, apart from function types.
From Swift Programming Guide
This should work (but I can't test on my current Mac):
for (key, value: Any) in contents {
...
} else if value is Float {
stringValue = String(value as Float) + ","

As wumm said, you can't directly cast to Float because Float is not a class type. You may be able to cast it to an NSNumber and bridge to a Float though. Try
value as NSNumber as Float
This strategy works with casting AnyObject into a Swift String.
Using your code and fixing the concatenation it would look like:
for (key, value: AnyObject) in contents {
if value is Float {
stringValue = "\(stringValue) \(value as NSNumber as Float) ,"
}
}

Related

Cannot match values of type

I'm just starting out with Swift 3 and I'm converting a Rails project to swift (side project while I learn)
Fairly simple, I have a Rails statement Im converting and Im getting many red errors in Xcode:
let startingPoint: Int = 1
let firstRange: ClosedRange = (2...10)
let secondRange: ClosedRange = (11...20)
func calc(range: Float) -> Float {
switch range {
case startingPoint:
return (range - startingPoint) * 1 // or 0.2
case firstRange:
return // code
default:
return //code
}
}
calc will either have an Int or Float value: 10 or 10.50
Errors are:
Expression pattern of type ClosedRange cannot match values of type Float
Binary operator - cannot be applied to operands of type Float and Int
I understand the errors but I dont know what to search for to correct it. Could you point me in the right direction, please?
Swift is strongly typed. Whenever you use a variable or pass something as a function argument, Swift checks that it is of the correct type. You can't pass a string to a function that expects an integer etc. Swift does this check at compile time (since it's statically typed).
To adhere by that rules, try changing your code to this:
let startingPoint: Float = 1
let firstRange: ClosedRange<Float> = (2...10)
let secondRange: ClosedRange<Float> = (11...20)
func calc(range: Float) -> Float {
switch range {
case startingPoint:
return (range - startingPoint) * 1 // or 0.2
case firstRange:
return 1.0 // 1.0 is just an example, but you have to return Float since that is defined in the method
default:
return 0.0 // 0.0 is just an example, put whatever you need here
}
}
For the first error, you might want to specify ClosedRange to be of type Floats. Something similar to:
let firstRange: ClosedRange<Float> = (2...10)
For the second error, the problem is you are trying to compare a Float (range:Float) with an Int (startingPoint). So I would suggest you convert the startingPoint variable to a Float as well.

Convert optional string to int in Swift

I am having troubles while converting optional string to int.
println("str_VAR = \(str_VAR)")
println(str_VAR.toInt())
Result is
str_VAR = Optional(100)
nil
And i want it to be
str_VAR = Optional(100)
100
At the time of writing, the other answers on this page used old Swift syntax. This is an update.
Convert Optional String to Int: String? -> Int
let optionalString: String? = "100"
if let string = optionalString, let myInt = Int(string) {
print("Int : \(myInt)")
}
This converts the string "100" into the integer 100 and prints the output. If optionalString were nil, hello, or 3.5, nothing would be printed.
Also consider using a guard statement.
You can unwrap it this way:
if let yourStr = str_VAR?.toInt() {
println("str_VAR = \(yourStr)") //"str_VAR = 100"
println(yourStr) //"100"
}
Refer THIS for more info.
When to use “if let”?
if let is a special structure in Swift that allows you to check if an Optional holds a value, and in case it does – do something with the unwrapped value. Let’s have a look:
if let yourStr = str_VAR?.toInt() {
println("str_VAR = \(yourStr)")
println(yourStr)
}else {
//show an alert for something else
}
The if let structure unwraps str_VAR?.toInt() (i.e. checks if there’s a value stored and takes that value) and stores its value in the yourStr constant. You can use yourStr inside the first branch of the if. Notice that inside the if you don’t need to use ? or ! anymore. It’s important to realise thatyourStr is actually of type Int that’s not an Optional type so you can use its value directly.
Try this:
if let i = str_VAR?.toInt() {
println("\(i)")
}

constant 'result' inferred to have type (), which may be unexpected

#IBAction func operate(sender: UIButton) {
if let operation = sender.currentTitle {
if let result = brain.performOperation(operation) {
displayValue = result
}
else {
displayValue = 0.0
}
}
}
I am new to coding so pardon my coding format and other inconsistencies. I have been trying out the iOS 8 intro to swift programming taught by Stanford university and I have ran into a problem with the modified calculator.
I get three errors. The first one is a swift compiler warning - at
if let result = brain.performOperation(operation)
It says
constant 'result' inferred to have type () which may be unexpected.
It gives me the suggestion to do this ----
if let result: () = brain.performOperation(operation)
The other two errors are
Bound value in a conditional binding must be of Optional type at if let result line
Cannot assign a value of type () to a value of Double at "displayValue = result"
Here is the github link if anyone needs more information on the code.
Thanks in advance.
Guessing from the errors, I expect that performOperation() is supposed to return Double? (optional double) while if fact it returns nothing.
I.e. it's signature is probably:
func performOperation(operation: String) {
// ...
}
.. while in fact it should be:
func performOperation(operation: String) -> Double? {
// ...
}
Reason why I think so is that this line: if let result = brain.performOperation(operation) is call "unwrapping the optional" and it expects that the assigned value is an optional type. Later you assign the value that you unwrap to the variable that seems to be of Double type.
By the way, the shorter (and more readable) way to write the same is:
displayValue = brain.performOperation(operation) ?? 0.0
It looks like brain.performOperation() does not return a result at all,
so there is no optional value, too.

How can I convert Int32 to Int in Swift?

It should be easy but I can only find the reverse conversion.
How can I convert Int32 to Int in Swift?
Unless the problem is different?
I have a value stored in Core Data and I want to return it as an Int.
Here is the code I am using, which does not work:
func myNumber () -> Int {
var myUnit:NSManagedObject
myUnit=self.getObject(“EntityName”) // This is working.
return Int(myUnit.valueForKey(“theNUMBER”)?.intValue!)
}
Am I missing something or isn't this ridiculously easy?
let number1: Int32 = 10
let number2 = Int(number1)
The error is your ? after valueForKey.
Int initializer doesnt accept optionals.
By doing myUnit.valueForKey(“theNUMBER”)?.intValue! gives you an optional value and the ! at the end doesnt help it.
Just replace with this:
return Int(myUnit.valueForKey(“theNUMBER”)!.intValue)
But you could also do like this if you want it to be fail safe:
return myUnit.valueForKey(“theNUMBER”)?.integerValue ?? 0
And to shorten you function you can do this:
func myNumber() -> Int {
let myUnit = self.getObject("EntityName") as! NSManagedObject
return myUnit.valueForKey("theNUMBER")?.integerValue ?? 0
}
Swift 4.0 producing "Cannot invoke initializer for type 'Int' with an argument list of type '(() -> Int32)"
let number1: Int32 = 10
let number2 = Int(number1)
Simply do this
Int("\(Int32value)")
I'm unable to understand why swift is making things difficult.
Sometimes "?" make things twisted ,
adding "!" to Int32 and then convert it to int works
let number1 = someInt32!
let number2 = Int(number1)

Why can't I use a variable of type float when "reducing" an array?

I have the following variable:
var calorieTotal: Float {
return calorieNumberArray.reduce(0) { $0 + $1 }
}
Basically, I'm trying to add the numbers of an array I have together. First, I had the variable set to type int, but now I need it as a float value. When I try to do this, an error comes up: "'UInt8' is not a subtype of 'float'". How can I fix this? Please provide the code for the new/changed variable, as I am new to programming.
I presume that calorieNumberArray is an array of Int - in such case, just pass a float as initial value, and explicitly convert to Float the 2nd parameter passed to the closure:
var calorieTotal: Float {
return calorieNumberArray.reduce(0 as Float) { $0 + Float($1) }
}
$0 doesn't need conversion because it's already a float