ios Swift 2读取并返回CSV文件数组中的项目

时间:2016-05-20 01:26:06

标签: ios arrays swift csv barcode

提前抱歉我的Swift 2知识非常基础。 我试图将条形码扫描器foundCode(code:String)返回的字符串替换为标题(default_code)中加载的CSV文件中的对应字符串,并将其返回到另一个viewcontroller中的UItextField。

我可以使用原始字符串成功扫描和segue,但aRow的输出会打印整个CSV文件;

Segue!
"Barcode Found: 9312311903002
["code": "code", "default_code": "default_code"]
["code": "9310097003060", "default_code": "1A1ALG"]
["code": "9310097003121", "default_code": "1A1ASG"]
["code": "9310097390801", "default_code": "1A1BS"]
["code": "9310097390702", "default_code": "1A1BU"]
......."

我的功能如下:

func foundCode(code: String) {
    print("Barcode Found: \(code)")


var myCSVContents = Array<Dictionary<String, String>>()

    CSVScanner.runFunctionOnRowsFromFile(["code", "default_code"], withFileName: "products", withFunction: {

        (aRow:Dictionary<String, String>) in

        myCSVContents.append(aRow)

        print (aRow)

    })


    self.delegate?.barcodeReaded(code)


    navigationController?.popViewControllerAnimated(true)
    }

有人可以帮我解决如何在数组中使用(代码)获取单个项目并返回(default_code)吗?

1 个答案:

答案 0 :(得分:0)

你想要这样吗?

override func viewDidLoad() {
    super.viewDidLoad()

    let array = [  ["code": "9310097003060", "default_code": "1A1ALG"],
        ["code": "9310097003121", "default_code": "1A1ASG"],
        ["code": "9310097390801", "default_code": "1A1BS"],
        ["code": "9310097390702", "default_code": "1A1BU"] ]

    let str = "9310097003060"


    let defaultcode = getDefaultCode(array, code: str)
    print(defaultcode)

}


func getDefaultCode(array:[Dictionary<String,String>] , code:String) -> String?{
    let array2 =  array.filter({$0["code"] == code})

    return array2.last?["default_code"]
}