如何在 Swift 4 中使用 String 子字符串?不推荐使用“substring(to:)":请使用带有“部分范围从"运算符的字符串切片下标 [英] How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator

查看:27
本文介绍了如何在 Swift 4 中使用 String 子字符串?不推荐使用“substring(to:)":请使用带有“部分范围从"运算符的字符串切片下标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下用 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:)' 已被弃用:请使用 String 切片下标和'partial range from' 运算符.

'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 中使用 String 子字符串?不推荐使用“substring(to:)":请使用带有“部分范围从"运算符的字符串切片下标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆