Daij-Djan Daij-Djan - 3 months ago 14
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
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?

Answer

I ended up with the ugly line:

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

no warnings, no errors, no runtime error