如何转换为String - 从Swift 1.1更新到Swift 1.2

时间:2015-09-28 19:23:20

标签: swift casting optional

let version:String = NSBundle.mainBundle().objectForInfoDictionaryKey(kCFBundleVersionKey) as? String ?? "unknown"

我收到错误:'(String?,StringLiteralConvertible)'无法转换为'StringLiteralConvertible'

2 个答案:

答案 0 :(得分:1)

Xcode 7有更好的错误消息:

error: 'CFString!' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?

并制作"修复它"插入as String的建议:

let version = NSBundle.mainBundle()
    .objectForInfoDictionaryKey(kCFBundleVersionKey as String)
    as? String ?? "unknown"

这与Swift 1.2(Xcode 6.4)和当前版本都进行了编译 Swift 2.0(Xcode 7)。

答案 1 :(得分:0)

这个怎么样:

var version = "unknown"
if let key = NSBundle.mainBundle().objectForInfoDictionaryKey(kCFBundleVersionKey) as String {
    version = key
}