在swift中从函数返回多个值

在swift中从函数返回多个值

本文介绍了在swift中从函数返回多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从swift函数中返回3个相同类型(Int)的独立数据值?我试图返回一天中的时间,我需要返回小时,分钟和秒作为单独的整数,但所有在一个去从同一个函数,这是可能的吗?



我想我只是不理解返回多个值的语法。这是我正在使用的代码,我在最后(返回)行遇到问题。



任何帮助都将不胜感激!

  func getTime() - > Int 
{
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitSecond,fromDate:日期)
let hour = components.hour
let minute = components.minute
let second = components.second
let times:String =(\(hour):\\ \\(分钟):\(秒))
返回小时,分钟,秒钟
}




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

然后调用它:

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

或者:

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


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
}
解决方案

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

这篇关于在swift中从函数返回多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 04:04