快速从函数中返回多个值

Return multiple values from a function in swift(快速从函数中返回多个值)

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

问题描述

如何从 swift 中的函数返回 3 个相同类型(Int)的单独数据值?

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.

任何帮助将不胜感激!

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
}

推荐答案

返回一个元组:

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

然后它被调用为:

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

或:

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

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

本文标题为:快速从函数中返回多个值

基础教程推荐