Using Swift 2, in my contrived example I am converting a String
to an Int
or more specifically an Int
or an Int?
using a generic. In the case where the Int?
should be nil the cast will fail with a fatalError: fatal error: unexpectedly found nil while unwrapping an Optional value
These look like they may be similar/duplicate questions:
My question is: how is one supposed to cast to an optional that is nil?
Example:
class Thing<T>{
var item: T
init(_ item: T){
self.item = item
}
}
struct Actions{
static func convertIntForThing<T>(string: String, thing:Thing<T>) -> T{
return convertStringToInt(string, to: T.self)
}
static func convertStringToInt<T>(string: String, to: T.Type) -> T{
debugPrint("Converting to ---> \(to)")
if T.self == Int.self{
return Int(string)! as! T
}
// in the case of "" Int? will be nil, the cast
// here causes it to blow up with:
//
// fatal error: unexpectedly found nil while unwrapping an
// Optional value even though T in this case is an Optional<Int>
return Int(string) as! T
}
}
func testExample() {
// this WORKS:
let thing1 = Thing<Int>(0)
thing1.item = Actions.convertIntForThing("1", thing: thing1)
// This FAILS:
// empty string where value = Int("")
// will return an Optional<Int> that will be nil
let thing2 = Thing<Int?>(0)
thing2.item = Actions.convertIntForThing("", thing: thing2)
}
testExample()