我是 Swift 新手,正在尝试学习可选绑定的概念。我想出了以下代码:
let possibleNumber = Int("123")
possibleNumber.dynamicType
if let actualNumber = Int(possibleNumber){
print("\(possibleNumber) has an integer value of \(actualNumber)")
} else {
print("\(possibleNumber) could not be converted to an int")
}
Xcode Playground 输出错误信息:
value of optional type "int?" not unwrapped, did you mean to use "!" or "?"
但是,当我添加“!” 至 if let actualNumber = Int(possibleNumber!){
let possibleNumber = Int("123")
possibleNumber.dynamicType
if let actualNumber = Int(possibleNumber!){
print("\(possibleNumber) has an integer value of \(actualNumber)")
} else {
print("\(possibleNumber) could not be converted to an int")
}
Xcode 显示另一个错误信息:
initialiser for conditional binding must have Optional type, not int
为什么会这样?