我有一个看起来像这样的结构:
struct colorShapeSize{
let color: String!
let shape: String!
let size: UIImage!
}
我有一个看起来像这样的字符串:
"color:{Blue}shape:{round}size:{medium}"
所有字符串都采用相同的格式(即颜色始终为第一,第二形,第三尺寸)。
如何从字符串中提取数据并将其放入colorShapeSize
结构中?
答案 0 :(得分:1)
这个怎么样?
struct ColorShapeSize {
let color: String
let shape: String
let size: String
init(rawValue: String) {
var dictionary: [String: String] = [:]
var sorted = rawValue.components(separatedBy: "}").filter({ return $0.components(separatedBy: ":{").count == 2 })
for s in sorted {
let kv = s.components(separatedBy: ":{")
let key = kv[0]
let value = kv[1]
dictionary[key] = value
}
color = dictionary["color"] ?? ""
shape = dictionary["shape"] ?? ""
size = dictionary["size"] ?? ""
}
}
let str = "color:{Blue}shape:{round}size:{medium}"
let css = ColorShapeSize(rawValue: str)
print(css.color, css.shape, css.size)
答案 1 :(得分:1)
试试这个,它会在数组中提取字符串,然后你可以用值
做你想做的事func test() {
let givenString = "color:{Blue}shape:{round}size:{medium}"
var results = [String]()
do {
let regex = try NSRegularExpression(pattern: "\\{(.*?)\\}", options: [])
let tempString = givenString as NSString
regex.enumerateMatches(in: givenString, options: [], range: NSMakeRange(0, givenString.characters.count), using: { (result, flag, stop) in
if let range = result?.rangeAt(1) {
let number = tempString.substring(with: range)
results.append(number)
}
})
print(results) //["Blue", "round", "medium"] (Here you can initialize your struct with the values)
}
catch(let error) {
print("Unable to extract string : \(error.localizedDescription)")
}
}