coderLife2 coderLife2 - 27 days ago 6
iOS Question

How do it safely with optional bindings

After all long time later i build

makeResult
to display in the
label
but problem it is to much code here . how can I reduce the code? .

@IBAction func value_Array(_ sender: AnyObject) {

var hobbies = [String]()

// print(jsondata["hobbies"])

hobbies = jsondata["hobbies"] as! [String]
var makeResult : String?
for (index, value) in hobbies.enumerated(){
print(value)
makeResult = (makeResult != nil ? "\(makeResult!) \n" : "") + " your \(index+ 1) is \(value)"

}
outputResult.text = makeResult != nil ? makeResult : " "
}


Note : Since I have to unwrap
hobbies
anyway how do it safely with optional bindings .

Answer

I think this does what you want safely and succinctly.

@IBAction func value_Array(_ sender: AnyObject) {

  guard let hobbies = jsondata["hobbies"] as? [String] else {
    outputResult.text = ""
    return
  }

  outputResult.text = hobbies.enumerated().map { index, element in
    return " your \(index + 1) is \(element)"
  }.joined(separator: " \n")
}
Comments