How to define initializers in a protocol extension?

后端 未结 4 474
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-30 20:06
protocol Car {
     var wheels : Int { get set}

     init(wheels: Int)

}

extension Car {
    init(wheels: Int) {
        self.wheels = wheels
    }
}
<
4条回答
  •  借酒劲吻你
    2021-01-30 20:48

    May not be the same but in my case instead of using init I used a static func to return the object of the class.

    protocol Serializable {
       static func object(fromJSON json:JSON) -> AnyObject?
    }
    
    class User {
        let name:String
    
        init(name:String) {
            self.name = name
        }
    }
    
    extension User:Serializable {
    
        static func object(fromJSON json:JSON) -> AnyObject? {
            guard let name = json["name"] else {
                return nil
            }
    
            return User(name:name)
         }
    
    }
    

    Then to create the object I do something like:

    let user = User.object(fromJSON:json) as? User
    

    I know its not the best thing ever but its the best solution I could find to not couple business model with the data layer.

    NOTE: I'm lazy and I coded everything directly in the comment so if something doesn't work let me know.

提交回复
热议问题