无法下标类型' [CustomObject]'索引类型'字符串'

时间:2017-10-26 21:43:08

标签: ios arrays swift dictionary

我们将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]?

现在我们要做的只是获得FIRST金额(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

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

2 个答案:

答案 0 :(得分:0)

看起来您正在将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

答案 1 :(得分:0)

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

<html>
  <head>
    <meta name="viewport" content="width=device-width,height=device-height,user-scalable=no,maximum-scale=1.0,initial-scale=1.0" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <!-- ISO-8859-1 -->
    <title>Cordova Mobile Spec</title>

  </head>
  <body>
    <video width=100% height=100% id="player">
      <source src="http://myhaircolorgenie.com/content/genie/ClientConsultationTips1/HaircolorConsultationChecklist1.mp4">
      <meta property="og:video:secure_url" content="https://www.w3schools.com/tags/movie.mp4">
      <meta property="og:video:type" content="video/mp4">
    </video>
    <div>
      <button onclick="document.getElementById('player').play()"> play </button>
      <button onclick="document.getElementById('player').pause()"> pause </button>
    </div>
    <script>
      document.getElementById('player').play();
    </script>
  </body>
</html>

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