0
votes

I'm a bit new to swift optionals and am looking for a graceful way of dealing with transforming optionals to non-optionals in a map function.

I'd like my map transformation to not include nulls and also to have the most succint optionals syntax.

let result = JSON as? [Dictionary<String,String>]

//how can I avoid the result != nil check here with a more graceful optionals syntax
if (result != nil && response!.statusCode == 200 && error == nil){
    let strHighlights = result!.map { json in
        //is there a more 'optionals' syntax for this so that it doesn't return nulls in the map?
        return json["uname"]!  //i would like to avoid the bang! here as that could cause an error
    }
    callback(success: true ,errorMsg: nil, highlights:strHighlights)
}
else{
    callback(success: false,errorMsg:error?.localizedDescription, highlights:[])
}

Can I do this more gracefully than checking to see if result != nil in the 3rd line? Also, in the map function I'd prefer not to do the hard ! cast in the json["uname"] in case it doesn't exist. Can I use optional syntax to gracefully ignore a nil value in that optional so that it doesn't get returned in the map? I can do a json["uname"] != nil check but that seems a bit verbose and makes me wonder if there is a more succint optionals syntax in swift for that.

1

1 Answers

1
votes

I think this is what you want:

if let result = result, response = response
    where response.statusCode == 200 && error == nil {
        let strHighlights = result.reduce([String]()) { array, json in
            if let name = json["uname"] {
                return array + [name]
            } else {
                return array
            }
        }
        callback(success: true ,errorMsg: nil, highlights:strHighlights)
} else {
    callback(success: false,errorMsg:error?.localizedDescription, highlights:[])
}

(No exclamation marks required)

Oh and btw: Every kind of those functions (map, filter, reversed, ... Can be expressed in a single reduce function. Also combinations of them can often be represented with a single reduce function.