I was using only advance function by passing two arguments. Can somebody help me to use it with three arguments which is illustrated as:
我通过传递两个参数只使用高级函数。有人可以帮助我使用三个参数,如下所示:
func advance<T : ForwardIndexType>(start: T, n: T.Distance, end: T) -> T
1 个解决方案
#1
That function increments the start
index by n
positions, but not beyond the end
index.
该函数将起始索引增加n个位置,但不超过结束索引。
Example: You want to truncate strings to a given maximal length:
示例:您希望将字符串截断为给定的最大长度:
func truncate(string : String, length : Int) -> String {
let index = advance(string.startIndex, length, string.endIndex)
return string.substringToIndex(index)
}
println(truncate("fooBar", 3)) // foo
println(truncate("fo", 3)) // fo
In the first call, the start index is incremented by 3 positions, in the second example only by two. With
在第一次调用中,起始索引增加3个位置,在第二个示例中仅增加2个。同
let index = advance(string.startIndex, length)
the second call would crash with a runtime exception, because a string index must not be advanced beyond the end index.
第二个调用将因运行时异常而崩溃,因为字符串索引不能超出结束索引。
#1
That function increments the start
index by n
positions, but not beyond the end
index.
该函数将起始索引增加n个位置,但不超过结束索引。
Example: You want to truncate strings to a given maximal length:
示例:您希望将字符串截断为给定的最大长度:
func truncate(string : String, length : Int) -> String {
let index = advance(string.startIndex, length, string.endIndex)
return string.substringToIndex(index)
}
println(truncate("fooBar", 3)) // foo
println(truncate("fo", 3)) // fo
In the first call, the start index is incremented by 3 positions, in the second example only by two. With
在第一次调用中,起始索引增加3个位置,在第二个示例中仅增加2个。同
let index = advance(string.startIndex, length)
the second call would crash with a runtime exception, because a string index must not be advanced beyond the end index.
第二个调用将因运行时异常而崩溃,因为字符串索引不能超出结束索引。