young
(rtSwift)
1
I have some very large static array must be sorted. What's the best way to do it?
// 1 this doesn't compile
//let list = [4, 23, 345, 5985, 34, 32, 2].sort() // error: cannot use mutating member on immutable value of type '[Int]'
// 2 This work, but my actual list is very large, better not have to make another copy?
let list = [4, 23, 345, 5985, 34, 32, 2].sorted()
// 3 is this better? but is so verbose
let listDeux: [Int] = {
var result = [4, 23, 345, 5985, 34, 32, 2]
result.sort()
return result
}()
print(list)
print(listDeux)
Does you list come from some sort of code generator? Can you sort it inside the code generator?
1 Like
michelf
(Michel Fortin)
3
I think #2 and #3 are pretty much equivalent, once optimized: sorted() is inlinable, and its implementation is pretty much that of #3. To be 100% sure, you'll need to compile with optimizations and check the disassembly.
2 Likes
young
(rtSwift)
4
Yes I'm talking about my code generator. The need to sort is inside my code generator: this list is manually entered, I need to made sure it's sorted before I generate my code output.
But the question is in general what's the best way to do this?