gpt4 book ai didi

swift - 在 Swift 中获取空 Range

转载 作者:行者123 更新时间:2023-12-02 02:49:54 24 4
gpt4 key购买 nike

我对 Swift 很陌生,并尝试使用正则表达式,但从字符串中获取匹配似乎是一项难以克服的任务。

这是我目前的方法。

print(data.substring(with: (data.range(of: "[a-zA-Z]at", options: .regularExpression))))

这不起作用,因为

Value of optional type 'Range<String.Index>?' must be unwrapped to a value of type 'Range<String.Index>'

我想这可能与它可能为空有关,所以现在我想使用 ?? 为其提供替代方案运算符。

print(data.substring(with: (data.range(of: "[a-zA-Z]at", options: .regularExpression) ?? Range<String.Index>())))

我想做的是为其提供一个空范围对象,但似乎不可能创建所需类型的空对象。

有什么建议吗?

最佳答案

Range<String.Index> 根本没有无参数初始化器.

创建空范围 String.Index 的一种方法是使用:

data.startIndex..<data.startIndex

请记住,您不应在此处使用整数,因为我们正在处理字符串的索引。请参阅this如果你不明白为什么。

所以:

print(data.substring(with: (data.range(of: "[a-zA-Z]at", options: .regularExpression) ?? data.startIndex..<data.startIndex)))

但是substring(with:)已弃用。建议使用下标:

print(data[data.range(of: "[a-zA-Z]at", options: .regularExpression) ?? data.startIndex..<data.startIndex])

关于swift - 在 Swift 中获取空 Range<String.Index>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62173009/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com