Big Johnson
Big Johnson

Reputation: 217

String interpretation in Swift

I have a struct that looks like this:

struct colorShapeSize{
    let color: String!
    let shape: String!
    let size: UIImage!
}

and I have a string that looks something like this:

"color:{Blue}shape:{round}size:{medium}"

All of the strings will be in the same format (i.e. color will always come first, shape second, and size third).

How would I extract the data from the string and put it into a colorShapeSize struct?

Upvotes: 0

Views: 225

Answers (2)

kathayatnk
kathayatnk

Reputation: 1015

try this, it will extract the string in array, then you can do what you want with the value

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)")
    }
}

Upvotes: 1

Ryan
Ryan

Reputation: 4884

How about this?

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)

Upvotes: 1

Related Questions