Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get from AnyObject(NSString) to String

I am reading a plist key (NSArray with n NSDictionaries):

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

now I iterate over it:

    for regionToMonitor in regionsToMonitor {

and now I want to to get uuidString of the regionToMonitor

in ObjC: NSString *uuidString = regionToMonitor[@"uuidString"];

in swift I try: let uuidString = regionToMonitor["uuid"]!.stringValue;

the above does compile but the string is always nil in swift. regionToMonitor["uuid"] when used without !.stringValue works fine in println

how do I get a valid Swift.String here?

I am trying to pass it to NSUUID!


I also tried

let uuidString:String = regionToMonitor["uuid"]
=> AnyObject isn't convertible to String

let uuidString = regionToMonitor["uuid"] as String
=> Could not find an overload for 'subscript' that accepts the supplied arguments

let uuidString = regionToMonitor["uuid"];
=> 'AnyObject?' cannot be implicitly downcast to 'String'; did you mean to use 'as' to force downcast?

like image 667
Daij-Djan Avatar asked Jun 03 '14 00:06

Daij-Djan


2 Answers

I ended up with the ugly line:

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

no warnings, no errors, no runtime error

like image 123
Daij-Djan Avatar answered Sep 16 '22 21:09

Daij-Djan


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.

like image 33
Amitay Avatar answered Sep 18 '22 21:09

Amitay