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

时间:2018-09-20 18:01:04

标签: swift linux

我正在尝试使用CSwiftV库在linux上读取csv文件,但是最令我感兴趣的返回类型是可选的字典数组。我一直在努力了解如何使用下标来访问数组的内容。使用库最基本的示例(如果已安装马拉松,只需将其复制并复制到文件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)

到目前为止很好,但是现在当我尝试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]]'
  • 在这种情况下(我正在考虑类似于csv.keyedRows[0]["Year"]的东西)如何访问字典数据?

1 个答案:

答案 0 :(得分:1)

为此:

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

您可以使用可选绑定:

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

或者您可以使用后缀?运算符:

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