我想将字符串中包含的字母的索引转换为整数值.试图读取头文件,但我找不到Index的类型,尽管它似乎符合协议ForwardIndexType的方法(例如distanceTo).

var letters = "abcdefg"
let index = letters.characters.indexOf("c")!

// ERROR: Cannot invoke initializer for type 'Int' with an argument list of type '(String.CharacterView.Index)'
let intValue = Int(index)  // I want the integer value of the index (e.g. 2)

感谢您的帮助.

推荐答案

编辑/更新:

Xcode 11 • Swift 5.1 or later

extension StringProtocol {
    func distance(of element: Element) -> Int? { firstIndex(of: element)?.distance(in: self) }
    func distance<S: StringProtocol>(of string: S) -> Int? { range(of: string)?.lowerBound.distance(in: self) }
}

extension Collection {
    func distance(to index: Index) -> Int { distance(from: startIndex, to: index) }
}

extension String.Index {
    func distance<S: StringProtocol>(in string: S) -> Int { string.distance(to: self) }
}

Playground testing

let letters = "abcdefg"

let char: Character = "c"
if let distance = letters.distance(of: char) {
    print("character \(char) was found at position #\(distance)")   // "character c was found at position #2\n"
} else {
    print("character \(char) was not found")
}

let string = "cde"
if let distance = letters.distance(of: string) {
    print("string \(string) was found at position #\(distance)")   // "string cde was found at position #2\n"
} else {
    print("string \(string) was not found")
}

Swift相关问答推荐

多个提取来计算核心数据中的记录

try 在SwiftUI中做5星评级

如何防止自动状态恢复,如果应用程序被启动打开特定的文档?

如何使用Swift宏向 struct 体及其init函数添加新成员?

如何在visionOS中定制悬停效果区域

如何将图像插入到矩形中

插入/删除视图时的Swiftui动态过渡

如何获取嵌套数组中项的路径以修改数组?

如何绑定环境变量ios17

列表不显示信息

无法使用 RealityKit 播放 USDZ 动画

将阻塞函数集成到 Swift 异步中

如何在 Xcode 中的 UITests 下以通用方式访问后退栏按钮项?

在 ViewController 的 UICollectionView 中拉取刷新

UICollectionView 自定义单元格在 Swift 中填充宽度

3D touch /强制touch 实现

Type 应该采用什么协议来让泛型函数将任何数字类型作为 Swift 中的参数?

快速覆盖属性

使用相机进行人脸检测

Objective-C 方法与可选需求方法 Swift 冲突