2017-09-02 13 views
2

我想將swift3代碼轉換爲swift4。但這個錯誤顯示如何在Swift中使用字符串下標4

「子(來自:)」被棄用:請使用字符串的切片標 以‘從’操作部分範圍。」

我的代碼是:提前

extension String { 


    func substring(_ from: Int) -> String { 
     return self.substring(from: self.characters.index(self.startIndex, offsetBy: from)) 

    } 

的感謝!

+0

查看https://stackoverflow.com/questions/45562662/how-to-use-string-slicing-subscript-in-swift-4 – algrid

+0

我已經檢查....但仍然不明白...你能解釋一下嗎... @algrid –

+0

你能解釋一下嗎?@ MoeAbdul-Hameed –

回答

4

你應該有:

extension String { 

    func substring(_ from: Int) -> String { 
     let start = index(startIndex, offsetBy: from) 
     return String(self[start ..< endIndex]) 
    } 
} 

在迅速的,你可以得到一個使用字符串切片 - 一個建築像這樣:string[startIndex ..< endIndex]。字符串索引是swift中的一種特殊類型,因此您不能使用簡單的整數 - 您必須獲得適當的索引,例如調用index(_,offsetBy:)或使用預定義的startIndexendIndex

+0

thanksss !!!! @algrid .. –

相關問題