快速从数组对象获取特定值

时间:2019-05-11 06:39:38

标签: arrays swift

我想从该数组中获取交易ID的值。

这是我的数组:

["{
transaction_id:1894934,
 pin:0534552925794805, 
serial:20236031783146920986
}",
 "{transaction_id:1894935,
 pin:0665208961850777,
 serial:20236031783146920987}"]

我如何从中获取交易ID的价值? 看来数组中的对象和我的值都以这种格式存储,所以,如何检索特定值?

1 个答案:

答案 0 :(得分:1)

这是一种非常特别的格式,是伪JSON字符串数组。伪的,因为它们无效,所以必须将密钥用双引号引起来。

可能的解决方案是使用transaction_id提取Scanner的值

let array = ["{transaction_id:1894934,pin:0534552925794805,serial:20236031783146920986}","{transaction_id:1894935,pin:0665208961850777,serial:20236031783146920987}"]

let identifiers = array.compactMap{ string -> Int? in
    let scanner = Scanner(string: string)
    var value = 0
    guard scanner.scanCharacters(from: CharacterSet.decimalDigits.inverted, into: nil),
        scanner.scanInt(&value) else { return nil }
    return value
}

print(identifiers)

要将字符串转换为字典,请使用正则表达式

let transactions = array.map{ string -> [String:String] in
    let regex = try! NSRegularExpression(pattern: "(\\w+):(\\d+)")
    var result = [String:String]()
    let matches = regex.matches(in: string, range: NSRange(string.startIndex..., in: string))
    for match in matches {
        let keyRange = Range(match.range(at: 1), in: string)!
        let valueRange = Range(match.range(at: 2), in: string)!
        result[String(string[keyRange])] = String(string[valueRange])
    }
    return result
}