Returns multiple values ​​from a function in swift

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

I'm trying to return the time of day, I need to return the Hour, Minute and Second as separate integers, but all in the same direction 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 use, I have problems 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 } 
+74
function return swift
Dec 17 '14 at 17:18
source share
4 answers

Return the tuple:

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

Then it is called as:

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

or

 let time = getTime() println("hour: \(time.0)") 
+157
Dec 17 '14 at 17:22
source share

also:

 func getTime() -> (hour: Int, minute: Int,second: Int) { let hour = 1 let minute = 2 let second = 3 return ( hour, minute, second) } 

Then it is called as:

 let time = getTime() print("hour: \(time.hour), minute: \(time.minute), second: \(time.second)") 

This is the standard way to use this word in the book "Fast programming language" written by Apple.

or also:

 let time = getTime() print("hour: \(time.0), minute: \(time.1), second: \(time.2)") 

it is the same, but less clear.

+49
Jul 30 '15 at 12:21
source share

you should return three different values ​​from this method and get these three in one variable like this.

 func getTime()-> (hour:Int,min:Int,sec:Int){ //your code return (hour,min,sec) } 

get value in one variable

 let getTime = getTime() 

now you can access hours, minutes and seconds simply by ".". i.e.

 print("hour:\(getTime.hour) min:\(getTime.min) sec:\(getTime.sec)") 
+6
Jun 16 '16 at 11:57
source share

Swift 3

 func getTime() -> (hour: Int, minute: Int,second: Int) { let hour = 1 let minute = 20 let second = 55 return (hour, minute, second) } 

Use:

 let(hour, min,sec) = self.getTime() print(hour,min,sec) 
+2
Sep 04 '17 at 12:04 on
source share



All Articles