如何使用三个参数快速使用高级功能? [英] How to use advance function in swift with three parameters?

查看:91
本文介绍了如何使用三个参数快速使用高级功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只通过传递两个参数来使用advance函数。有人可以帮我用三个参数来表示它:

  func advance< T:ForwardIndexType>(start:T ,n:T.Distance,end:T) - > T 


解决方案

该函数将 n 头寸开始指数,但不是
超过
结束 code> index。



示例:您想将字符串截断为给定的最大长度:

  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

在第一次调用中,起始索引增加3个位置,第二个示例中的
只增加2个位置。


  let index = advance(string.startIndex,length)

第二次调用会因运行时异常而崩溃,因为
a字符串索引不得超出结束索引。


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

解决方案

That function increments the start index by n positions, but not beyond the end index.

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

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.

这篇关于如何使用三个参数快速使用高级功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆