从一个函数返回多个值

我如何从一个快速的函数返回3个相同类型(Int)的独立数据值?

我试图返回一天中的时间,我需要将小时,分钟和秒作为单独的整数返回,但是从同一个函数一次性返回,这可能吗?

我想我只是不明白返回多个值的语法。这是我正在使用的代码,我在最后一行(返回)中遇到了麻烦。

任何帮助都将不胜感激!

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
}
117366 次浏览

返回元组:

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

然后它被调用为:

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

或:

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

另外:

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

然后它被调用为:

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

这是在苹果编写的《快速编程语言》一书中使用它的标准方法。

或者就像这样:

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

是一样的,但不那么清晰。

您应该从该方法返回三个不同的值,并在一个单独的变量中获得这三个值,如下所示。

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

得到单个变量的值

let getTime = getTime()

现在你可以通过简单的“ .”来访问小时、分和秒。

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

Swift 3

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

使用方法:

let(hour, min,sec) = self.getTime()
print(hour,min,sec)
//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)")

更新 Swift 4.1

在这里,我们创建一个结构来实现 Tuple 的使用并验证 OTP 文本长度。这个例子需要两个字段。

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)
}
}

用法:

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

希望能有帮助!

谢谢