Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert value of type 'Int' to expected argument type 'Index' (aka 'String.CharacterView.Index')

Tags:

string

swift

Code:

let x: String = ("abc".substringFromIndex(1))
print(x)
//func tail(s: String) -> String {
//    return s.substringFromIndex(1)
//}
//print(tail("abcd"))

This works as expected.

But if I uncomment the last 4 lines, then I get:

Error: cannot convert value of type 'Int' to expected argument type 'Index' (aka 'String.CharacterView.Index')

Really weird.

like image 714
qed Avatar asked Jan 18 '16 00:01

qed


2 Answers

This is because the subscripting functions in String no longer operate on ints, but on the inner Index type:

extension String {
    public typealias Index = String.CharacterView.Index

    //...

    public subscript (i: Index) -> Character { get }

So you need to grab some Index values. You can achieve this by obtaining the first index in the string (aka the index of the first character), and navigate from there:

func tail(s: String) -> String {
    return s.substringFromIndex(s.startIndex.advancedBy(1))
}

Note that the above code no longer compiles in the latest Swift version, I'll leave for historical purposes and for people stuck in earlier Swift.

These days we can write something along the lines of

extension String {
    var tail: String { String(self[index(startIndex, offsetBy: 1)...]) }
    // or
    var tail: String { String(self[index(after: startIndex)...]) }
    // or even this
    var tail: String { String(dropFirst()) }
}
like image 154
Cristik Avatar answered Oct 30 '22 07:10

Cristik


In Swift 4:

func tail(s: String) -> String {
    return String(s.suffix(from: s.index(s.startIndex, offsetBy: 1)))
}
like image 25
Adis Avatar answered Oct 30 '22 06:10

Adis