Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/gwt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何安全地使用可选绑定_Ios_Swift - Fatal编程技术网

Ios 如何安全地使用可选绑定

Ios 如何安全地使用可选绑定,ios,swift,Ios,Swift,经过很长时间之后,我构建了makeResult以显示在标签中,但问题是这里的代码太多了。如何减少代码 @IBAction func value_Array(_ sender: AnyObject) { var hobbies = [String]() // print(jsondata["hobbies"]) hobbies = jsondata["hobbies"] as! [String]

经过很长时间之后,我构建了
makeResult
以显示在
标签中,但问题是这里的代码太多了。如何减少代码

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

注意:由于我必须打开
爱好
无论如何,如何使用可选绑定安全地进行操作。

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

@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)"
  }
}
使用内部
索引
变量的另一种方法是首先将索引和爱好压缩到一个元组中。但这使得字符串创建行更加复杂;你的选择

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

我认为这是你想要的安全和简洁

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

太好了,你的问题是什么?@JAL谢谢。我如何减少代码?你应该让你的代码更安全,而不是更短。PS:而且
(键,值)
实际上是
(索引,值)
提示:使用
映射(…)
加入(…)
非常感谢。。。我在等待这种解决方案