[swift-dev] index indexes and ranges of String

Carlos García carlosypunto at gmail.com
Fri Jan 6 08:39:47 CST 2017


Hi,

I think this is important enough and useful for we to be in the core standard library

extension String {

    func index(of string: String, options: String.CompareOptions = .literal) -> String.Index? {
        return range(of: string, options: options)?.lowerBound
    }

    func indexes(of string: String, options: String.CompareOptions = .literal) -> [String.Index] {
        var result: [String.Index] = []
        var start = startIndex
        while let range = range(of: string, options: options, range: start..<endIndex) {
            result.append(range.lowerBound)
            start = range.upperBound
        }
        return result
    }

    func ranges(of string: String, options: String.CompareOptions = .literal) -> [Range<String.Index>] {
        var result: [Range<String.Index>] = []
        var start = startIndex
        while let range = range(of: string, options: options, range: start..<endIndex) {
            result.append(range)
            start = range.upperBound
        }
        return result
    }

}


Source is not mine, I’ve found here: http://stackoverflow.com/a/32306142/4550651 <http://stackoverflow.com/a/32306142/4550651>

Carlos García
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-dev/attachments/20170106/e2b0ea90/attachment.html>


More information about the swift-dev mailing list