How to collect the return value of a function (Swift 3)

南楼画角 提交于 2019-12-23 06:36:22

问题


Goal: I want to collect the return value of a function.

Question: How can I call the 'test' function to collect the return variable 'name' without passing through a parameter?

Is there a way to collect a variable(values) from functions with agruments(parameters) without passing through a parameter?

I have provided an example:

let userName = "Jake"
let userInfo = test(name: userName)

    func test(name: String) -> String {

        return name
    }

    // function call
    // Goal: I want to retrieve the function return value without passing a parameter
    let newUser = test()    

Does the function 'test' return value have to be stored to retrieve it? I want to retrieve the 'userName' Jake


回答1:


You can return like below,

let userName = "Jake" //Global variable of the class
let userInfo = test() //Jake

func test() -> String { //single - element tuple will don't have label for return.

   return self.userName
}

If you like to return with labels then you need tow or more return values like below,

   func test() -> (name:String,age:Int) {        
       return (self.userName,125)
    }

And access specific values by test().name



来源:https://stackoverflow.com/questions/44872388/how-to-collect-the-return-value-of-a-function-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!