我很好奇的性能特点joined(),并.flatMap(_:)在扁平化多维数组:
let array = [[1,2,3],[4,5,6],[7,8,9]]
let j = Array(array.joined())
let f = array.flatMap{$0}
Run Code Online (Sandbox Code Playgroud)
他们都压平嵌套array进[1, 2, 3, 4, 5, 6, 7, 8, 9].我是否应该更喜欢一个而不是性能?此外,是否有更可读的方式来编写呼叫?
我看到这篇帖子 展示了如何通过以下方式获得数组的最常值:
let myArray = [4, 4, 4, 3, 3, 3, 4, 6, 6, 5, 5, 2]
// Create dictionary to map value to count
var counts = [Int: Int]()
// Count the values with using forEach
myArray.forEach { counts[$0] = (counts[$0] ?? 0) + 1 }
// Find the most frequent value and its count with max(isOrderedBefore:)
if let (value, count) = counts.max(isOrderedBefore: {$0.1 < $1.1}) {
print("\(value) occurs \(count) times")
}
Run Code Online (Sandbox Code Playgroud)
我想为一个数组实现相同的结果CGPoints,这有点不同.我尝试使用相同的代码并得到一个错误:
Type 'CGPoint' does …Run Code Online (Sandbox Code Playgroud)