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.
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()) }
}
In Swift 4:
func tail(s: String) -> String {
return String(s.suffix(from: s.index(s.startIndex, offsetBy: 1)))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With