如何在 Swift 4 中使用字符串子字符串?'substring(to:)' 已弃用:请使用带有 'partial range from' 运算符的字符串切片下标

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 4 中使用字符串子字符串?'substring(to:)' 已弃用:请使用带有 'partial range from' 运算符的字符串切片下标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下用 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 use String 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' 运算符的字符串切片下标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Why local notification is not firing for UNCalendarNotificationTrigger(为什么没有为UNCalendarNotificationTrigger触发本地通知)
Pushing UIViewController above UITabBar(将UIView控制器推送到UITabBar上方)
Dropbox Files.download does not start when number of files in folder is gt; 1000(当文件夹中的文件数为1000时,Dropbox Files.Download不会启动)
appearance().setBackgroundImage Not Working On Custom Class(外观().setBackoundImage在自定义类上不起作用)
Show/Hide barButtonItem(显示/隐藏barButtonItem)
java.lang.IllegalStateException: SimpleTypeImpl should not be created for error type(异常:不应为错误类型创建SimpleTypeImpl)