gpt4 book ai didi

macos - 使用字典查找和强制转换可选绑定(bind)时出现 Swift 编译器错误

转载 作者:行者123 更新时间:2023-11-30 10:21:50 24 4
gpt4 key购买 nike

我正在从主 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”不是“(NSObject, AnyObject)”的子类型

我意识到这是那些神秘的 Swift 编译器消息之一,它的含义比它明确指出的要微不足道得多 - 但我无法确定我上面的两个代码片段有何不同 - 为什么一个有效,另一个无效。

最佳答案

String 不是一个对象;使用 NSString 代替:

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

如果您希望 stringValueString 而不是 NSString:

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

关于macos - 使用字典查找和强制转换可选绑定(bind)时出现 Swift 编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26050523/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com