Daij-Djan Daij-Djan - 1 year ago 55
Swift Question

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
in swift.
when used without !.stringValue works fine in

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?

Answer Source

I ended up with the ugly line:

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

no warnings, no errors, no runtime error