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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With