问题:
使用swift 2.2在Xcode 7.3下运行以下代码时,编译器无法正确推断可选的类型:
import Foundation
func whatAmI<T>(inout property:T?)
{
switch property {
case is Int?:
print("I am an Int?")
case is String?:
print("I am a String?")
default:
print("I don't know what I am")
}
}
var string : String?
whatAmI(&string)
Run Code Online (Sandbox Code Playgroud)
在我身边使用Xcode 7.3,这将打印出来 I am an Int?
但是,当我在将变量传递给函数之前使用空字符串初始化变量时,开关会将其推断为String?.
这将I am a String?在之前的Xcode版本中打印.
你得到类似的结果吗?
观察:
使用此函数签名时也会出现同样的情况:
func whatAmI(property:AnyObject?)
Run Code Online (Sandbox Code Playgroud)
- 错误 -
这个问题是swift 2.2中的回归:https: //bugs.swift.org/browse/SR-1024
这似乎是一个错误。最小的例子如下:
func genericMethod<T>(property: T?) {
print(T) // String
let stringNil = Optional<String>.None
print(stringNil is String?) // true (warning - always true)
print(stringNil is T?) // true
let intNil = Optional<Int>.None
print(intNil is String?) // false (warning - always fails)
print(intNil is T?) // true - BUG
}
genericMethod("")
Run Code Online (Sandbox Code Playgroud)