Set and protocols in Swift

后端 未结 2 1573
一整个雨季
一整个雨季 2020-12-20 11:58

I would like to initialize a Set with values corresponding to the Hashable protocol and a custom protocol.

I tried :

protocol CustomProtocol: Hasha         


        
2条回答
  •  囚心锁ツ
    2020-12-20 12:29

    In Swift 3, one solution is to use the AnyHashable structure.

    For instance, to create a Observers/Observable pattern, we could do :

    protocol Observer {
        func observableDidSomething(_ observable: Observable)
    }
    
    class Observable {
        private var observersSet: Set = []
    
        private var observers: [Observer] {
            return observersSet.flatMap { $0 as? Observer }
        }
    
        func add(_ observer: O) where O : Observer, O : Hashable {
            observersSet.insert(observer)
        }
    
        func remove(_ observer: O) where O : Observer, O : Hashable {
            observersSet.remove(observer)
        }
    
        // ...
    
        private func doSomething() {
            // do something ...
            observers.forEach { $0.observableDidSomething(self) }
        }
    } 
    

    Notice that I separate the Hashable protocol from my protocol Observer.

提交回复
热议问题