【问题标题】:return json data split up into different values Swift 4返回 json 数据拆分为不同的值 Swift 4
【发布时间】:2018-01-15 17:03:45
【问题描述】:

目前我们有以这种格式返回的 json 值

 "CSS_RGB__c": "rgb(190,102,123)",

我正在尝试将这些值转换为单独的 ,r,g,b 值(例如 r = 190, g = 102, b = 123)

以前这行得通:

if let raw = dictionary["CSS_RGB__c"] as? NSString {
    let filtered = raw.substring(from: 4).trimmingCharacters(in: CharacterSet(charactersIn: ")"))
    var values = filtered.components(separatedBy: ",")
    if values.count == 3 {
        self["r"] = NSString(string: values[0]).floatValue as NSNumber?
        self["g"] = NSString(string: values[1]).floatValue as NSNumber?
        self["b"] = NSString(string: values[2]).floatValue as NSNumber?
    }
}

但是使用 swift 4 解析 json 的新方法我不完全确定如何拆分值:

struct Family: Codable {
 let cssRGBC: String

  enum CodingKeys: String, CodingKey {
   case cssRGBC = "CSS_RGB__c"
}
}

【问题讨论】:

    标签: json swift parsing swift4 codable


    【解决方案1】:

    您可以使用正则表达式在两个字符串之间查找字符串,映射其范围以提取结果,使用components(separatedBy: ",") 获取 rgb 组件并从字符串中初始化一个新整数,如果存在则修剪空格:

    let raw = "rgb(190,102,123)"
    let regexPattern = "(?<=rgb\\()(.*)(?=\\))"
    if let rgb = raw.range(of: regexPattern, options: .regularExpression)
        .map({String(raw[$0])})?
        .components(separatedBy: ",")
        .flatMap({Int($0.trimmingCharacters(in: .whitespaces))}){
        print(rgb)  // "[190, 102, 123]\n"
    }
    

    【讨论】:

    • 这很好,如果我需要单独的 r,g,b 的值怎么办,比如 r = 190, g = 102 等
    • rgb[0], rgb[1], rgb[2]
    猜你喜欢
    • 2018-04-28
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    • 2018-10-04
    • 1970-01-01
    • 2018-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多