如何安全地使用可选绑定

时间:2016-11-07 13:16:25

标签: ios swift

经过很长一段时间后,我构建makeResult以显示在label但问题是这里有很多代码。我怎样才能减少代码?

   @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 : " "
        }

注意:因为我必须解开hobbies,所以如何安全地使用可选绑定。

2 个答案:

答案 0 :(得分:0)

这可能不会更小,但更安全。如果没有爱好数据,这不会崩溃。

@IBAction func value_Array(_ sender: AnyObject) {
  guard
    let hobbies = jsondata["hobbies"] as? [String],
    hobbies.count > 0
  else {
    outputResult.text = " "
    return
  }

  var index = 0
  outputResult.text = hobbies.reduce("") {
    index += 1
    return $0 + ($0.isEmpty ? "" : " \n") + " your \(index) is \($1)"
  }
}

使用内部index变量的另一种方法是首先将索引和爱好压缩到一个元组中。但这会使字符串创建线更复杂;你的选择。

@IBAction func value_Array(_ sender: AnyObject) {
  guard
    let hobbies = jsondata["hobbies"] as? [String],
    hobbies.count > 0
  else {
    outputResult.text = " "
    return
  }

  outputResult.text = zip([1...hobbies.count], hobbies).reduce("") {
    return $0 + ($0.isEmpty ? "" : " \n") + " your \($1.0) is \($1.1)"
  }
}

答案 1 :(得分:0)

我认为这可以安全,简洁地完成你想做的事。

@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")
}