Type of optionals cannot be inferred correctly in swift 2.2

别说谁变了你拦得住时间么 提交于 2019-12-09 03:32:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!