2017-02-22 110 views
-4

是否有任何简单的方法将字符串转换为如下形式:[[1,2],[1,3],[1,4]]是否包含数组?将array.description字符串转换为数组

我会很高兴。

+3

这看起来并不像一个*字典的说明。*你是如何获得字符串的? - 如果必须将字典/数组转换为字符串并返回,最好选择一种类似JSON的格式。 –

+0

对不起,我想过Array ... – Dzeremix

+1

http://stackoverflow.com/questions/37391290/convert-string-array-representation-of-integers-into-array-of-integers-in- swift – Moritz

回答

0

我做的方法为它和它的作品:

func convertToArray(string: String) -> [[Int]] { 
    var arrayOrder = 0 
    var mainArray: [[Int]] = [] 
    var array: [Int] = [] 

    for character in string.characters { 
     if character == "[" { 
      arrayOrder += 1 
     } 

     if arrayOrder >= 2 && character != "[" && character != "]" && character != "," { 
      let integer: Int = Int(String(character))! 
      array.append(integer) 
     } 

     if character == "]" { 
      if arrayOrder >= 2 { 
       mainArray.append(array) 
       array = [] 
      } 

      arrayOrder -= 1 
     } 
    } 

    return mainArray 
} 
+0

只有当我们在主数组中有一层数组时。 – Dzeremix

1

最简单的方法是将其转换成JSON和背部:

let str = "[[1,2],[1,3],[1,4]]" 
let data = str.data(using: .utf8)! 

do { 
    let json = try JSONSerialization.jsonObject(with: data, options: []) 
    if let arr = json as? [[Int]] { 
     print(arr) 
    } 
} catch { 
    print(error) 
}