如何从文本字段中获取一组集合?

时间:2019-03-15 10:51:45

标签: ios swift

我需要转换textField.text中的值 到Set<Set<Int?>>

字符串示例:[nil],[1],[2],[1,2]

1 个答案:

答案 0 :(得分:0)

let string = "[nil],[1],[2],[1,2]"

var resultArray: [Set<Int?>] = []

for substring in string.split(separator: "[") {
    var set = Set<Int?>()
    var setString = String(substring)
    setString.removeLast(setString.last == "]" ? 1 : 2)
    for substring in setString.split(separator: ",") {
        set.insert(Int(substring))
    }
    resultArray.append(set)
}
print(resultArray)
// [Set([nil]), Set([Optional(1)]), Set([Optional(2)]), Set([Optional(2), Optional(1)])]