我正在练习Swift Optional类型,并注意到奇怪的(对我来说)行为。代码:
func returnOptionalIntFromString(_ val: String) -> Int? {
return Int(val)
}
func returnIntFromString(_ val: String) -> Int {
return Int(val) ?? 0
}
let optionalStr: String? = "10"
let mappedC1 = optionalStr.map(returnIntFromString)
let mappedC2 = optionalStr.map(returnOptionalIntFromString)
let flatMappedC1 = optionalStr.flatMap(returnIntFromString)
let flatMappedC2 = optionalStr.flatMap(returnOptionalIntFromString)
为什么这行let flatMappedC1 = optionalStr.flatMap(returnIntFromString)
正在编译?我将(String) -> Int
传递给接受(String) -> Optional<Int>
的函数,所以它必须是编译时错误?或没有? :)
答案 0 :(得分:3)
选项由编译器专门处理。特别是一个值
如有必要,T
类型会自动换入Optional<T>
:
let a = 5
let b: Int? = a
这也适用于非可选vs可选的返回类型 关闭:
let cla: () -> Int = { return 13 }
let clb: () -> Int? = cla
这就是
中发生的事情let flatMappedC1 = optionalStr.flatMap(returnIntFromString)
答案 1 :(得分:0)
我想我必须说示例中的所有变量都是Optional
let optionalStr: String? = "10"
let mappedC1 = optionalStr.map(returnIntFromString)
let mappedC2 = optionalStr.map(returnOptionalIntFromString)
let flatMappedC1 = optionalStr.flatMap(returnIntFromString)
let flatMappedC2 = optionalStr.flatMap(returnOptionalIntFromString)
print(optionalStr, mappedC1, mappedC2, flatMappedC1, flatMappedC2)
yeilds:
Optional("10") Optional(10) Optional(Optional(10)) Optional(10) Optional(10)
呀! &#39;可选世界&#39;来了! :)
所以,let flatMappedC1 = optionalStr.flatMap(returnIntFromString)
应该这样读:
如果optionalStr
不是零,请打开&#34; 10&#34;并使用flatMap函数,其中returnIntFromString
有非可选参数。函数returnIntFromString
返回Int
,可以简单地转换为Int?
,如@MartinR所说。函数flatMap
yeilds Int?
。如果optionalStr
为nil flatMappedC1
,则无效。