Swift 字符串索引转换为 Int 索引 - 详细指南
在 Swift 中,可以使用 String.Index 类型来表示字符串中的索引。要将 String 类型的索引转换为 Int 类型的索引,可以使用 distance(from:to:) 方法。\n\n以下是将 Swift 中的 String 索引转换为 Int 索引的示例代码:\n\nswift\nlet str = \"Hello, World!\"\nlet index = str.index(str.startIndex, offsetBy: 7) // 获取第7个字符的索引\n\nif let intIndex = str.distance(from: str.startIndex, to: index) as Int? {\n print(intIndex) // 输出:7\n}\n\n\n在上面的示例代码中,我们先使用 index(_:offsetBy:) 方法获取字符串中第7个字符的索引。然后使用 distance(from:to:) 方法将该索引转换为 Int 类型的索引。最后,我们将转换后的索引打印出来。\n\n请注意, distance(from:to:) 方法返回的是 String.IndexDistance 类型,而不是 Int 类型。因此,我们需要将其强制转换为 Int 类型。
原文地址: https://www.cveoy.top/t/topic/pwKk 著作权归作者所有。请勿转载和采集!