for循环中的for不起作用,因为int类型不符合协议序列.
我有3个数组:
1个主数组,存储数组
1个奇数阵,开头为空
1个偶数组,开头为空
意思是主阵列的所有奇数索引将存储在奇数阵列中,而偶数阵列则相同.
while i < masterA.count { evenA.append(masterA[i]) if i > 0{ oddA.append(masterA[i - 1]) } i += 2 }
然而,这不够好.谁有更好的主意?
这是另一种可能的解决方案
原文链接:https://www.f2er.com/swift/319303.htmllet evenA = stride(from: 0,to: masterA.count,by: 2).map { masterA[$0] } let oddA = stride(from: 1,by: 2).map { masterA[$0] }
元素直接从源阵列中的偶数/奇数位置“拾取”.
表现比较:
我的简单,不是非常复杂的特殊基准测试代码:
import Swift let N = 10_000_000 let RUNS = 50 let masterA = (0..<N).map { $0 } var times = (0.0,0.0,0.0) for _ in 1...RUNS { // filter+map (dfri) do { let start = Date() let evenA = masterA.enumerated().filter { $0.0 % 2 == 0 }.map{ $0.1 } let oddA = masterA.enumerated().filter { $0.0 % 2 != 0 }.map{ $0.1 } let time = Date().timeIntervalSince(start) times.0 += time } // flatMap (dfri) do { let start = Date() let evenA = masterA.enumerated().flatMap { $0 % 2 == 0 ? $1 : nil } let oddA = masterA.enumerated().flatMap { $0 % 2 != 0 ? $1 : nil } let time = Date().timeIntervalSince(start) times.1 += time } // stride+map (me) do { let start = Date() let evenA = stride(from: 0,by: 2).map { masterA[$0] } let oddA = stride(from: 1,by: 2).map { masterA[$0] } let time = Date().timeIntervalSince(start) times.2 += time } // loop (Keiwan) do { let start = Date() var evenA = [Int]() var oddA = [Int]() for (index,element) in masterA.enumerated() { if index % 2 == 0 { evenA.append(element) } else { oddA.append(element) } } let time = Date().timeIntervalSince(start) times.3 += time } } print(N,RUNS) print(times.0/Double(RUNS),times.1/Double(RUNS),times.2/Double(RUNS),times.3/Double(RUNS))
结果:(在MacBook上,在发布模式下运行)
#elements filter+map flatMap stride+map loop 10,000 0.0001 0.00008 0.00004 0.00004 100,000 0.0016 0.0008 0.0004 0.0004 1,000,000 0.0295 0.0136 0.0090 0.0091 10,000 0.3025 0.1332 0.0909 0.1250