nwales
nwales

Reputation: 3561

How to cast to String - updating from from Swift 1.1 to Swift 1.2

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

I'm getting an error: '(String?, StringLiteralConvertible)' is not convertible to 'StringLiteralConvertible'

Upvotes: 0

Views: 107

Answers (2)

Martin R
Martin R

Reputation: 539775

Xcode 7 has the better error message for the problem:

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

and makes the "Fix-it" suggestion to insert as String:

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

And this compiles both with Swift 1.2 (Xcode 6.4) and the current Swift 2.0 (Xcode 7).

Upvotes: 1

Code Different
Code Different

Reputation: 93161

How about this:

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

Upvotes: 0

Related Questions