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

我可以使用原始字符串成功扫描和搜索,但是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)
    }


有人可以协助我如何使用(code)获得单个项目并在数组中返回(default_code)吗?

最佳答案

你想要这样吗?

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"]
}

关于ios - ios Swift 2读取并返回CSV文件数组中的项目,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37336528/

10-09 18:21
查看更多