Tham số hàm Swift và giá trị trả về (có ví dụ)

Trong bài viết này, bạn sẽ tìm hiểu về các hàm do người dùng định nghĩa khác nhau nhận đầu vào của các loại khác nhau và trả về đầu ra, với các ví dụ.

Trong bài viết trước Swift Functions, chúng ta đã tìm hiểu về các hàm. Bây giờ, chúng ta sẽ xem xét các cách và kiểu khác nhau mà chúng ta có thể tạo một hàm trong Swift, tức là xử lý đầu vào và đầu ra trong một hàm.

Hàm không có tham số và không có giá trị trả về

Loại hàm này không nhận bất kỳ giá trị đầu vào và trả về nào.

 func funcname () (// câu lệnh) HOẶC func funcname () -> () (// câu lệnh) HOẶC func funcname () -> Void (// câu lệnh)

Tất cả các cú pháp trên đều hợp lệ để tạo một hàm không nhận tham số và không trả về giá trị.

Cú pháp trên func funcname() -> ()cũng tương đương với func funcname() -> Voidbởi vì Voidchỉ là một kiểu chữ của (). Bạn có thể truy cập Swift Typealias để tìm hiểu thêm.

Ví dụ 1: Không có tham số nào được truyền và không có giá trị trả về

 func greetUser() ( print("Good Morning!") ) greetUser() 

Khi bạn chạy chương trình trên, kết quả đầu ra sẽ là:

 Buổi sáng tốt lành!

Hàm không có tham số nhưng trả về giá trị

Loại hàm này không nhận bất kỳ tham số đầu vào nào mà trả về một giá trị. Để thêm kiểu trả về, bạn cần thêm mũi tên ( ->) và kiểu trả về.

 func funcname () -> ReturnType (// câu lệnh trả về giá trị)

Ví dụ 2: Không có tham số nào được truyền nhưng trả về giá trị

 func greetUser() -> String ( return "Good Morning!" ) let msg = greetUser() print(msg) 

Khi bạn chạy chương trình trên, kết quả đầu ra sẽ là:

 Buổi sáng tốt lành!

Trong chương trình trên, bạn đã xác định được Kiểu trả về String. Bây giờ, câu lệnh phải trả về một chuỗi từ câu lệnh bên trong hàm, nếu không bạn sẽ gặp lỗi.

returntừ khóa chuyển quyền điều khiển chương trình từ phần thân của hàm sang lời gọi hàm. Nếu bạn cần trả về giá trị từ hàm, hãy thêm giá trị sau returntừ khóa.

return "Good Morning!"câu lệnh trả về giá trị kiểu Stringtừ hàm. Lưu ý rằng loại trả về và giá trị phải khớp với nhau.

Bạn cũng có thể gán giá trị trả về cho một biến hoặc một hằng số. let msg = gán giá trị trả về cho hằng số msg. Vì vậy, câu lệnh print(msg)xuất ra Chào buổi sáng! trong bảng điều khiển.

Nếu bạn muốn bỏ qua giá trị, bạn có thể chỉ cần sử dụng _như let _ =.

Hàm có tham số nhưng không có giá trị trả về

Các tham số được sử dụng để lấy đầu vào trong hàm. Tham số chứa tên tham số và kiểu được theo sau bởi dấu hai chấm ( :). Loại hàm này nhận tham số đầu vào nhưng không trả về giá trị.

 func funcname (tên tham số: Loại) (// câu lệnh)

Ví dụ 3: Các tham số được truyền nhưng không có giá trị trả về

 func greetUser(msg:String) ( print(msg) ) greetUser(msg: "Good Morning!") 

Khi bạn chạy chương trình trên, kết quả đầu ra sẽ là:

 Buổi sáng tốt lành!

Trong chương trình trên, hàm chấp nhận một tham số kiểu duy nhất String. Tham số chỉ có thể được sử dụng bên trong hàm. msg là tên của tham số.

Bạn có thể gọi hàm bằng cách chuyển cho nó một giá trị chuỗi với tên tham số là greetUser(msg: "Good Morning!"). Tên tham số msg chỉ hiển thị bên trong hàm greetUser().

Do đó, câu lệnh print(msg)xuất ra Good Morning! trong bảng điều khiển.

Hàm với tham số và giá trị trả về

Loại hàm này nhận tham số và cũng trả về giá trị.

 func funcname (tham sốName: Type) -> ReturnType (// câu lệnh)

Ví dụ 4: Các tham số được truyền và trả về giá trị

 func greetUser(name:String) -> String ( return "Good Morning! " + name ) let msg = greetUser(name: "Jack") print(msg) 

Khi bạn chạy chương trình trên, kết quả đầu ra sẽ là:

Buổi sáng tốt lành! Jack

Trong chương trình trên, hàm chấp nhận một tham số duy nhất của kiểu Stringvà cũng trả về giá trị Good Morning! Jack loại String.

Hàm với nhiều tham số và nhiều giá trị trả về

Loại hàm này nhận nhiều tham số được phân tách bằng dấu phẩy và cũng trả về nhiều giá trị. Bạn có thể trả về nhiều giá trị trong Swift bằng Tuples. Xem Swift Tuples để tìm hiểu thêm về nó.

 func funcname (tham sốName: Loại, tham sốName2: Loại,…) -> (ReturnType, ReturnType…) (// câu lệnh)

Ví dụ 5: Nhiều tham số được truyền và nhiều giá trị trả về

 func greetUser(name:String, age:Int) -> (String, Int) ( let msg = "Good Morning!" + name var userage = age if age < 0 ( userage = 0 ) return (msg, userage) ) let msg = greetUser(name: "Jack", age: -2) print(msg.0) print("You have (msg.1) coins left") 

Khi bạn chạy chương trình trên, kết quả đầu ra sẽ là:

 Chào buổi sáng! Jack Bạn còn 0 xu 

Trong chương trình trên, hàm greetUser()chấp nhận nhiều tham số kiểu StringInt. Hàm cũng trả về nhiều giá trị dưới dạng một bộ loại StringInt.

Để truy cập từng giá trị trả về, chúng tôi sử dụng các vị trí chỉ mục 0, 1,… Ở đây, chúng tôi đã sử dụng msg.0 để truy cập vào Good Morning! Jack và msg.1 để truy cập 0 .

Đôi khi việc sử dụng các vị trí chỉ mục có thể không trực quan và không thể đọc được. Chúng tôi có thể giải quyết vấn đề này một cách dễ dàng bằng cách đặt tên để trả về giá trị. Chương trình trên cũng có thể được viết lại như dưới đây.

Example 6: Multiple return values with name

 func greetUser(name:String, coins:Int) -> (name:String, coins:Int) ( let msg = "Good Morning!" + name var userCoins = coins if coins < 0 ( userCoins = 0 ) return (msg, userCoins) ) let msg = greetUser(name: "Jack",coins: -2) print(msg.name) print("You have (msg.coins) coins left") 

In this program, the return type is of tuple that contains the variable name with the type. The main advantage of this is you can access the result using the variable name as msg.name and msg.coins instead of msg.0 and msg.1.

Function with argument label

When you define a function that accepts inputs, you can define the input name with the help of parameter name. However, there is another type of name which you can give along with the parameter name, known as argument label.

The use of argument labels allow a function to be called in an expressive way, sentence-like manner, while still providing a function body that is readable and clear in intent.

Each function parameter has both an argument label and a parameter name. By default, parameters use their parameter name as their argument label. But, if you explicitly define the argument name, the argument label is used when calling the function.

The syntax of function with argument label is

 func funcname(argumentLabel parameterName:Type)-> Return Type ( //statements )

Let's see this in example below.

Example 7: Function without argument label

 func sum(a:Int, b:Int) -> Int ( return a + b ) let result = sum(a: 2, b: 3) print("The sum is (result)") 

When you run the above program, the output will be:

 The sum is 5

In the above example, we have not specified the argument label, so it takes default parameter name a and bas the argument label while calling the function.

You may notice the function call is not expressive/sentence when calling the function. You may think it can be made more expressive as English if you could make the function call as:

 let result = sum(of: 2, and: 3)

Now let's change the function as:

Example 8: Function with better function call but not as parameter names

 func sum(of:Int, and:Int) -> Int ( return of + and ) let result = sum(of: 2, and: 3) print("The sum is (result)") 

Now the method call is expressive. However, now we have to use the parameter name of & and in return of + and to find the sum of two numbers. Now, this makes the function body unreadable. Use of a and b instead of of&and would make more sense inside the function body.

For this purpose we have to explicitly define argument label as:

Example 9: Function with argument labels

 func sum(of a :Int, and b:Int) -> Int ( return a + b ) let result = sum(of: 2, and: 3) print("The sum is (result)") 

In the above program, the function accepts two parameter of type Int. The function call uses the argument label of & and which makes sense while calling the function as sum(of: 2, and: 3) instead of sum(a: 2, b: 3).

Also, the function body uses the parameter name a and b instead of of & and which also makes more sense while applying operations.

You can also omit the argument label by writing a _ before the parameter name.

 func sum(_ a :Int, _ b:Int) -> Int ( return a + b ) let result = sum(2, 3) print("The sum is (result)") 

Function with default parameter values

You can give default values for any parameter in a function by assigning a value to the parameter after that parameter's type. Giving a default parameter allows you to neglect the parameter while calling the function.

If you do not pass value to the parameter while calling the function, its default value is used. However, if you explicitly pass a value to the parameter while calling, the specified value is used.

 func funcname(parameterName:Type = value) -> Return Type ( //statements )

Example 10: Function with default parameter values

 func sum(of a :Int = 7, and b:Int = 8) -> Int ( return a + b ) let result1 = sum(of: 2, and: 3) print("The sum is (result1)") let result2 = sum(of: 2) print("The sum is (result2)") let result3 = sum(and: 2) print("The sum is (result3)") let result4 = sum() print("The sum is (result4)") 

When you run the above program, the output will be:

 The sum is 5 The sum is 10 The sum is 9 The sum is 15 

In the above program, the function sum(of a :Int = 7 , and b:Int = 8) -> Int accepts two parameter of type Int but also specifies the default value of parameter a = 7 and b = 8.

If you pass value as a parameter in the function call as sum(of: 2, and: 3) then 2 and 3 is used instead of parameter default value.

But if you don't pass the parameter value as sum() , then default value 7 and 8 are used as the parameter value.

Function with variadic parameters

A variadic parameter can accept zero or more values of a specific type. You can specify variadic parameter by inserting three period characters (… ) after the parameter's type name.

You usually use a variadic parameter when you need to pass a varying number of input values to the parameter when the function is called. For example, a list of numbers, a list of alphabets, etc.

The syntax of function with variadic parameters is:

 func funcname(parameterName:Type… ) -> Return Type ( //statements )

Example 11: Function with variadic parameters

 func sum(of numbers:Int… ) ( var result = 0 for num in numbers ( result += num ) print("The sum of numbers is (result)") ) sum(of: 1, 2, 3, 4, 5, 6, 7, 8) 

In the above program, the function sum(of numbers:Int… ) accepts a variadic parameter of type Int. A variadic parameter can accept multiple values separated by comma as sum(of: 1, 2, 3, 4, 5, 6, 7, 8).

The values 1, 2, 3, 4, 5, 6, 7, 8 passed as a variadic parameter are made available within the function's body as an array of the Int type. Therefore, we can apply for-in loop in the value as for num in numbers.

When you run the above program, the output will be:

 The sum of numbers is 36

Note: Swift built in print() function also accepts variadic parameter of type Any.

Any represents to any data type in Swift e.g. Int, Float, Double,String etc.

Function with in-out parameters

When you define the function parameter, the function parameters cannot be modified inside the body. So they are constants by default. Let's see this in example:

 func process(name:String) ( if name == ""( name = "guest" ) ) 

The above program results a compile-time error because you cannot change the value of a parameter.

If you want a function to modify a parameter's value, you need to define the parameter as in-out parameter. You write an in-out parameter by placing the inout keyword right before a parameter's type.

Behind the scenes, an in-out parameter has a value that is passed into the function, is modified by the function, and is passed back out of the function to replace the original value. Therefore the value passed in the function call cannot be a constant. You must declare it as a variable.

The syntax of function with inout parameter is:

 func funcname(parameterName:inout Type) -> Return Type ( //statements )

Example 12: Function with in out parameter

 func process(name:inout String) ( if name == ""( name = "guest" ) ) var userName = "" process(name: &userName) print(userName) 

When you run the above program, the output will be:

 guest

In the above program, we have declared a function that accepts inout parameter name so that the parameter can be changed/altered inside the body of the function.

You must use ampersand (&) sign directly before a variable's name when you pass argument to an in-out parameter so that it can be modified by the function.

thú vị bài viết...