-
-
Save dfrib/e26e9cd00806c02d7a1861d2a4661a8f to your computer and use it in GitHub Desktop.
...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protocol Addable { | |
func +(_: Self, rhs: Self) -> Self | |
} | |
protocol Divisable { | |
func /(_: Self, rhs: Self) -> Self | |
} | |
protocol InitializableByInt { | |
init(_: Int) | |
} | |
extension Array where Element : | |
protocol<Addable, Divisable, InitializableByInt> { | |
func average() -> Element? { | |
var sum : Element | |
if self.isEmpty { | |
return nil | |
} | |
else { | |
sum = self.first! | |
for i in 1 ..< self.count { | |
sum = sum + self[i] | |
} | |
return sum/Element(self.count) | |
} | |
} | |
} | |
// or, in shorter form | |
extension Array where Element : | |
protocol<Addable, Divisable, InitializableByInt> { | |
func average() -> Element? { | |
guard !self.isEmpty else { return nil } | |
return self.reduce(Element(0), combine: +) / Element(self.count) | |
} | |
} | |
// note, however, that you'd need to explicitly conform types to | |
// your custom protocols, which makes it much easier to simply make | |
// use of the Swift native protocols. | |
extension Double: Addable, Divisable, InitializableByInt { } | |
// ... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Still I am getting the same error as i mentioned you, what should I do?
after this
var array1 = [10,20,30]
array1.average() //error line