How to I get the first or last few characters of a string in a method chain?

一曲冷凌霜 提交于 2019-12-12 04:01:36

问题


If I use functional-style method chains for string manipulation, I can not use the usual machinery for getting the first or last few characters: I do not have access to a reference to the current string, so I can not compute indices.

Example:

[some, nasty, objects]
    .map( { $0.asHex } )
    .joined()
    .<first 100>
    .uppercased()
    + "..."

for a truncated debug output.

So how to I implement <first 100>, or do I have to break the chain?


回答1:


I don't know of any API that does this. Fortunately, writing our own is an easy exercise:

extension String {
    func taking(first: Int) -> String {
        if first <= 0 {
            return ""
        } else if let to = self.index(self.startIndex, 
                                      offsetBy: first, 
                                      limitedBy: self.endIndex) {
            return self.substring(to: to)
        } else {
            return self
        }
    }
}

Taking from the end is similar.

Find full code (including variants) and tests here.



来源:https://stackoverflow.com/questions/43277938/how-to-i-get-the-first-or-last-few-characters-of-a-string-in-a-method-chain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!