Fast optional chaining with NSDictionary

Please help remake this

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

      

into optional chaining syntax on one line. I tried to do it like this:

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

      

and got the error:

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

      

This is my function header:

func getFieldForCode(code: String) -> NSDictionary? 

      

Is it possible? I ask this because when 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 advice?

+3


source to share


1 answer


You cannot pass it directly to String

, because you are pulling it from NSDictionary

and as the error says String

does not match NSCopying

. However, it String

connects to NSString

and NSString

does a match NSCopying

. So, with a little bit of castings / bridges, you can make it work like this:

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

      



Note. ... If you use this in an optional binding (as you want), remember to leave the type declaration ?

from stored_value

:

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

      

+2


source







All Articles