Swift의 closure 

func add(x: Int, y: Int) -> Int {
return(x+y)
}
print(add(x:10, y:20))


let addf = {  (x:Int, y:Int) -> Int in
return (x+y)
}

print(addf(x:3, y:4))
//--> print(addf(3,4)

//main.swift:11:11: error: extraneous argument labels 'x:y:' in call
//print(addf(x:3, y:4)

closure로 호출할 시에는 argument label이 필요하지 않습니다

 

func mul(a: Int, b: Int) -> Int {
    return a * b
}
let multiply = {(a: Int, b: Int) -> Int in
    return a * b
}
print(mul(a:10, b:20))
print(multiply(10, 20))

let add = {(a: Int, b: Int) -> Int in
    return a + b
}
print(add(10, 20)) 

func math(x: Int, y: Int, cal: (Int, Int) -> Int) -> Int {
    return cal(x, y)
}
var result = math(x: 10, y: 20, cal: add) //return add(10,20)
print(result)
result = math(x: 10, y: 20, cal: multiply)//return multiply(10,20)
print(result)
result = math(x: 10, y: 20, cal: {(a: Int, b: Int) -> Int in
    return a + b
}) //클로저 소스를 매개변수에 직접 작성
print(result)
result = math(x: 10, y: 20) {(a: Int, b: Int) -> Int in
    return a + b
}//trailing closure
print(result)

후행 클로저(trailing closure)

 클로저가 함수의 마지막 argument라면 마지막 매개변수명(cl)을 생략한 후 함수 소괄호 외부에 클로저를 작성

func someFun(cl: () -> Void) {
}
// trailing closure를 사용 안하면
someFun(cl: {
//closure’s body
})
// trailing closure 사용
someFun() {
//trailing closure's body goes here
}

func math(x: Int, y: Int, cal: (Int, Int) -> Int) -> Int {
return cal(x, y)
}

result = math(x: 10, y: 20) {(a: Int, b: Int) -> Int in
return a + b
}//trailing closure

 

closure 표현식의 생략

result = math(x: 10, y: 20, cal: {(val1: Int, val2: Int) in
	return val1 + val2
}) //리턴형 생략
print(result)

result = math(x: 10, y: 20) {(val1: Int, val2: Int) in
	return val1 + val2
} //trailing closure, 리턴형 생략
print(result)

result = math(x: 10, y: 20, cal: {
	return $0 + $1
}) //매개변수 생략하고 단축인자(shorthand argument name)사용
print(result)

result = math(x: 10, y: 20) {
	return $0 + $1
} //trailing closure, 매개변수 생략하고 단축인자사용
print(result)

result = math(x: 10, y: 20, cal: {
	$0 + $1
}) //클로저에 리턴값이 있으면 마지막 줄을 리턴하므로 return생략
print(result)

result = math(x: 10, y: 20) { $0 + $1 } //return 생략
print(result)

 

 property는 저장 프로퍼티(stored property)과 계산 프로퍼티(computed property)

class Man{
	var age : Int = 1 //stored property는 초기값이 있어야 함
	var weight : Double = 3.5
}

class Man{
	var age : Int? //stored property는 초기값이 있어야 함, nil
	var weight : Double!
}

class Man{
	var age : Int = 1
	var weight : Double = 3.5
	func display(){
	print("나이=\(age), 몸무게=\(weight)")
	}
class func cM(){
	print("cM은 클래스 메서드입니다.")
	}
static func scM(){
	print("scM은 클래스 메서드(static)")
	}
}

var kim : Man = Man()
kim.display() //인스턴스 메서드는 인스턴스가 호출
Man.cM() //클래스 메서드는 클래스가 호출
Man.scM() //클래스 메서드는 클래스가 호출

 클래스명.클래스메서드()

 타입 메서드 또는 클래스 메서드는 클래스 레벨에서 동작

 타입 메서드는 인스턴스 메서드와 동일한 방법으로 선언하지만 class 나 static 키워드를 앞에 붙여서 선언

 class키워드로 만든 클래스 메서드는 자식 클래스에서 override가능 함

----------------------------------------------------------------------------------------------------------------------------------------------

class Man{
var age : Int = 1  // init 초기화 시 초기값 생략가능
var weight : Double = 3.5 // init 초기화 시 초기값 생략가능
func display(){
	print("나이=\(age), 몸무게=\(weight)")
}
init(age: Int, yourWeight : Double){
	self.age = age  // this 대신 self 사용가능
	weight = yourWeight
	} //designated initializer
}
//var kim : Man = Man() //오류
//init()을 하나라도 직접 만들면 default initializer는 사라짐
var kim : Man = Man(age:10, yourWeight:20.5)
kim.display()

 클래스, 구조체, 열거형(enum) 인스턴스가 생성되는 시점에서 해야 할 초기화 작업

 인스턴스가 만들어지면서 자동 호출됨

 init 메서드(생성자)

      init() { }

 designated initializer

 - 모든 프로퍼티(age, weight)를 다 초기화시키는 생성자

 init()을 하나라도 직접 만들면 기본적으로 만들어지는 눈에 안보이는 default initializer는 사라짐

 소멸자

 - 인스턴스가 사라질 때 자동 호출

 - deinit{}

-----------------------------------------------------------------------------------------------------------------------------------------------------------------

class Man{
var age : Int = 1
var weight : Double = 3.5
func display(){
        print("나이=\(age), 몸무게=\(weight)")
    }
init(age: Int, weight : Double){
        self.age = age
        self.weight = weight
    } //designated initializer
init(age:Int) // 메소드 오버로딩
    {
        self.age=age
    }
}
//var kim : Man = Man() //오류
//init()을 하나라도 직접 만들면 default
//initializer는 사라짐
var kim : Man = Man(age:10, weight:20.5)
kim.display()

 매개변수의 개수와 자료형이 다른 같은 이름의 함수를 여러 개 정의

 매개변수가 다른 두 생성자를 통해 두가지 방법으로 인스턴스를 만들 수 있음

'iOS' 카테고리의 다른 글

iOS (?)  (0) 2023.11.14
iOS (10)  (0) 2023.11.07
iOS (3)  (1) 2023.09.26
iOS (2)  (0) 2023.09.19
2023-09-12  (0) 2023.09.12

+ Recent posts