我对swift选项有点新意,我正在寻找一种优雅的方法来处理地图函数中非选项的变换选项。
我希望我的地图转换不包含空值,并且还有最多的succint选项语法。
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:[])
}
我可以更优雅地做到这一点,而不是检查结果!= nil在第3行?另外,在地图功能中,我不想做那么难!在json [&#34; uname&#34;]中施放,以防它不存在。我是否可以使用可选语法优雅地忽略该可选中的nil值,以便它不会在地图中返回?我可以进行json["uname"] != nil
检查,但这看起来有点冗长,让我想知道swift中是否有更多的succint选项语法。
答案 0 :(得分:1)
我认为这就是你想要的:
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:[])
}
(不需要感叹号)
哦,顺便说一下:各种功能(地图,过滤,反转,......都可以用单个reduce函数表示。它们的组合通常可以用一个reduce函数表示。