2017-02-22 31 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) 
}