Leonardo Leonardo - 6 months ago 26
Swift Question

swift json null check

I'm poor at swift yet. (also English! Sorry!)

to check null in decoded json dictionary.

here is working code after search some tips.
but I think this code is very bad.

any idea to make this gorgeous code ?

var v_desc = ""
var v_sword = ""
var v_sortk = 0
for (_, value) in api_result {
if let ch_descr = value["description"] as? String {
v_desc = ch_descr
} else {
v_desc = ""
}
if let ch_sword = value["search_word"] as? String {
v_sword = ch_sword
} else {
v_sword = ""
}
if let ch_sortk = value["sort_key"] as? Int {
v_sortk = ch_sortk
} else {
v_sortk = 0
}

self.cell_data.append(aps_tag(catg_UID: value["ctag_UID"] as! Int, set_code: value["set_code"] as! Int, title: value["title"] as! String, description: v_desc, search_word: v_sword, nums: value["nums"] as! Int, sort_key: v_sortk))

}

Answer

Gorgeous is subjective but you can make it more concise with the nil-coalescing operator (??):

for (_, value) in api_result {
    let catg_UID = value["ctag_UID"] as! Int
    let set_code = value["set_code"] as! Int
    let title    = value["title"] as! String
    let nums     = value["nums"] as! Int

    let v_desc   = value["description"] as? String ?? ""
    let v_sword  = value["search_word"] as? String ?? ""
    let v_sortk  = value["sort_key"] as? Int ?? 0

    let aps_tag  = aps_tag(catg_UID: catg_UID, set_code: set_code, title: title, description: v_desc, search_word: v_sword, nums: nums, sort_key: v_sortk)
    self.cell_data.append(aps_tag)
}

Another thing: those snake_case variable and function names remind me a lot of C/C++. Doesn't look very Swifty to me but it's a personal preference.