• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Noob Swift frustration with dicts and optionals
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Noob Swift frustration with dicts and optionals


  • Subject: Noob Swift frustration with dicts and optionals
  • From: Jens Alfke <email@hidden>
  • Date: Wed, 17 Sep 2014 09:58:12 -0700

Could someone explain this weird Swift error to me? I've figured out how to get around it, but I'd like to understand why it's occurring, since the description makes no sense to me. (The larger context of this is some code that extracts values from an NSDictionary parsed from JSON, carefully using optionals to avoid crashing on invalid input data.)

Here's an actual playground you can try out:

import Foundation
var dict = [NSObject:AnyObject]()
dict["foo"] = "bar"

let val = dict["foo"]        // result is {Some "bar"}
let val2 = val as? String        // result is {Some "bar"}

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. Also, the type of `dict["foo"]` _is too_ an optional, as shown in the results column of the playground. And where did the tuple mentioned in the error come from?

The utterly unintuitive fix is to change 'String' in the last line to 'NSString'. Then it compiles and produces the expected result. WTF?!?

—Jens


 _______________________________________________
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

  • Follow-Ups:
    • Re: Noob Swift frustration with dicts and optionals
      • From: Marco S Hyman <email@hidden>
    • Re: Noob Swift frustration with dicts and optionals
      • From: Cody Garvin <email@hidden>
  • Prev by Date: Re: Adding Swift-bridging hints in Obj-C headers?
  • Next by Date: Re: Noob Swift frustration with dicts and optionals
  • Previous by thread: Re: Adding Swift-bridging hints in Obj-C headers?
  • Next by thread: Re: Noob Swift frustration with dicts and optionals
  • Index(es):
    • Date
    • Thread