3 ms·
there are holes in Swift's generics system, but this isn't one of them. you don't need separate extensions for int, string, float etc. arrays. the parent post g
by Tainnor 7y ago
there are holes in Swift's generics system, but this isn't one of them. you don't need separate extensions for int, string, float etc. arrays. the parent post gave you a generic implementation that works with any type of array
- melling 7y agoHmmm. I thought ArraySlice had different semantics. Why wouldn’t it be declared returning [Element]? extension Array { func take(_ n: Int) -> [Element] { self[0..<n] } } Apple provides this warning for ArraySlice: “Long-term storage of ArraySlice instances is discouraged. A slice holds a reference to the entire storage of a larger array, not just to the portion it presents, even after the original array’s lifetime ends. Long-term storage of a slice may therefore prolong the lifetime of elements that are no longer otherwise accessible, which can appear to be memory and object leakage.” https://developer.apple.com/documentation/swift/arrayslice https://developer.apple.com/documentation/swift/arrayslice Would it be acceptable to put these implementations in a Functional library?
- Someone 7y agoYes, it would. Returning an Array would require take to copy the data, slowing down your nice functional code.
- Tainnor 7y agoThis is because Swift is quite low-level when it comes to storage etc., so [0..<n] returns an ArraySlice. However, this has nothing to do with generics.If you're willing to sacrifice performance, you could easily write extension Array { func take(_ n: Int) -> [Element] { Array(self[0..<n]) } }