Swift : How to get the string before a certain character?

前端 未结 11 1899
北恋
北恋 2020-12-24 01:45

How do I get the string before a certain character in swift? The code below is how I did it in Objective C, but can\'t seem to perform the same task in Swift. Any tips or su

11条回答
  •  滥情空心
    2020-12-24 02:17

    You could use the method prefix(upTo:) in Swift 4 or above

    var string = "hello Swift"
    if let index = string.firstIndex(of: " ") {
        let firstPart = string.prefix(upTo: index)
        print(firstPart) // print hello
    }
    

提交回复
热议问题