Swift에서의 결합도(Tight And Loose Coupling in Swift)

장수빈·2024년 6월 7일

Swift문법

목록 보기
8/11

Tight Coupling(높은 결합도)

final class APIService {

	func exampleService(completion: @escaping(([Entity]) -> Void)) {

		// Network calling
		//...
		let data = Entity(id: "123", title: "DabaDoo")
		completion([data])

	}

}
final class Interactor {
  
	private let coupledService = APIService()
  
	func callService() {
  		coupledService.exampleService { [weak self] entity in
          guard let self = self else {return}
              // Do staff with data
   		}
  	}
}

Loose Coupling(낮은 결합도)

protocol APIServiceInterface{
	func exampleService(completion: @escaping(([Entity]) -> Void))
}

final class APIService: APIServiceInterface {

	func exampleService(completion: @escaping(([Entity]) -> Void)) {

		// Network calling
		//...
		let data = Entity(id: "123", title: "DabaDoo")
		completion([data])
	}
}
final class Interactor {
  
    private let decoupledService: APIServiceInterface
  
    init(decoupledService: APIServiceInterface) {
        self.decoupledService = decoupledService
    }
  	func callService() {
      	decoupledService.exampleService { [weak self] entity in
          	guard let self = self else {return}
              // Do staff with data
     	}
  	}
}

위에 tight coupling 파트와 다르게 APIService를 직접 호출한게 아닌
protocol을 호출하여 결합도를 낮추었다.

profile
iOS 공부 이모저모 낙서장

0개의 댓글