Return multiple values from a function in swift
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
}
Solution 1:
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)")
Solution 2:
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.
Solution 3:
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)")
Solution 4:
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)
Solution 5:
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