如何从swift 3中的子字符串中获取整数?

时间:2018-02-02 12:34:39

标签: ios string swift3

这里我有一个类似于"{\"label\":\"57-175\",\"stock\":0}"的字符串,其中我需要将57175作为整数,并且我需要将其与数组编号进行比较但是在截断之后从字符串我无法得到整数的形式,我试图得到整数它返回nil如果我试图得到字符串它返回可选(57)或可选(175)两个数字和提到的数字需要是与下面数组中的整数相比,我试过的代码可以帮助我解决这个问题吗?

for item in (self.detailModel?.extensionAttribute?.productStock)! {
    let start = item.index(item.startIndex, offsetBy: 10)
    print(start)

    let end         = item.index(item.endIndex, offsetBy: -12)
    let range       = start..<end
    let mySubstring = item[range]
    let myString    = String(mySubstring)
    print(myString)

    let stockStart     = item.index(item.startIndex, offsetBy: 18)
    let stockEnd       = item.index(item.endIndex, offsetBy: -1)
    let stockRange     = stockStart..<stockEnd
    let stockSubString = item[stockRange]
    let stockString    = String(stockSubString)
    print(stockString)

    if stockString ==  "\"stock\":0" {
        let startSize  = myString?.prefix(2)
        let sizeString = String(describing: startSize)
        print(sizeString)

        let color   = sizeString.replacingOccurrences(of: "\"", with: "")
        self.colorNumber = color
        let endSize = myString?.suffix(3)
        let string  = String(describing: endSize)
        print(string)

        let size = string.replacingOccurrences(of: "\"", with: "")
        self.sizeNumber = size
        print(self.sizeNumber)

        for item in self.configurableArray {
            for (key, array) in item {
                if (self.colorNumber?.contains("\(key)"))! {
                    print(Int(self.sizeNumber!))
                    let farray = array.filter {
                        $0 != Int(self.sizeNumber!) 
                    }
                }

                print(self.colorNumber!)
                print(key)
                print(self.configurableArray)
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

快速而肮脏的方式:

let jsonData = jsonString.data(using: .utf8)!
let jsonDictionary = try JSONSerialization.jsonObject(with: jsonData, options: []) as! [String: Any]
let labelString = jsonDictionary["label"] as! String
let labelNumberArray = labelString.components(separatedBy: "-").map({ Int($0) })
let number1 = labelNumberArray[0]!
let number2 = labelNumberArray[1]!

我建议使用guard或if语句,而不是像上面的代码那样强制解包所有内容:

guard let jsonData = jsonString.data(using: .utf8),
    let jsonDictionary = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any],
    let stock = jsonDictionary["stock"] as? NSNumber,
    let labelString = jsonDictionary["label"] as? String else {
    //return or throw expection
}

let labelNumberArray = labelString.components(separatedBy: "-").flatMap({ Int($0) })

guard labelNumberArray.count == 2 else {
    //return or throw expection
}

let labelNumber1 = labelNumberArray[0]
let labelNumber2 = labelNumberArray[1]
let stockNumber = stock.intValue