问题
Problem:
When running the following code under Xcode 7.3 with swift 2.2, the compiler is unable to correctly infer the type of the optional:
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)
On my side with Xcode 7.3 this will print I am an Int?
However, when I initialize the variable with an empty string before passing it to the function, the switch infers it to be a String?.
This would print I am a String?
in the previous Xcode version.
Are you getting similar results?
Observations:
The same occurs when using this function signature:
func whatAmI(property:AnyObject?)
-- Bug --
This issue is a regression in swift 2.2: https://bugs.swift.org/browse/SR-1024
回答1:
This seems to be a bug. The minimal example is the following:
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("")
来源:https://stackoverflow.com/questions/36160934/type-of-optionals-cannot-be-inferred-correctly-in-swift-2-2