1

I am trying to get "readerSession" from an associative array and put it into a variable. This is what I've tried.

Code

println(thevalue)

Returned

{
    readerSession = 41;
    tax = 7;
    tax2 = 6;
    taxName = GST;
    taxName2 = PST;
}

So readerSession is equal to 41, now lets see if I can get ahold of it.

Code

println(thevalue["readerSession"])

Returned Optional(41)

Ok great, exactly what I want, now I'll try to put it into a variable.

Code

var readerSession = thevalue["readerSession"] as? String ?? "0"
println("READER SESSION \(readerSession) ")

Returned READER SESSION 0

Why is it "0"??? It should be "41"

1 Answer 1

1

The reason that you get "0" is because the value stored in the associative array is an Int, not a String. Therefore, when you try casting to String the cast returns null, so the right-hand side of the ?? kicks in, and you get a zero string.

You can fix it like this:

var readerSession : AnyObject = thevalue["readerSession"] ?? "0"
Sign up to request clarification or add additional context in comments.

2 Comments

but this way readerSession is sometimes an NSNumber and sometimes an NSString, which cannot be a good design
@newacct I agree - this is only a workaround for the given design.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.