如何转换“索引"输入“Int"在斯威夫特? [英] How to convert "Index" to type "Int" in Swift?

查看:17
本文介绍了如何转换“索引"输入“Int"在斯威夫特?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to convert the index of a letter contained within a string to an integer value. Attempted to read the header files but I cannot find the type for Index, although it appears to conform to protocol ForwardIndexType with methods (e.g. 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 或更高版本

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) }
}

<小时>

游乐场测试

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")
}

这篇关于如何转换“索引"输入“Int"在斯威夫特?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆