【问题标题】:How to get an Int from a string.index?如何从 string.index 中获取 Int?
【发布时间】:2018-06-04 06:33:18
【问题描述】:

swift 4.1、xcode 9.3、可可应用

如何从 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)
}

错误代码:

二元运算符“+”不能应用于类型的操作数 'String._CharacterView.Index?' (又名“可选”)和 '诠释'

【问题讨论】:

  • 看看这可能对你有帮助stackoverflow.com/questions/47485680/…
  • 我相信他们的问题是关于 (aka 'Optional') 和 'Int' [重复]。我的问题是关于(又名'Optional')和'Int'。所以我认为它没有帮助。如果它只是可选的,我可以打开它,但这是 string.index。所以我不能。
  • 这真的很难哈?我已经为此工作了 6 个小时,但仍然找不到解决方案。 :3
  • 不不不难,听马丁的回答

标签: swift xcode cocoa


【解决方案1】:

您可以使用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:) 返回字符的 first 索引 在字符串中,所以上面的代码将打印

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-09
    • 1970-01-01
    相关资源
    最近更新 更多