Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a tuple in Swift

sorry for such a basic question but I ve only just started working with tuples

this is my code

func test() -> (authorName:String, numberOfViews:Int) {

    let author : String = ""
    let numberViews = 0


    return(authorName : author, numberOfView : numberViews)


}

can anyone provide the correct way to do this

thanks in advance

like image 607
Richy Garrincha Avatar asked Nov 10 '14 18:11

Richy Garrincha


People also ask

How do I return a tuple in Swift?

Returning a Tuple from a Function If you didn't want to name them in the function prototype, that is okay as well, you just have to state the types, so stating the return type specifically as ” (String, Int) ” is also acceptable to the Swift compiler.

How do I return multiple items in Swift?

Swift's functions have a single return type, such as Int or String , but that doesn't mean we can only return a single value. In fact, there are two ways we can send back multiple pieces of data: Using a tuple, such as (name: String, age: Int) Using some sort of collection, such as an array or a dictionary.

Can a function return two values Swift?

Tuples can be used to return multiple values from Swift functions. A tuple allows you to group together multiple values of different types which can then be returned from a function as a single entity.

How do you return in Swift?

If you want to return your own value from a function, you need to do two things: Write an arrow then a data type before your function's opening brace, which tells Swift what kind of data will get sent back. Use the return keyword to send back your data.


1 Answers

according to the Apple's swift book:

func test() -> (authorName:String, numberOfViews:Int) {

let author : String = ""
let numberViews = 0


return(author, numberViews)
}

you define the return object at the declaration. and in the return statement just put the values.

like image 56
gutte Avatar answered Oct 24 '22 08:10

gutte