KKendall - 1 year ago 31

Swift Question

Basically I want to be able to pass in either

`Set<Int>`

`[Int]`

`Int`

I would rather not have to convert

`[Int]`

`Set<Int>`

`[Int]`

`Set<Int>`

I use this function in many places and the callers sometimes care about order (

`[Int]`

`Set<Int>`

Something like this:

`extension SequenceType where Generator.Element: Int { }`

but as a parameter.

The

`Int`

`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 Source

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
```