I just want to convert a character into an Int.
This should be simple. But I haven't found the previous answers helpful. There is always some error. Perhaps it is because I'm trying it in Swift 2.0.
for i in (unsolved.characters) {
fileLines += String(i).toInt()
print(i)
}
In Swift 2.0,
toInt()
, etc., have been replaced with initializers. (In this case,Int(someString)
.)Because not all strings can be converted to ints, this initializer is failable, which means it returns an optional int (
Int?
) instead of just anInt
. The best thing to do is unwrap this optional usingif let
.I'm not sure exactly what you're going for, but this code works in Swift 2, and accomplishes what I think you're trying to do:
Or, for a Swiftier solution:
You can shorten this more with
flatMap
:flatMap
returns "anArray
containing the non-nil results of mappingtransform
overself
"… so whenInt(String($0))
isnil
, the result is discarded.