OllieGreen - 7 months ago 16

Swift Question

How do I return 3 separate data values of the same type(Int) from a function in swift?

I'm attempting to return the time of day, I need to return the Hour, Minute and Second as separate integers, but all in one go from the same function, is this possible?

I think I just don't understand the syntax for returning multiple values. This is the code I'm using, I'm having trouble with the last(return) line.

Any help would be greatly appreciated!

`func getTime() -> Int`

{

let date = NSDate()

let calendar = NSCalendar.currentCalendar()

let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitSecond, fromDate: date)

let hour = components.hour

let minute = components.minute

let second = components.second

let times:String = ("\(hour):\(minute):\(second)")

return hour, minute, second

}

Answer

Return a tuple:

```
func getTime() -> (Int, Int, Int) {
...
return ( hour, minute, second)
}
```

Then it's invoked as:

```
let (hour, minute, second) = getTime()
```

or:

```
let time = getTime()
println("hour: \(time.0)")
```