Skip to content

Instantly share code, notes, and snippets.

@scotteg
Last active August 29, 2015 14:06
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 scotteg/aa20228503f8151186fd to your computer and use it in GitHub Desktop.
Save scotteg/aa20228503f8151186fd to your computer and use it in GitHub Desktop.
Example of a Swift class subscript that takes a variadic parameter and returns a tuple
class Introspector {
var values: Any!
subscript(theValues: Int...) -> (sum: Int, average: Double) {
values = theValues
var sum = 0
for integer in theValues {
sum += integer
}
let average = Double(sum) / Double(theValues.count)
return (sum: sum, average: average)
}
subscript(theValues: Double...) -> (sum: Double, average: Double) {
values = theValues
var sum = 0.0
for value in theValues {
sum += Double(value)
}
let average = sum / Double(theValues.count)
return (sum: sum, average: average)
}
}
let myIntrospector = Introspector()
let result1 = myIntrospector[1, 2, 3, 4, 5]
println("For \(myIntrospector.values), sum is \(result1.sum) and average is \(result1.average).") // Prints "For [1, 2, 3, 4, 5], sum is 15 and average is 3.0."
let result2 = myIntrospector[1.1, 2.2, 3.3, 4.4, 5.5]
println("For \(myIntrospector.values), sum is \(result2.sum) and average is \(result2.average).") // Prints "For [1.1, 2.2, 3.3, 4.4, 5.5], sum is 16.5 and average is 3.3."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment