John Kakon
John Kakon

Reputation: 2541

Swift optional chaining with NSDictionary

Please help to remake this

 if let field = parent_obj?.getFieldForCode(code) {
    if let stored_value = field["value"] as? String {

into optional chaining syntax in single line. I tried to do it like this:

let stored_value = parent_obj?.getFieldForCode(code)?["value"] as? String

and got an error:

Type 'String' does not conform to protocol 'NSCopying'

This is my function header:

func getFieldForCode(code: String) -> NSDictionary? 

Is it possible? I ask it because any time I work with NSArrays and NSDictionaries my code looks terrible:

if let code = self.row_info["code"] as? String {
        if let value_field = self.row_info["value_field"] as? String {
            if let field = parent_obj?.getFieldForCode(code) {
                if let stored_value = field["value"] as? String {
                    if let fields = self.fields_set{
                        if let current_value = fields[indexPath.row][value_field] as? String {

Any advices?

Upvotes: 3

Views: 244

Answers (1)

Mike S
Mike S

Reputation: 42325

You can't cast it directly to a String because you're pulling it from an NSDictionary and, like the error says, String doesn't conform to NSCopying. However, String is bridged to NSString, and NSString does conform to NSCopying. So, with a little bit of casting/bridging trickery, you can make it work like this:

let stored_value: String? = parent_obj?.getFieldForCode(code)?["value"] as? NSString

Note: If you're using this in an optional binding (which it looks like you want to), don't forget to drop the ? from stored_value's type declaration:

if let stored_value: String = parent_obj?.getFieldForCode(code)?["value"] as? NSString {
    /* ... */
}

Upvotes: 2

Related Questions