【问题标题】:ios Swift 2 read and return item in CSV file Arrayios Swift 2读取并返回CSV文件数组中的项目
【发布时间】:2016-05-20 01:26:05
【问题描述】:

抱歉,我的 Swift 2 知识非常基础。 我正在尝试将条码扫描器返回的字符串 foundCode(code: String) 替换为其在已加载的 CSV 文件的标题 (default_code) 中的对应字符串,并将其返回到另一个视图控制器中的 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) 吗?

【问题讨论】:

    标签: ios arrays swift csv barcode


    【解决方案1】:

    你想要这样吗?

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

    【讨论】:

    • 谢谢,但在声明错误之前我得到了使用局部变量'getDefaultCode'。如何实现您的示例?
    • getDefaultCode 是一个函数,只是把它放在你的函数之外
    • 哦,这完全正确地说明了您的答案。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-08
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 2017-01-01
    • 1970-01-01
    相关资源
    最近更新 更多