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)
}
Run Code Online (Sandbox Code Playgroud)
错误代码:
二元运算符“+”不能应用于“String._CharacterView.Index?”类型的操作数 (又名“可选< String.Index >”)和“Int”
您可以使用计算从 a到字符串起始位置的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)
}
}
Run Code Online (Sandbox Code Playgroud)
但请注意,index(of:)返回字符串中字符的第一个索引,因此上面的代码将打印
a 0
b 1
a 0
b 1
Run Code Online (Sandbox Code Playgroud)
如果您的目的是获取字符串中每个字符的运行偏移量,则使用enumerated()
for (distance, char) in str.enumerated() {
print(char, distance)
}
Run Code Online (Sandbox Code Playgroud)
这将打印
a 0
b 1
a 2
b 3
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6532 次 |
| 最近记录: |