Created
October 16, 2021 10:19
-
-
Save deathlezz/07772d21da67d70e00de61ecceadc846 to your computer and use it in GitHub Desktop.
Simple use of functions in Swift 5.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Simple use of functions | |
// | |
// basic function | |
func description() { | |
print("Here's Johnny!") | |
} | |
description() // Here's Johnny! | |
// accepting parameters | |
func square(number: Int) { | |
print(number * number) | |
} | |
square(number: 8) // 64 | |
// returning values | |
func double(number: Int) -> Int { | |
return number * 2 | |
} | |
print(double(number: 8)) // 16 | |
// default parameters | |
func user(name: String, hasAccount: Bool = true) { | |
if hasAccount { | |
print("Welcome back \(name)!") | |
} else { | |
print("You must register first.") | |
} | |
} | |
user(name: "Garry") // Welcome back Garry! | |
// variadic function | |
func isEven(numbers: Int...) { | |
let check = numbers.filter {$0 % 2 == 0} | |
print(check) | |
} | |
isEven(numbers: 1, 2, 3, 4, 5, 6) // [2, 4, 6] | |
// inout parameters | |
func add(number: inout Int) { | |
number += 10 | |
} | |
var number = 5 | |
add(number: &number) | |
print(number) // 15 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment