在Swift 2.2中无法正确推断出可选类型 [英] Type of optionals cannot be inferred correctly in swift 2.2

查看:132
本文介绍了在Swift 2.2中无法正确推断出可选类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:

在带有swift 2.2的Xcode 7.3下运行以下代码时,编译器无法正确推断可选类型:

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)

在我的Xcode 7.3上,这将打印I am an Int?

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?.

这将在以前的Xcode版本中打印I am a String?.

This would print I am a String? in the previous Xcode version.

您得到类似的结果吗?

观察:

使用此功能签名时会发生同样的情况:

The same occurs when using this function signature:

func whatAmI(property:AnyObject?)

-错误-

此问题是Swift 2.2中的回归: https://bugs.swift.org/browse/SR-1024

This issue is a regression in swift 2.2: https://bugs.swift.org/browse/SR-1024

推荐答案

这似乎是一个错误.最小的示例如下:

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("")

这篇关于在Swift 2.2中无法正确推断出可选类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆