That’s why I provided two examples containing different types to illustrate what I meant.
I don’t believe you can add a generic function to the array to handle this.
In another repo, I’ve used the FloatingPoint protocol with some luck. However, this should also work with Int’s, for instance:
extension Array where Element: FloatingPoint {
var sum: Element {
self.reduce(0, +)
}
}
https://github.com/melling/data-science-from-scratch-swift/b...What’s wrong with something like this?
extension Array {
func take(_ n: Int) -> ArraySlice<Element> {
self[0..<n]
}
}
For your other example, you can make the function accept an array of Ints by constraining Element to AdditiveArithmetic instead of FloatingPoint. extension Sequence where Element: AdditiveArithmetic {
func sum() -> Element {
return reduce(.zero, +)
}
} [1,2,3].take(2)
[“a”,”b”,”c”].take(2)
[p1,p2,p3].take(2)
How much logic are we going to need to repeat for all the types for all the functions? 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
Would it be acceptable to put these implementations in a Functional library?
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])
}
}That one and the need for generic associatedTypes trip me up all the time.
I think about it every time I see new feature announcements like today's. The opportunity cost of the wasted effort, the new thing that will probably make things harder for everyone. Possibly including those who try to fulfill the generics manifesto.
One thing I wish Swift had was an easy way to add more generic functionality. For example, if I want to add drop(), dropWhile(), take(), takeWhile(),... there’s no nice way to extend Array
Btw, I’m working a Swift Cookbook for anyone who quickly wants to come up to speed on Swift. All open source. Feel free to comment or commit.https://github.com/melling/SwiftCookBook