ios - 检索 JSON 对象并填充数组 Swift

标签 ios arrays swift

我有一个这种结构的 json 对象:

[
    {
        "id": 1,
        "seat_no": 6
    },
    {
        "id": 2,
        "seat_no": 27
    }
]

主要的挑战是我需要获取 seat_no 并将其添加到我稍后将使用的 int 数组中:

func getReserved() -> [Int] {
  var reservedSeatsJSON : JSON = JSON()
  var seats = Int()
  var reservedSeats = [Int]()

  for item in reservedSeatsJSON.array! {
     seats = item["seat_no"].int!
     reservedSeats.append(seats)
     self.reservedSeatsLabel.text = "Reserved(\(reservedSeatsJSON.array!.count))"
  }
  return reservedSeats      
}              

每次我运行它时,reservedSeats 都会返回空的。这里的主要思想是我需要在 for 循环中填充一个 int 数组并在 for 循环外返回填充的数组

最佳答案

首先检查 reservedSeatsJSON json 是否包含实际的 JSON?

如果它包含实际的 JSON 则按如下方式执行。简短的方法。

func getReserved() -> [Int] {
     var reservedSeatsJSON : JSON = JSON()
     self.reservedSeatsLabel.text = "Reserved(\(reservedSeatsJSON.array.count))" 

     return reservedSeatsJSON.arrayValue.map { $0["seat_no"].intValue }
}

关于ios - 检索 JSON 对象并填充数组 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48333025/

相关文章:

iOS 模拟器不使用与 OS X 相同的布局

ios - react native 可滚动选项卡 View onchange

ios - 静音按钮不会使 AVAudioPlayer 静音

swift - 在枚举中传递数组

swift - Firebase 连接状态在第一次运行时总是返回 false

IOS 警告 : Unable to allocate render buffer storage

java - 您如何在 Blackberry Java 应用程序中遍历和存储 XML?

ios - 尝试将 UIImage 数组加载到 UITableView 时,Swift 3 错误 : "Argument labels ' (named:_:, _ :, )' do not match any available overloads"

javascript - 将值从代码隐藏传递给 js

ios - 每次我滚动 cell.viewWithTag 都会在展开发现 nil 时给出 fatal error