Based on the question, Int and Double both conform to these protocols:
BindableData - RealityKit
CustomReflectable
Decodable
Encodable
Hashable
MLDataValueConvertible - CreateML
SIMDScalar
I tried extending Decodable, and it’s not compiling:
// try #1
extension Decodable {
func sum() -> AnyObject {
let numbers = [AnyObject]()
var total = 0
for i in 0..<numbers.count {
total += numbers[i] // error -- cannot convert to expected type Int
}
return total as AnyObject
}
}
I’m trying to use AnyObject as a catch-all for Int and Double; I don’t know another way to accommodate just these two data types.
Did anyone try to extend a different protocol?
I think I tried Decodable also (or maybe it was SIMDScalar) & had a similar problem. I eventually found one that worked but it was one or two steps removed - it was not a protocol directly mentioned by either Double or Integer. IIRC, it was easier to find by looking at Double rather than Integer.
I tried extending CustomStringConvertible to output a String, didn’t take either:
// try #2
extension CustomStringConvertible {
func sum() -> String {
let numbers = [AnyObject]()
var total = 0.0
for i in 0..<numbers.count {
total += numbers[i] as AnyObject as! Double // Cannot convert value of type 'AnyObject' to expected argument type 'Double' so I clicked 'Fix' to add the addition 'as! Double'
}
return "\(total)"
}
}
// silver challenge output
[4, 8, 15, 16, 23, 42].sum // () -> String
[80.5, 9.6].sum // () -> String
Do I revert to AnyObject like in my first try? If so, how do I code for outputting a sum with a matching type of the array?
You’re extending the wrong thing.
Back on page 316 they showed how you could extend Sequence in a way that would only apply to sequences containing elements conforming to the Exercise protocol. The goal here is to do something similar but instead of Exercise you need some other constraint on Element, one that specifies Element is something that can be added together. The challenge is to find a protocol that specifies that & use it as part of your extension of Sequence.
1 Like
I don’t know why it took me too long to find “Numeric Protocols” in the Developer Documentation:
// try #8
extension Sequence where Element: AdditiveArithmetic {
func sum() -> Element {
return reduce(.zero, +)
}
}
// silver challenge output
let intSum = [4, 8, 15, 16, 23, 42].sum() // 108
let doubleSum = [80.5, 9.6].sum() // 90.1
1 Like