Downcast element when reading from Dictionary in Swift -
i'm trying access element dictionary element , downcast type other anyobject maintain getting same compiler error: could not find overload 'subscript' accepts supplied arguments.
i know can using 2 if statements so:
if allow x = dict["key"] { if allow y = x as? string { // ... } } but sense there has more elegant solution this. format makes sense me is:
if allow x = dict["key"] as? string { // ... } but results in error, mentioned above. i've tried dozens of variations of this, none of seems create difference. can't done in swift?
the reason desired formulation isn't working you're trying disclose 2 optionals single as?. there 2 optionals because both subscripting of dictionary , attempted cast string homecoming optional values. there isn't way in 1 if statement runtime-safe, there way:
if allow x = dict["key"]! as? string { println(x) } the problem if dict["key"] ends beingness nil, forced unwrapping crash app. improve way (you can skip first if), if step:
let x: anyobject? = dict["key"] if allow y = x as? string { println(y) } the step cost of working dictionary<string, anyobject> - if can dictionary type more specific, won't have more.
dictionary swift downcast
No comments:
Post a Comment