Get from AnyObject(NSString) to String

喜你入骨 提交于 2019-11-30 03:23:05
Daij-Djan

I ended up with the ugly line:

var uuidString:String = regionToMonitor["uuid"] as! String

no warnings, no errors, no runtime error

I found this to work for me

var uuidString: String? = regionToMonitor["uuid"] as AnyObject? as? String

EDIT: this was the answer for an older swift version

Please use the accepted answer.

AnyObject? is an optional, because the dictionary may or may not contain a value for the "uuid" key. To get at an optional's value, you have to unwrap it. See Optionals in the documentation.

The safest way to deal with an optional is to put it in a conditional statement.

if let uuidString = regionToMonitor["uuid"] {
    // do something with uuidString
}

If you're absolutely positively sure the dictionary will always contain this key/value pair, you can use an implicitly unwrapped optional (the ! suffix):

println("UUID: \(regionToMonitor["uuid"]!)")       

In this case, if there's no value for the key your app will crash.

If you use ! a lot, it looks like you're yelling all the time... which might help illustrate why you should use it sparingly, if at all. :)

I've found a working solution, which compiles without warnings and such:

var regions = NSBundle.mainBundle().infoDictionary["Regions"] as Array<Dictionary<String, AnyObject>>

for region in regions {
    let dict: NSDictionary = region
    var uuid = dict["uuidString"] as String
}

The infoDictionary from the NSBundle returns an NSArray and NSDictionary, not a Swift.Array or Swift.Dictionary. Though, they should be interchangeable, but maybe they aren't as we though.

I am not sure my solution is effective of not but here it is.

var uuidVar = regionToMonitor["uuid"]
var uuidString:String = "\(uuidVar)"

Hope it helps.

You can also use

var uuidString = regionToMonitor["uuid"]? as String

It has the same results as what you are doing, but is IMHO more clear in intent. The as operator force unwraps anyway, so putting the exclamation mark behind it feels redundant. Putting the question mark behind the dictionary subscript makes it clear you are chaining an optional.

If you are sure you want the unwrapped value you can use any of these:

var uuidString:String! = regionToMonitor["uuid"]
var uuidString = regionToMonitor["uuid"] as String!

or even this:

if var uuidString = regionToMonitor["uuid"] {
    println("\(uuidString) has been unwrapped")
}

Keep it simple:

let uuidString = "\(regionToMonitor["uuid"])"
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!