도슐랭스타
iOS - 함수(1) 본문
Swift 함수 선언
func 함수이름(매개변수이름: 매개변수타입) -> 반환타입 {
// 함수 내부 코드
return 반환값
}
리턴값이 없으면 ->은 생략 가능
func sayHello() {
//리턴값 없으면( -> Void ) 지정하지 않아도 됨
print("Hello")
}
sayHello()
함수의 자료형
- 매개변수 자료형과 리턴값의 자료형이 나옴.
func add(x : Int, y : Int) -> Int {
return x+y
}
print(add(x:10,y:10))
print(type(of:add))
sayHello() 함수의 자료형은 () -> () 으로 나옴.
내부 매개변수 이름과 외부 매개변수 이름
func add(first x : Int, second y : Int) -> Int {
return x+y
}
- 외부 매개변수 이름 = first, second
- 내부 매개변수 이름 = x, y
이렇게 호출하면 에러가 뜸.
외부 매개변수를 사용하여 호출해야함.
func add(x : Int, y : Int) -> Int {
return x+y
}
print(add(x:10,y:10))
위 함수처럼 외부 매개변수를 생략하면 내부 매개변수가 외부 매개변수를 겸함.
외부 매개변수를 "_"으로 생략하거나 "with"를 사용하기도 함.
함수 선언의 예시
//1
func add(x : Int, y : Int) -> Int {
return x+y
}
print(add(x:10,y:20))
//2
func add1( _ x : Int, with y : Int) -> Int {
return x+y
}
print(add1(10,with:20))
//3
func add2(first x : Int,second y : Int) -> Int {
return x+y
}
print(add2(first:10,second:20))
//4
func add3(_ x : Int, _ y : Int) -> Int {
return x+y
}
print(add3(10,20))
함수명 호출
- print(#function)
func add(x : Int, y : Int) -> Int {
print(#function)
return x+y
}
print(add(x:10,y:20))
//1
func add(x : Int, y : Int) -> Int {
print(#function)
return x+y
}
print(add(x:10,y:20))
//2
func add1( _ x : Int, with y : Int) -> Int {
print(#function)
return x+y
}
print(add1(10,with:20))
//3
func add2(first x : Int,second y : Int) -> Int {
print(#function)
return x+y
}
print(add2(first:10,second:20))
//4
func add3(_ x : Int, _ y : Int) -> Int {
print(#function)
return x+y
}
print(add3(10,20))
"함수이름(외부매개변수:외부매개변수:)" 까지가 다 함수명임.
반응형
'iOS' 카테고리의 다른 글
iOS - first class object, first class citizen(1급 객체, 1급 시민) (0) | 2024.10.14 |
---|---|
iOS - 함수(2) (0) | 2024.10.14 |
iOS - 연산자와 옵셔널 (1) | 2024.09.25 |
iOS-2차시 (0) | 2024.09.11 |
iOS-OT (0) | 2024.09.04 |
Comments