2015-10-12 36 views
-1
let amount = "73.45" 

我想要四個不同的常量(字符串,而不是字符)與此字符串中的每個數字。理想的情況是:在Swift 2中訪問字符串中的每個字符

let amount1 = amount[0] // 7 
let amount2 = amount[1] // 3 
let amount3 = amount[3] // 4 
let amount4 = amount[4] // 5 

我已搜查,找不到任何工作,我要麼得到整個字符串或字符串的字符。任何意見將是有益的 - 新Xcode和迅速

回答

4

你可以隨時使用

let characters = amount.characters 

得到的字符串,而不是字符的字符,您可以:

let amount1 = String(characters[0]) 

做對於所有數字

let amounts = amount.characters.map { 
    return String($0) 
} 

要過濾分隔符,您可以

let amounts = amount.characters.map { 
    return String($0) 
}.filter { 
    $0 != "." 
} 

請注意,如果您已將輸入號碼本地化,則應檢查NSLocale以獲取正確的小數分隔符,或只刪除所有非數字字符。要做到這一點的方法之一是使用:

let amounts = amount.characters.filter { 
    $0 >= "0" && $0 <= "9" 
}.map { 
    String($0) 
} 

你可以把你的數字成不同的變量,然後,但我會建議反對:

let amount1 = amounts[0] 
let amount2 = amounts[1] 
let amount3 = amounts[2] 
let amount4 = amounts[3] 
+0

謝謝你,這對我幫助很大+1 – cakes88