Skip to content

Instantly share code, notes, and snippets.

@dfrib

dfrib/foo.swift Secret

Last active August 8, 2016 13:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfrib/e26e9cd00806c02d7a1861d2a4661a8f to your computer and use it in GitHub Desktop.
Save dfrib/e26e9cd00806c02d7a1861d2a4661a8f to your computer and use it in GitHub Desktop.
...
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 { }
// ...
@jay58
Copy link

jay58 commented Aug 8, 2016

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment