简体   繁体   English

如何在可选的字典数组中使用下标

[英]How to use subscripts in an Optional Array of Dictionary

I am attempting to read a csv file on linux using the CSwiftV library, however the returned type that interests me the most is an optional array of dictionaries. 我正在尝试使用CSwiftV库在linux上读取csv文件,但是最令我感兴趣的返回类型是可选的字典数组。 I have been struggling to understand how to use subscripting to access the contents of the Array. 我一直在努力了解如何使用下标来访问数组的内容。 Using the library most basic example (if you have marathon installed, just copy on a file and marathon run ): 使用库最基本的示例(如果已安装marathon,只需将其复制到文件上并marathon run ):

import CSwiftV // marathon: https://github.com/Daniel1of1/CSwiftV.git

let inputString = "Year,Make,Model,Description,Price\r\n1997,Ford,E350,descrition,3000.00\r\n1999,Chevy,Venture,another description,4900.00\r\n"

let csv = CSwiftV(with: inputString)

let rows = csv.rows // [
                    //  ["1997","Ford","E350","descrition","3000.00"],
                    //  ["1999","Chevy","Venture","another description","4900.00"]
                    // ]

let headers = csv.headers // ["Year","Make","Model","Description","Price"]

let keyedRows = csv.keyedRows // [
                              //  ["Year":"1997","Make":"Ford","Model":"E350","Description":"descrition","Price":"3000.00"],
                              //  ["Year":"1999","Make":"Chevy","Model":"Venture","Description":"another, description","Price":"4900.00"]
                              // ]

print(csv.rows)
print(csv.headers)
print(csv.keyedRows)

So far so good, but now when I try print(csv.keyedRows[0][0]) or print(csv.keyedRows[[0]]) I get something like: 到目前为止, print(csv.keyedRows[0][0])很好,但是现在当我尝试使用print(csv.keyedRows[0][0])print(csv.keyedRows[[0]])我得到的是:

   - 24:16: value of optional type '[[String : String]]?' must be unwrapped to refer to member 'subscript' of wrapped base type '[[String : String]]'
  • How can I access the dictionary data in this case (I am thinking on something similar to csv.keyedRows[0]["Year"] ) ? 在这种情况下,如何访问字典数据(我在考虑类似于csv.keyedRows[0]["Year"] )?

For this: 为了这:

print(csv.keyedRows[0]["Year"])

You can use optional binding: 您可以使用可选绑定:

if let keyedRows = csv.keyedRows {
    print(keyedRows[0]["Year"])
} else {
    // keyedRows is nil!
}

Or you can use the postfix ? 或者您可以使用后缀? operator: 运营商:

print(csv.keyedRows?[0]["Year"] as Any)
// or
print(csv.keyedRows?[0]["Year"] ?? "")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM