Swift 클로저의 capturing 이해를 돕는 예시

Wonil Lee·2024년 2월 6일
0
class Ball {
    
    var size: Int
    
    init(size: Int) {
        self.size = size
    }
}

class A {
    
    var closure: () -> Void
    
    init(closure: @escaping () -> Void) {
        self.closure = closure
    }
}

var rubberBall = Ball(size: 10)

var weakCaptureObj = A { [weak rubberBall] in
    print("weakCaptureObj \t\t| rubberBall?.size: \(rubberBall?.size)")
}

var strongCaptureObj = A { [rubberBall] in
    print("strongCaptureObj \t| rubberBall.size: \(rubberBall.size)")
}

var noCaptureObj = A {
    print("noCaptureObj \t\t\t| rubberBall.size: \(rubberBall.size)")
}

print("before changing rubberBall size...")
weakCaptureObj.closure()
strongCaptureObj.closure()
noCaptureObj.closure()
print("")

rubberBall.size = 20
print("//rubberBall.size = 20//")
print("")

print("after changing rubberBall size...")
weakCaptureObj.closure()
strongCaptureObj.closure()
noCaptureObj.closure()
print("")

rubberBall = Ball(size: 100)
print("//rubberBall = Ball(size: 100)//")
print("")

print("after replacing rubberBall...")
weakCaptureObj.closure()
strongCaptureObj.closure()
noCaptureObj.closure()
print("")

strongCaptureObj = A { [rubberBall] in
    print("strongCaptureObj \t| rubberBall.size: \(rubberBall.size)")
}
print(#"""
//
strongCaptureObj = A { [rubberBall] in
    print("strongCaptureObj \t| rubberBall.size: \(rubberBall.size)")
}
//
"""#)
print("")

print("after replacing strongCaptureObj...")
weakCaptureObj.closure()
strongCaptureObj.closure()
noCaptureObj.closure()
print("")

/* 결과
before changing rubberBall size...
weakCaptureObj 		| rubberBall?.size: Optional(10)
strongCaptureObj 	| rubberBall.size: 10
noCaptureObj 			| rubberBall.size: 10

//rubberBall.size = 20//

after changing rubberBall size...
weakCaptureObj 		| rubberBall?.size: Optional(20)
strongCaptureObj 	| rubberBall.size: 20
noCaptureObj 			| rubberBall.size: 20

//rubberBall = Ball(size: 100)//

after replacing rubberBall...
weakCaptureObj 		| rubberBall?.size: Optional(20)
strongCaptureObj 	| rubberBall.size: 20
noCaptureObj 			| rubberBall.size: 100

//
strongCaptureObj = A { [rubberBall] in
    print("strongCaptureObj \t| rubberBall.size: \(rubberBall.size)")
}
//

after replacing strongCaptureObj...
weakCaptureObj 		| rubberBall?.size: nil
strongCaptureObj 	| rubberBall.size: 100
noCaptureObj 			| rubberBall.size: 100
*/
profile
DEV WITH APPLE

0개의 댓글