简体   繁体   English

Swift 3:如何进行字符串范围?

[英]Swift 3: How to do string ranges?

Last night I had to convert my Swift 2.3 code to Swift 3.0 and my code is a mess after the conversion. 昨晚我不得不将我的Swift 2.3代码转换为Swift 3.0,转换后我的代码很乱。 In Swift 2.3 I had the following code: 在Swift 2.3中,我有以下代码:

let maxChar = 40;
let val = "some long string";
var startRange = val.startIndex;
var endRange = val.startIndex.advancedBy(maxChar, limit: val.endIndex);
let index = val.rangeOfString(" ", options: NSStringCompareOptions.BackwardsSearch , range: startRange...endRange , locale: nil)?.startIndex;

Xcode converted my code to this which doesn't work: Xcode将我的代码转换为不起作用的代码:

let maxChar = 40;
let val = "some long string";
var startRange = val.startIndex;
var endRange = val.characters.index(val.startIndex, offsetBy: maxChar, limitedBy: val.endIndex);
let index = val.range(of: " ", options: NSString.CompareOptions.backwards , range: startRange...endRange , locale: nil)?.lowerBound

The error is in the parameter range in val.rage , saying No '...' candidates produce the expected contextual result type 'Range?' 错误在val.rage的参数range ,说没有'...'候选产生预期的上下文结果类型'Range?' .

I tried using Range(startRange...endRange) as suggestd in the docs but I'm getting en error saying: connot invoke initiliazer for type ClosedRange<_> with an arguement list of type (ClosedRange) . 我尝试使用Range(startRange...endRange)作为文档中的建议,但我得到错误说: connot使用类型的争论列表(ClosedRange)调用类型ClosedRange <_>的initiliazer Seems like I'm missing something fundametnal. 好像我错过了一些基本的东西。

Any help is appreciated. 任何帮助表示赞赏。 Thanks! 谢谢!

Simple answer: the fundamental thing you are missing is that a closed range is now different from a range. 简单回答:你缺少的基本要素是现在一个封闭的范围与范围不同。 So, change startRange...endRange to startRange..<endRange . 因此,将startRange...endRange更改为startRange..<endRange

In more detail, here's an abbreviated version of your code (without the maxChar part): 更详细地说,这是代码的缩写版本(没有maxChar部分):

let val = "some long string";
var startRange = val.startIndex;
var endRange = val.endIndex;
let index = val.range(
    of: " ", options: .backwards, range: startRange..<endRange)?.lowerBound
// 9

Now you can use that as a basis to restore your actual desired functionality. 现在,您可以将其用作恢复实际所需功能的基础。


However, if all you want to do is split the string, then reinventing the wheel is kind of silly: 但是,如果您只想拆分字符串,那么重新发明轮子有点愚蠢:

let arr = "hey ho ha".characters.split(separator:" ").map{String($0)}
arr // ["hey", "ho", "ha"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM