Get from AnyObject(NSString) to String

45,493

Solution 1

I ended up with the ugly line:

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

no warnings, no errors, no runtime error

Solution 2

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.

Solution 3

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. :)

Solution 4

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.

Solution 5

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.

Share:
45,493
Daij-Djan
Author by

Daij-Djan

OSX &amp; iOS Dev from Cologne, Germany. Now living in the Bay Area The wheel weaves as the wheel wants -- Wheel Of Time by R. Jordan

Updated on July 21, 2022

Comments

  • Daij-Djan
    Daij-Djan almost 2 years

    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?

  • rickster
    rickster almost 10 years
    Try removing some of the extra downcasting (as ...) you're doing before accessing the dictionary - this might be an issue with inferred types.
  • Leandros
    Leandros almost 10 years
    I'am not completely sure about, what the NSBundle returns here. The first method does indeed work (but not without a warning), the second doesn't (not just because you're missing a parenthesis).
  • rickster
    rickster almost 10 years
    Cmd-click NSBundle in your code to see its Swift declarations. (Xcode automagically Swift-ifies the header on demand, with comments.) That might help track down type issues.
  • rickster
    rickster almost 10 years
    As for missing parens... clearly someone needs to figure out how to embed SO in a playground or vice versa. :D
  • Leandros
    Leandros almost 10 years
    var regions = NSBundle.mainBundle().infoDictionary["Regions"] is AnyObject?, but it contains an NSArray with zero entries. It definitely doesn't work without downcast.
  • Leandros
    Leandros almost 10 years
    You can't println a Dictionary like this, I said it doesn't work, not because of parens. ;) I have no clue why, but it doesn't work. Test it out in the PlayGround.
  • Daij-Djan
    Daij-Djan almost 10 years
    correction: if do this + a println -- the whole thing comes crashing don EXC_INVOP on reading the plist
  • tng
    tng almost 10 years
    Doing this causes my swift process to crash with error 254. See stackoverflow.com/questions/24154163/… for details.
  • gerarddp
    gerarddp over 9 years
    Why do you need to type uuidString, won't it be the same if you do var uuidString = regionToMonitor["uuid"] as String!
  • Daij-Djan
    Daij-Djan over 9 years
    in the beta I developed this for, not typing it CRASHED :)
  • sudo
    sudo almost 9 years
    By the way, if regionToMonitor were an optional NSDictionary or Dictionary, Xcode 6.3 would say that AnyObject? cannot be cast to String, which is misleading.
  • Igor Pantović
    Igor Pantović almost 9 years
    @sudo Your comment got me out of 20 minute error search. Indeed, XCode is reporting totally unrelated error, I had to add regionToMonitor!["blah"] and tadaaaaa....no errors :)
  • Stephen Rauch
    Stephen Rauch over 7 years
    Welcome to Stack Overflow! I recommend you take the tour. When giving an answer it is preferable to give some explanation as to WHY your answer is the one.