arr.split(where:)
ๆญคๆนๆณๆไบค็ฑ where:
ๅๆธไพๅคๆท๏ผใๅ้ฃๅไธญ๏ผๅๅพๅ
ฉๅ
็ด ไน้่ฉฒไธ่ฉฒๆท้๏ผๅฝขๆๆฐ็ๅญ้ฃๅใใ
๐็ฏไพ๏ผ
let array = [1, 2, 2, 2, 3, 4, 4]
// โญ๏ธ equivalent to: `array.split { $0 != $1 }`
array.split(where: !=) // [[1], [2, 2, 2], [3], [4, 4]]
๐พ ็จๅผ๏ผ
// โญ๏ธ arr.split(where:)
extension Array {
/// split an array into array of subarrays.
public func split(
where shouldSplit: (Element, Element) -> Bool
) -> [[Element]]
{
// result of splitting (array of subarrays)
var result: [[Element]] = isEmpty ? [] : [[self[0]]]
// for each (previous, current) pair
for (previous, current) in zip(self, self.dropFirst()) {
// if should split,
if shouldSplit(previous, current) {
// append new subarray
// --------------------
result.append([current])
} else {
// else append to the last subarray.
// -----------------------------------
// ๐งจ Note:
// don't use `result.last` to append,
// the `last` property is immutableโ๏ธ
result[result.endIndex-1].append(current)
}
}
return result
}
}
Swift Algorithms โฉ Collection โฉ chunked(by:) โญ๏ธ
Swift โฉ
Array โฉ
dropFirst(_:) -> ArraySlice<Element> (โญ๏ธ ๆณจๆ๏ผ.dropFirst ไธฆๆฒๆๆ็ฌฌไธๅๅ ็ด ๅป้คโ๏ธ)
Collection โฉ .isEmpty
Merge Sort splits arrays in half recursively.
str.split() splits String into [Substring].
similar to arr.split(size:).
Last updated