2017-09-22 43 views
1

試圖從Swift中的字符串中移除第一個字符。我使用下面編寫的代碼,但第二行不斷崩潰我的應用程序。Swift中的字符串基礎知識

這不是解開字符串索引的正確方法嗎?什麼是?

var tempText = text 
let toRemove = tempText?.startIndex ?? String.Index(0) 
tempText?.remove(at: toRemove) 
+0

什麼是崩潰的消息?字符串是否爲空? – dan

+0

您可能希望看到https://stackoverflow.com/questions/28445917/what-is-the-most-succinct-way-to-remove-the-first-character-from-a-string-in-swi – rmaddy

回答

1

要初始化String.Index型,而不是獲取tempText字符串的索引。

而且,startIndex不是可選的tempText,但是是。

您應該檢查是否存在tempText和不爲空(你可以簡單地這樣做有if let),並在startIndex刪除字符,如果這些條件相匹配。

var tempText = text 

if let toRemove = tempText?.startIndex { 
    tempText?.remove(at: toRemove) 
} 
+0

謝謝,這清理完美。現在很明顯,你解釋* facepalm * – daredevil1234

+0

耶穌,所有的力量解開了什麼?你*已經*有一個if語句,只需將其更改爲條件綁定即可。 – Alexander

+0

@ the4kman這是真的嗎? 'tempText = tempText?.characters.dropFirst()。map(String.init)?? tempText' – Alexander

3

您可以使用收集方法dropFirst:

if let text = text { // you need also to unwrap your optional 
    let tempText = String(text.characters.dropFirst()) // And initialize a new String with your CharacterView 
} 

在斯威夫特4字符串符合集合,以便你可以在你的字符串直接使用它:

if let text = text { 
    let tempText = text.dropFirst() // "bc" 
}