Swift find all occurrences of a substring

前端 未结 7 1951
无人及你
无人及你 2020-12-06 00:46

I have an extension here of the String class in Swift that returns the index of the first letter of a given substring.

Can anybody please help me make it so it will

7条回答
  •  自闭症患者
    2020-12-06 01:00

    I know we aren't playing code golf here, but for anyone interested in a functional style one-line implementation that doesn't use vars or loops, this is another possible solution:

    extension String {
        func indices(of string: String) -> [Int] {
            return indices.reduce([]) { $1.encodedOffset > ($0.last ?? -1) && self[$1...].hasPrefix(string) ? $0 + [$1.encodedOffset] : $0 }
        }
    }
    

提交回复
热议问题