Class-Only Protocols in Swift

后端 未结 4 1334
攒了一身酷
攒了一身酷 2021-02-03 20:51

I want some of my classes (not all) to conform using \'Class-Only Protocols\' from docs. What I am doing is

protocol RefreshData: class, ClassA, ClassB
{
    fun         


        
4条回答
  •  爱一瞬间的悲伤
    2021-02-03 21:34

    Latest version of Swift can do it! I would do a protocol and protocol extensions that target the classes you want! (constraint the extension to specific class)

        protocol Movable {
            func moveForward()
            func moveBackward()
        }
    
        extension Movable where Self: Car {
            func moveForward() {
                self.location.x += 10;
            }
    
            func moveBackward() {
                self.location.x -= 10;
            }
        }
        extension Movable where Self: Bike {
            func moveForward() {
                self.x += 1;
            }
    
            func moveBackward() {
                self.x -= 1;
            }
        }
    
        class Car: Movable {
            var location: CGPoint
    
            init(atLocation location: CGPoint) {
                self.location = location
            }
        }
    
        class Bike: Movable {
            var x: Int
    
            init(atX x: Int) {
                self.x = x
            }
    }
    

提交回复
热议问题