从swift中的函数返回多个值

时间:2014-12-17 17:18:34

标签: function swift return

如何从swift中的函数返回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
}

6 个答案:

答案 0 :(得分:250)

返回一个元组:

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

然后将其调用为:

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

或:

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

答案 1 :(得分:66)

此外:

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

这是如何在Apple编写的Swift Programming Language一书中使用它的标准方法。

或者就像:

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

它是相同但不太清楚。

答案 2 :(得分:10)

你应该从这个方法中返回三个不同的值,并将这三个值放在一个像这样的变量中。

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

答案 3 :(得分:5)

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)

答案 4 :(得分:2)

更新 Swift 4.1

在这里,我们创建一个结构来实现Tuple的用法并验证OTP文本长度。在此示例中,该字段必须为2个字段。

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

希望有帮助!

谢谢

答案 5 :(得分:0)

//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)")