如何在Swift中将“索引”转换为“ Int”类型?

克里斯托弗:

我想将字符串中包含的字母的索引转换为整数值。尝试读取头文件,但找不到的类型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)

任何帮助表示赞赏。

里奥·达布斯(Leo Dabus):

编辑/更新:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在 Swift 中将 Enum 类型转换为 Double

如何在Swift中将String类型的变量转换为CFString?

如何在Swift中将Int转换为NSData?

如何在Swift中将Unicode字符转换为Int

如何在Swift中将RealmOptional转换为Int或Float?

如何在Swift中将Int转换为字符

如何在Java与Swift中将long转换为int?

如何在 Swift 中将 String 转换为 Int?

如何在Python中将[String,String]类型的RDD转换为[Int,Int]类型的RDD?

如何在python中将unsigned char类型的int字符串转换为int

如何在iOS Swift中将类型的UIViewController传递给函数并类型转换为变量?

如何在Swift中将Int32转换为Int?

如何在Swift中将大于Int.max的浮点值转换为Int

在scala中将类型布尔类型转换为Int类型

如何在方法中将int转换为类型Object;仅Java

如何在 VBA 中将百分比数据类型转换为 Int

如何在Swift中将字典转换为自定义类型?

如何在Swift中将数据转换为Doubles,Ints和Strings等类型?

如何在Swift中将Int转换为4个字节的字节数组?

如何在Swift中将Int转换为十六进制字符串

如何在Swift 3中将数据转换为Int?

如何在Swift中将[Int8]转换为[UInt8]

如何在Swift 4中将Int32转换为String?

如何在 Swift 中将包含 % 的字符串转换为 Int

如何在 Swift 中将文本字段中的字符串转换为 Int?

如何在Java中将double转换为int转换

如何在Java中将String类型转换为Class类型

如何在Delphi中将通用类型转换为实际类型

如何在python中将列数据类型int64转换为分类列数据类型?