Reputation:
I have a UILabel
called nihoshim
and the element in the last index is a number I want to increase. alpha
is a collection of UIButton
.
@IBAction func wordChoser(_ sender: UIButton) {
let tag = sender.tag - 1
var liel = nihoshim.text!
let index = Int(liel.endIndex) // error here
var alephbet = ["א","ב","ג","ד","ה","ו","ז","ח","ט","י","כ","ל","מ","נ","ס","ע","פ","צ","ק","ר","ש","ת"]
if gameLabel.text!.count <= 3 {
gameLabel.text = gameLabel.text! + alephbet[alpha.index(after: tag) - 1]
sender.isHidden = true
} else if gameLabel.text!.count <= 3 {
gameLabel.text = gameLabel.text! + alephbet[alpha.index(after: tag) - 1]
sender.isHidden = true
}
}
The error is:
Initializer 'init(_:)' requires that 'String.Index' conform to 'BinaryInteger'
Upvotes: 0
Views: 561
Reputation: 1
As Sulthan said you could use distance to be as below,
@IBAction func wordChoser(_ sender: UIButton) {
guard let liel = nihoshim.text, let morning = gameLabel.text else {
return
}
let tag: Int = sender.tag - 1
let index: Int = liel.distance(from: liel.startIndex, to: liel.endIndex)
var alephbet = ["א","ב","ג","ד","ה","ו","ז","ח","ט","י","כ","ל","מ","נ","ס","ע","פ","צ","ק","ר","ש","ת"]
if morning.count <= 3 {
gameLabel.text = morning + alephbet[tag]
gameLabel.text = morning + "\(index + tag)"
sender.isHidden = true
}
}
Upvotes: 0
Reputation: 51973
To get the last character of a string you can use suffix()
str.suffix(1)
So in your code, replace let index = Int(liel.endIndex)
with
guard let index = Int(liel.suffix(1)) else {
return //or some error handling
}
Upvotes: 1
Reputation: 130102
You cannot just convert String.Index
into a number.
The simplest way to do this, if we are talking about endIndex
, is:
let index = liel.count
For other indices, this would be:
let string = "abcd"
let stringIndex: String.Index = string.endIndex
let index: Int = string.distance(from: string.startIndex, to: stringIndex)
Upvotes: 1