如何在 Swift 中使用 String.substringWithRange?或者 Swift 中的 Range 是如何工作的?
大家好!我是 Swift 新手,从 Objective-C 迁移过来,在处理字符串时遇到了问题。在 Objective-C 中,我使用 `substringWithRange:` 轻松截取子字符串,例如:
```objc
NSString *str = @"Привет, мир!";
NSRange range = NSMakeRange(0, 6);
NSString *substr = [str substringWithRange:range]; // "Привет"
```
在 Swift 中,我尝试做同样的事情,但遇到了错误。我写了:
```swift
let str = "Привет, мир!"
let range = NSMakeRange(0, 6)
let substr = str.substringWithRange(range) // 错误!
```
Xcode 提示 `String` 没有 `substringWithRange` 方法。我读到在 Swift 中需要使用 `Range`,但我不明白如何创建它。为什么不能直接传递 `NSRange`?
请用示例解释:
1. 如何在 Swift 中正确截取字符串的子字符串?
2. 什么是 `Range` 和 `String.Index`,以及如何使用它们?
3. 如何处理包含 Unicode(例如表情符号或西里尔字母)的字符串?
提前感谢!