2016-08-27 50 views

Odpowiedz

10

Można użyć rangeOfString i substringToIndex jego startIndex następująco:

Swift 2

let word = "orange" 
if let index = word.rangeOfString("n")?.startIndex { 
    print(word.substringToIndex(index)) // "ora" 
} 

Swift 3

let word = "orange" 
if let index = word.range(of: "n")?.lowerBound { 
    print(word.substring(to: index)) // "ora" 
} 

Swift 4

let word = "orange" 
if let index = word.range(of: "n")?.lowerBound { 
    let substring = word[..<index] 
    let string = String(substring) 
    print(string) // "ora" 
} 
1

można zrobić to tak:

guard let range = text.rangeOfString("Your String or Character here") else { 
    return the text 
} 

return text.substringToIndex(range.endIndex) 
// depending on if you want to delete before a certain string, you would use range.startIndex