问题描述
我有以下用 Swift 3 编写的简单代码:
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)
从 Xcode 9 beta 5 开始,我收到以下警告:
From Xcode 9 beta 5, I get the following warning:
'substring(to:)
' 已弃用:请使用带有partial range from"运算符的 String
切片下标.
'
substring(to:)
' is deprecated: Please useString
slicing subscript with a 'partial range from' operator.
如何在 Swift 4 中使用这种 具有部分范围的切片下标?
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".
let newStr = str[..<index]
partial range from 运算符也一样,只是把另一边留空:
The same stands for partial range from operators, just leave the other side empty:
let newStr = str[index...]
请记住,这些范围运算符返回 Substring
.如果要转成字符串,使用String
的初始化函数:
Keep in mind that these range operators return a Substring
. If you want to convert it to a string, use String
's initialization function:
let newStr = String(str[..<index])
您可以在此处阅读更多关于新子字符串的信息.
You can read more about the new substrings here.
这篇关于如何在 Swift 4 中使用字符串子字符串?'substring(to:)' 已弃用:请使用带有 'partial range from' 运算符的字符串切片下标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!