【问题标题】:Swift compiler error using dictionary lookup and cast in optional bindingSwift 编译器错误使用字典查找并强制转换为可选绑定
【发布时间】:2014-09-26 01:06:46
【问题描述】:

我正在从主要NSBundleinfoDictionary 属性进行字典查找。这可以正常工作:

let infoDict = NSBundle.mainBundle().infoDictionary
var item = infoDict["CFBundleExecutable"]
if let stringValue = item as? String {
   ...
}

但是,我想把它们串起来。但是,当我这样做时,我收到一个编译器错误:

if let stringValue = NSBundle.mainBundle().infoDictionary["CFBundleExecutable"] as? String {
    ...
}

错误是:

'String' is not a subtype of '(NSObject, AnyObject)'

我意识到这是那些神秘的 Swift 编译器消息之一,它意味着比它明确声明的更微不足道的东西 - 但我无法确定我上面的两个代码 sn-ps 有何不同 - 为什么一个有效,一个无效.

【问题讨论】:

    标签: macos swift


    【解决方案1】:

    String 不是对象;改用NSString

    if let stringValue = NSBundle.mainBundle().infoDictionary["CFBundleExecutable"] as? NSString {
        ...
    }
    

    如果您希望 stringValue 成为 String 而不是 NSString

    if let stringValue:String = NSBundle.mainBundle().infoDictionary["CFBundleExecutable"] as? NSString {
        ...
    }
    

    【讨论】:

    • 是的,确实如此。我一直忘记String 是一个结构。谢谢!
    猜你喜欢
    • 2015-11-05
    • 1970-01-01
    • 1970-01-01
    • 2017-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-25
    相关资源
    最近更新 更多