【问题标题】:Cannot subscript a value of type '[CustomObject]' with an index of type 'String'无法使用“String”类型的索引为“[CustomObject]”类型的值下标
【发布时间】:2017-10-26 21:43:07
【问题描述】:

我们将 json 数据放入自定义对象中:

 "sentMoney": [
                {
                    "amount": 3840.83,
                    "currency": "MXN",
                    "isMajor": false
                },
                {
                    "amount": 200,
                    "currency": "USD",
                    "isMajor": true
                }
        ]

public final class SentMoney: NSCoding {
  public var currency: String?
  public var isMajor: Bool? = false
  public var amount: Double?
}

然后在变量中引用自定义对象:

 public var sentMoney: [SentMoney]?

现在我们要做的只是获得第一个金额 (3840.83)。

我尝试过这样做,但出现错误:

 let amountsOnlyArray = self.postTransferSuccess?.sentMoney.map({ $0["amount"] })//Error -Cannot subscript a value of type '[SentMoney]' with an index of type 'String' 
 let firstAmountOnly = self.postTransferSuccess?.sentMoney![0]["amount"]//Error -Type 'BSentMoney' has no subscript members

有没有更好的方法来获得第一笔金额?

【问题讨论】:

    标签: ios arrays swift dictionary


    【解决方案1】:

    当您将变量 sentMoney 显式声明为 [SentMoney] 时,您可以在映射数组或索引元素时直接使用对象的属性,如下所示。

    let amountsOnlyArray = self.postTransferSuccess?.sentMoney.map({ $0.amount })
    

    let firstAmountOnly = self.postTransferSuccess?.sentMoney![0].amount
    

    【讨论】:

      【解决方案2】:

      看起来您正在将 JSON 解析为一个想要访问该对象的属性的对象。您应该使用点符号来访问它,例如$0.amount

      let amountsOnlyArray = self.postTransferSuccess?.sentMoney.map({ $0.amount })
      let firstAmountOnly = self.postTransferSuccess?.sentMoney![0].amount
      

      编辑

      这里有一个更全面的例子:

      class SentMoney {
          public var currency: String?
          public var isMajor: Bool? = false
          public var amount: Double?
      }
      
      let one = SentMoney()
      one.amount = 1.2
      
      let two = SentMoney()
      two.amount = 3.4
      
      let sentMoney = [one, two]
      
      let amountsOnlyArray = sentMoney.map({ $0.amount })
      
      amountsOnlyArray // [{some 1.2}, {some 3.4}]
      
      sentMoney.first?.amount // 1.2
      

      【讨论】:

      • 奇怪的是,第一行出现错误“'[SentMoney]' 类型的值没有成员'amount'”
      • 听起来你是直接在数组上调用.amount,而不是获取第一个对象。也许您可以分享您用来创建 SentMoney 对象数组的代码?
      • 第二个常量直接起作用,不需要第一个常量!
      猜你喜欢
      • 1970-01-01
      • 2017-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-19
      相关资源
      最近更新 更多