๋ณธ ๋ธ๋ก๊ทธ์ ๋ด์ฉ์ ๋ช๋ช ํ์ต ๊ธฐ๊ด๋ค์ ์๋ฃ๋ฅผ ์ฐธ๊ณ ํ์ฌ ์ ์ ์ค์ค๋ก ํ์ตํ ๋ด์ฉ์ด๊ธฐ์ ํ๋ฆฐ ๋ด์ฉ์ด ํฌํจ๋์ด ์์ ์ ์์ต๋๋ค. ์ค๋ฅ๋ฅผ ๋ฐ๊ฒฌํ์ค ๊ฒฝ์ฐ ๋๊ธ์ ๋จ๊ฒจ์ฃผ์๊ธฐ๋ฅผ ๋ถํ๋๋ฆฝ๋๋ค. ๐๐ป
func ํจ์์ด๋ฆ (๋งค๊ฐ๋ณ์1: type, ๋งค๊ฐ๋ณ์2: type) -> ๋ฐํ๊ฐ{
์ํ๋ ํจ์ ๊ธฐ๋ฅ
return
}
ํจ์์ด๋ฆ(๋งค๊ฐ๋ณ์1, ๋งค๊ฐ๋ณ์2)
// return ๊ฐ
func ํจ์์ด๋ฆ (์ ๋ฌ์ธ์1 ๋งค๊ฐ๋ณ์1: type, ...) -> ๋ฐํํ์
{
ํจ์ ๊ธฐ๋ฅ
return
}
ํจ์์ด๋ฆ(์ ๋ฌ์ธ์1: ๋งค๊ฐ๋ณ์)
// return
func greeting(to friend: String, frome me: String) {
print("Hello \(friend)! I'm \(me)")
}
greeting(to: "hana", from: "yagom")
// Hello hana! I'm yagom
func sayHelloToFrinds(me: String, friends: String...) -> String {
return "Hello \(friends)! I'm \(me)!"
}
print(sayHelloToFriends(me: "yagom", friends: "hana", "eric", "wing"))
//Hello ["hana", "eric", "wing"]! I'm yagom!
func sayHelloToFrinds(me: Terry, friends: String...) -> String {
return "Hello \(friends)! I'm \(me)!"
}
print(sayHelloToFriends(friends: "hana", "eric", "wing"))
//Hello ["hana", "eric", "wing"]! I'm Terry!
//me: Terry๋ฅผ ๊ธฐ๋ณธ์ผ๋ก ์ง์ ํด์ฃผ์๊ธฐ์, ๋งค๊ฐ๋ณ์ friends๋ง ์
๋ ฅํด๋ ํจ์ ์คํ๊ฐ๋ฅ
var ํจ์๋ช
: (type, type...) -> returntype = ํ ๋นํจ์๋ช
(๋งค๊ฐ๋ณ์1, ๋งค๊ฐ๋ณ์2...)
print(1, 2, 3)
1 2 3
print(1, 2, 3, seperator: "!")
1!2!3
print(1, 2, 3, separator: "")
123
print("์์ํ :")
print("์ํ")
์์ํ :
์ํ
print("์์ํ", terminator: ":")
print("์ํ")
์์ํ : ์ํ
func isEven(num: Int) -> Bool {
var decider = num%2
return decider == 0
}
isEven(num: 10) // True
func calculateAgeRange(calYear: Int, birthYear: Int) -> String {
var number = (calYear - birthYear) - (calYear - birthYear)%10
return "\(number) ๋"
}
calculateAgeRange(calYear: 2021, birthYear: 1993) // 20 ๋
var fruitName = "์ฌ๊ณผ"
if fruitName == "์ฌ๊ณผ" {
print("์ ๊ฐ ์ข์ํ๋ ์ฌ๊ณผ๋ค์!")
} else if fruitName == "๋ธ๊ธฐ" {
print("๋ธ๊ธฐ๋ ๋
ผ์ฐ ๋ธ๊ธฐ")
} else if fruitName == "์๋ฐ" {
print("์ฌ๋ฆ์ ์ญ์ ์๋ฐ!")
} else {
print("๋ค๋ฅธ ๊ณผ์ผ๋ค๋ ๋ง์์ฃ !")
}
var fruitName = "์ฌ๊ณผ"
switch fruitName {
case "์ฌ๊ณผ":
print("์ ๊ฐ ์ข์ํ๋ ์ฌ๊ณผ๋ค์!")
case "๋ธ๊ธฐ":
print("๋ธ๊ธฐ๋ ๋
ผ์ฐ ๋ธ๊ธฐ")
case "์๋ฐ":
print("์ฌ๋ฆ์ ์ญ์ ์๋ฐ!")
default:
print("๋ค๋ฅธ ๊ณผ์ผ๋ค๋ ๋ง์์ฃ !")
}
func printGugudan(dan: Int) {
for time in 1...9 {
print("\(dan) * \(time) = \(dan * time)")
}
}
printGugudan(dan:2)
์ถ๋ ฅ
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
var people = ["์ฒ ์","์ํฌ","๋ฏผ์","ํ์ค","๊ธฐ๋จ","๋ํฌ"]
for person in people {
print(person)
}
Referance
์ผ๊ณฐ์์นด๋ฐ๋ฏธ ์ฝ๋ฉ์คํํฐ ๊ฐ์ ์๋ฃ