gpt4 book ai didi

swift - 如何从 string.index 获取 Int?

转载 作者:行者123 更新时间:2023-12-03 16:20:06 25 4
gpt4 key购买 nike

swift 4.1、xcode 9.3、 cocoa 应用程序

如何从 string.index 获取 Int 以便与其他属性编号一起使用?

@IBOutlet weak var inputFromTextField: NSTextField!
@IBAction func button(_ sender: NSButton) {
let temporaryHolder = inputFromTextField.stringValue.characters
for input in temporaryHolder {
let distance = temporaryHolder.index(of: input)
print(input)
print(distance + 100)
}

错误代码:

Binary operator '+' cannot be applied to operands of type 'String._CharacterView.Index?' (aka 'Optional< String.Index >') and 'Int'

最佳答案

您可以使用distance(from:to:)来计算(整数)距离从 String.Index 到字符串的起始位置:

let str = "abab"
for char in str {
if let idx = str.index(of: char) {
let distance = str.distance(from: str.startIndex, to: idx)
print(char, distance)
}
}

但请注意,index(of:) 返回字符的第一个索引在字符串中,所以上面的代码将打印

a 0
b 1
a 0
b 1

如果您的目的是获取字符串中每个字符的运行偏移量,请使用enumerated()

for (distance, char) in str.enumerated() {
print(char, distance)
}

这将打印

a 0
b 1
a 2
b 3

关于swift - 如何从 string.index 获取 Int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50674573/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com