How can I use String substring in Swift 4? #39;substring(to:)#39; is deprecated: Please use String slicing subscript with a #39;partial range from#39; operator(如何在 Swift 4 中使用字符串子字符串?substring(to:) 已弃用:请使用带有 partial range from 运算符的字符串切片下标) - IT屋-程序员软
问题描述
我有以下用 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 useStringslicing 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' 运算符的字符串切片下标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Swift 4 中使用字符串子字符串?'substring(to:)' 已弃用:请使用带有 'partial range from' 运算符的字符串切片下标
基础教程推荐
- iOS4 创建后台定时器 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
