함수란?

함수 선언시 가장 앞에 func 키워드를 붙이고 (person: String) 파라미터와 형 그리고 → String 형태로 반환형을 정의한다.

구조체, 클래스, 열거형 등 특정 타입에 연관되어 사용하는 함수를 method. 모듈 전체에서 전역적으로 사용할수 있는 함수를 그냥 함수라고 부른다.

func 함수 이름(매개변수...) -> 반환타입 {
	함수 실행 구문
		return 반환값
}
func introduce(name: String) -> String {
		//return + "제 이름은" + name + "입니다."
}

let introduceJenny: String = introduce(name: "Jenny")
print(introduceJenny)
func greet(person: String) -> String {
	let greeting = "Hello" + person + "!"
	return greeting
}

print(greet(person: "Anna"))  // prints "Hellos Anna!"

함수 파라미터와 반환 값 (Function Parameters and Return Values)


func sayHelloWorld() -> String {
	return "hello, world"
}

print(sayHelloWorld())  // Prinsts "hello, world"
func greet(person: String, alreadyGreeted: Bool) -> String {
	if alreadyGreeted {
		return greetAgain(person: person)
	} else {
		return greet(person: person, alreadyGreeted: alreadyGreeted)
	}
}

print(greet(person: "Tim", alreadyGreeted: true))  // Hello again, Tim!

엄밀히 말하면 위 함수는 반환 값을 선언하지 않았지만 반환 값이 있습니다. 반환 값이 정의 되지 않은 함수는 Void라는 특별한 형을 반환합니다. Void는 간단히 ()를 사용한 빈 튜플입니다.

func greet(person: String) {
	print("Hello, \\(person)!")
}
greet(person: "Dave")

→ 글자수 count 를 구할때 printAndCount(string: string) 이므로(String) count 가 무시될 수 있다,

func printAndCount(string: String) -> Int {
    print(string)
    return string.count
}
func printWithoutCounting(string: String) {
    let _ = printAndCount(string: string)
}
printAndCount(string: "hello, world")  // prints "hello, world" and returns a value of 12
printWithoutCounting(string: "hello, world")  // prints "hello, world" but does not return a value