我一直在使用Swift 3更新我的一些旧代码和答案但是当我使用子字符串获取Swift字符串和索引时,事情变得令人困惑.
具体来说,我尝试以下方法:
let str = "Hello, playground"
let prefixRange = str.startIndex..<str.startIndex.advancedBy(5)
let prefix = str.substringWithRange(prefixRange)
Run Code Online (Sandbox Code Playgroud)
第二行给我以下错误
'String'类型的值没有成员'substringWithRange'
我看到现在String确实有以下方法:
str.substring(to: String.Index)
str.substring(from: String.Index)
str.substring(with: Range<String.Index>)
Run Code Online (Sandbox Code Playgroud)
起初这些让我很困惑,所以我开始玩索引和范围.这是子串的后续问题和答案.我在下面添加一个答案来说明它们是如何使用的.
我一直在使用Swift 3更新我的一些旧代码和答案,但是当我使用Swift Strings和Indexing时,理解事情是一件很痛苦的事情.
具体来说,我尝试以下方法:
let str = "Hello, playground"
let prefixRange = str.startIndex..<str.startIndex.advancedBy(5) // error
Run Code Online (Sandbox Code Playgroud)
第二行给我以下错误
'advancedBy'不可用:要将索引推进n步,请在生成索引的CharacterView实例上调用'index(_:offsetBy :)'.
我看到它String有以下方法.
str.index(after: String.Index)
str.index(before: String.Index)
str.index(String.Index, offsetBy: String.IndexDistance)
str.index(String.Index, offsetBy: String.IndexDistance, limitedBy: String.Index)
Run Code Online (Sandbox Code Playgroud)
起初这些让我很困惑所以我开始玩它们直到我理解它们.我在下面添加一个答案来说明它们是如何使用的.