目前我们有以这种格式返回的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"
}
}
答案 0 :(得分:1)
您可以使用正则表达式查找两个字符串之间的字符串,映射其范围以提取结果,使用components(separatedBy: ",")
获取rgb组件并从字符串中修剪新的整数(如果存在):< / p>
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"
}