【问题标题】:Formatting NSArray for Swift为 Swift 格式化 NSArray
【发布时间】:2020-04-24 14:12:16
【问题描述】:

我在格式化 NSArray 时遇到问题

let temp = json.value(forKeyPath: "data.current_condition.temp_F") as Any
                                                  
                            DispatchQueue.main.async {
                                self.setWeather(temp: temp as! NSArray  )
                              }
func setWeather(  temp: NSArray) {
          TempLabel.text = "\(temp)"

当我运行程序时,TempLabel 只显示“(”,因为它是 NSArray 形式。我不知道如何摆脱“(”。

【问题讨论】:

  • 请解释一下。你的问题很清楚
  • @nivritgupta 感谢您的反馈。编辑了问题。

标签: ios swift nsarray


【解决方案1】:

使用对象的描述在 UI 上显示它是非常脆弱的,并且可以在 iOS 内部随时更改。

我会尝试将 json 值的结果转换为 Swift 类型。在您的情况下,[Int] 应该可以工作。然后使用其中一种收集方法将 Int 数组转换为 String。

试试这样的:

let temp = json.value(forKeyPath: "data.current_condition.temp_F") as! [Int]
TempLabel.text = temp.map({ "\($0)" }).joined(separator: ", ")

【讨论】:

  • 谢谢。我很难理解 map 函数,所以 .map({ "($0)" }) 表示数组中的每个值,并且 .joined(separator: ", ") 是插入逗号 if [[1,2],[1.2] then [1,2,1,2]。但是在这种情况下它是如何工作的呢?
  • map 基本上采用数组的元素并使用方法对其进行转换。在我们的例子中 Int -> String 使用字符串插值:“($0)” ([1, 2, 3] -> ["1", "2", "3"])。 joined 是另一种使用分隔符 (["1", "2", "3"] -> ", ") 连接字符串数组元素的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-10
  • 1970-01-01
  • 2015-11-30
相关资源
最近更新 更多