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
Swift uses type inference extensively, allowing you to omit the type or part of the type of many variables and expressions in your code. For example, instead of writing var x: Int = 0, you can write var x = 0, omitting the type completely—the compiler correctly infers that x names a value of type Int.
Swift optional variables make code safer if you forget to give an initial value to a variable. The swift optional variable can have a value or be nil if have no value. But in real programming, we need to get the original value that is wrapped by the optional variable.
Unlike Any, which is defined by the language, AnyObject is defined by the Swift standard library. For more information, see Class-Only Protocols and AnyObject. The Self type isn’t a specific type, but rather lets you conveniently refer to the current type without repeating or knowing that type’s name.
Named types include classes, structures, enumerations, and protocols. For example, instances of a user-defined class named MyClass have the type MyClass. In addition to user-defined named types, the Swift standard library defines many commonly used named types, including those that represent arrays, dictionaries, and optional values.
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("")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With