Вы можете использовать метод Collection split
и установить omittingEmptySubsequences
на true
:
extension StringProtocol {
func notContains(_ element: Element) -> Bool {
return !contains(element)
}
var numbers: [SubSequence] {
return split(maxSplits: Int.max, omittingEmptySubsequences: true, whereSeparator: "0123456789.".notContains)
}
}
let text = "12.1gh 34.5abc 32.5"
let result = text.numbers // ["12.1", "34.5", "32.5"]
let nums = result.flatMap(Double.init) // [12.1, 34.5, 32.5]