KKendall KKendall - 4 months ago 6
Swift Question

Function parameter where I can pass in Set<Int> or [Int]

Basically I want to be able to pass in either

Set<Int>
or
[Int]
Or any thing where at the very least, I can iterate through an unordered set of
Int
.

I would rather not have to convert
[Int]
to a
Set<Int>
(and vice versa). And I would like to avoid making to functions that require something different (
[Int]
or
Set<Int>
) but do the same thing, which is what I'm doing now.

I use this function in many places and the callers sometimes care about order (
[Int]
) and sometimes not (
Set<Int>
). But the function does not require any specific order.




Something like this:

extension SequenceType where Generator.Element: Int { }


but as a parameter.




Function Example (as requested):

The
Int
as explained above was just for simplification, my example is some data object.

struct TextNumber {
let text: String
let number: Int
}


And here is the essentials of what I want to do with the data.

func sendUpTextNumberArray(arrayOfTextNumber: [TextNumber]) {
var convertedData = [[String:AnyObject]]()
for textNumber in arrayOfTextNumber {
convertedData.append(textNumber.convert())
}
Service.sendJSON(convertedData)
}

Answer

You can do as follow:

Swift 2

let setOfIntegers = Set([1,2,3])
let arrayOfIntegers = [1,2,3]

func sum<T: SequenceType where T.Generator.Element == Int>(integers: T) -> T.Generator.Element {
    return integers.reduce(0, combine: +)
}

sum(arrayOfIntegers)  // 6
sum(setOfIntegers)    // 6

Swift 3

func sum<T: Sequence where T.Iterator.Element == Int>(_ integers: T) -> T.Iterator.Element {
    return integers.reduce(0, combine: +)
}

sum(arrayOfIntegers)  // 6
sum(setOfIntegers)    // 6