ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Swift] Protocol & Delegate
    개발/Swift 2020. 11. 4. 16:30
    반응형

    Bird라는 슈퍼클래스에 fly() 기능을 넣어두고

    Eagle이라는 자식 클래스에 Bird 클래스를 Inherit 한다고가정했을때

    Penguin은 Bird 클래스를 상속 받지만 fly() 기능을 사용하면 안된다.

    AirPlane 을 구현할경우 fly를 사용하기 위해 Bird를 상속받아야하는 경우도 생긴다.

     

    이때 프로토콜을 사용하다.

    protocol CanFly{
    	func fly()
    }
    

    인터페이스 처럼 상세구현은 자식에서한다.   

    class Eagle : Bird , CanFly{
        func fly(){
          print("FLY")
        }
      
    }

    protocol은 class 가 아닌 struct에서도 상속 받을수있다.

     

    Delegate 

     

    Model - WeatherManager 클래스에서

    우선 프로토콜을 만든다 

    protocol WeatherManagerDelegate {
        func didUpdateWeather(weather:WeatherModel)
    }
    

    didUpdateWeather()는 하위 클래스에서 구현할것이다.

     

    우선 didUpdateWeather 메소드는

    Model - WeatherManager 클래스에서 사용할것이다.

    (해당 메소드를 실행 시킬 클래스) 

    날씨에 대한 데이터를 받자마자 해당 메소드를 실행시킬것이다.

    우선 해당프로토콜 delegate를 만든다.

        var delegate : WeatherManagerDelegate?
    

     

    그리고 해당 클래스에서 필요한 didUpdateWeather를 데이터를 받고나서 사용한다.

    if let weather = self.parseJSON(weatherData: safeData){
      delegate?.didUpdateWeather(weather: weather)
    
    }

     

    하지만 아직 메소드가 상세히 구현되어있지 않다.

    viewController에가서 해당 프로토콜을 상속받은뒤 delegate 지정후

    메소드를 구현한다.

    //viewDidLoad 에서 delegate 지정후
    weatherManager.delegate = self
    
    
    메소드 구현
    func didUpdateWeather(  weather : WeatherModel){
       print(weather.temperature)
    }

     

     

    반응형

    댓글

Designed by Tistory.