2016-01-18 62 views
2

代码:无法将类型的值“诠释”预期参数类型“索引”(又名“String.CharacterView.Index”)

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

可正常工作。

但是,如果我去掉最后的4行,然后我得到:

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

很奇怪。

+0

我描述一个奇怪的行为,不只是要求如何得到的尾巴一个字符串。这不是重复的。 – qed

回答

3

这是因为在String的下标功能不再整数操作,但在内部Index类型:

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

    //... 

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

因此,你需要抓住一些Index值。您可以通过在字符串中获得第一指数(又称第一个字符的索引)实现这一点,并导航从那里:

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