Re: Noob Swift frustration with dicts and optionals
Re: Noob Swift frustration with dicts and optionals
- Subject: Re: Noob Swift frustration with dicts and optionals
- From: Marco S Hyman <email@hidden>
- Date: Wed, 17 Sep 2014 10:34:06 -0700
On Sep 17, 2014, at 9:58 AM, Jens Alfke <email@hidden> wrote:
> Could someone explain this weird Swift error to me?
The error you are getting is due to an extraneous ?. However,
fixing that changes the error instead of eliminating it.
> let val3 = dict["foo"]? as? String // <—error
>
> The error is "Operand of postfix '?' should have optional type; type is '(NSObject, AnyObject)'
>
> I don't understand why this fails, since that line is really just a combination of the two previous lines merged into one statement.
Get rid of the ? after dict["foo"]. It is not necessary. Yes,
the return value is an optional. That's fine. It means that
val3 is an optional that must be unwrapped before use. The doc says:
--------
Use subscripting to access the individual elements in any dictionary. The value returned from a dictionary's subscript is of type ValueType?—an optional with an underlying type of the dictionary’s ValueType:
• var dictionary = ["one": 1, "two": 2, "three": 3]
• let value = dictionary["two"]
• // value is an optional integer with an underlying value of 2
--------
let val3 = dict["foo"] as? String
now generates the error 'String' is not a subtype of '(NSObject, AnyObject)' which goes to show that String and NSString aren't as
equivalent as one would hope. As you found changing the code to
let val3 = dict["foo"] as? NSString
gives you an optional NSString as your result. To use it you might
want something like
if let val3 = dict["foo"] as? NSString {
// val3 is unwrapped and safe to use
println(val3)
}
"bar" is printed.
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Xcode-users mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden