I have the following simple code written in Swift 3:
let str = "Hello, playground"
let index = str.index(of: ",")!
let newStr = str.substring(to: index)
From Xcode 9 beta 5, I get the following warning:
'
substring(to:)
' is deprecated: Please useString
slicing subscript with a 'partial range from' operator.
How can this slicing subscript with partial range from be used in Swift 4?
You should leave one side empty, hence the name "partial range".
The same stands for partial range from operators, just leave the other side empty:
Keep in mind that these range operators return a
Substring
. If you want to convert it to a string, useString
's initialization function:You can read more about the new substrings here.
Example of
uppercasedFirstCharacter
convenience property in Swift3 and Swift4.Property
uppercasedFirstCharacterNew
demonstrates how to use String slicing subscript in Swift4.Swift4:
Usage:
You can create your custom subString method using extension to class String as below:
Shorter in Swift 4:
I have written a string extension for replacement of 'String: subString:'
PS: Optionals are forced to unwrap. Please add Type safety check wherever necessary.