178

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
}
2
  • 1
    return NSArray(objects: hour, minute, second)
    – Amr Hossam
    Commented Dec 17, 2014 at 17:22
  • 5
    The "Swift Programming Language" iBook actually has a section titled "Functions with Multiple Return Values" ...
    – Martin R
    Commented Dec 17, 2014 at 17:53

6 Answers 6

371

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)")
7
  • 30
    Note that a better solution might be to define a Time struct and use that instead of the tuple. Commented Dec 17, 2014 at 17:23
  • 1
    How would you call that swift func from an objective C method? Curious how you would gain a handle to three returned values. Would you use a dictionary, for example?
    – phil
    Commented Dec 18, 2014 at 22:51
  • 1
    You wouldn't. If you want to call it from objc you have to return a class (maybe a struct) not sure. Commented Dec 19, 2014 at 7:21
  • 7
    It's recommended to add name to the parameters: func getTime() -> (hour: Int, minute: Int,second: Int) Then get like getTime().hour Commented Sep 3, 2015 at 19:19
  • @BrunoLemos eh, I'm still going to go with the better solution is to define a Time struct and use that. Commented Sep 3, 2015 at 20:52
87

Also:

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

Then it's invoked as:

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

This is the standard way how to use it in the book The Swift Programming Language written by Apple.

or just like:

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

it's the same but less clearly.

6
  • 1
    the right answer can't compile right in swift 2.0: wrong, returning an unnamed tuple in Swift 2 works the same as with Swift 1. See this screenshot.
    – Eric Aya
    Commented Jul 30, 2015 at 12:26
  • yes, you are right , but I get a compile error in a similarity context. I should find it why.
    – jtianling
    Commented Jul 30, 2015 at 12:29
  • The compile error was not related, it was because of the CalendarUnit format having changed in Swift 2, not the tuple format.
    – Eric Aya
    Commented Jul 30, 2015 at 12:30
  • Not like that, the compile error I talked about was appear in the code myself.
    – jtianling
    Commented Jul 30, 2015 at 12:33
  • time.hour won't work anymore. Please update the code. Commented Aug 20, 2019 at 7:15
15

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

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

get the value in single variable

let getTime = getTime()

now you can access the hour,min and seconds simply by "." ie.

print("hour:\(getTime.hour) min:\(getTime.min) sec:\(getTime.sec)")
10

Swift 3

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

To use :

let(hour, min,sec) = self.getTime()
print(hour,min,sec)
8

Update Swift 4.1

Here we create a struct to implement the Tuple usage and validate the OTP text length. That needs to be of 2 fields for this example.

struct ValidateOTP {
var code: String
var isValid: Bool }

func validateTheOTP() -> ValidateOTP {
    let otpCode = String(format: "%@%@", txtOtpField1.text!, txtOtpField2.text!)
    if otpCode.length < 2 {
        return ValidateOTP(code: otpCode, isValid: false)
    } else {
        return ValidateOTP(code: otpCode, isValid: true)
    }
}

Usage:

let isValidOTP = validateTheOTP()
    if isValidOTP.isValid { print(" valid OTP") } else {   self.alert(msg: "Please fill the valid OTP", buttons: ["Ok"], handler: nil)
    }

Hope it helps!

Thanks

1
1
//By : Dhaval Nimavat
    import UIKit

   func weather_diff(country1:String,temp1:Double,country2:String,temp2:Double)->(c1:String,c2:String,diff:Double)
   {
    let c1 = country1
    let c2 = country2
    let diff = temp1 - temp2
    return(c1,c2,diff)
   }

   let result = 
   weather_diff(country1: "India", temp1: 45.5, country2: "Canada", temp2:    18.5)
   print("Weather difference between \(result.c1) and \(result.c2) is \(result.diff)")
1
  • Output : Weather difference between India and Canada is 27.0 Commented Jul 12, 2018 at 5:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.