swiftprotocolsprotocol-extension

Protocol with Empty Init


I am using a framework that has a 'user' protocol with all the desired properties listed, the protocol also has an empty init method. I need to create a user but any instance I create using the protocol complains that the init doesnt initialize all properties

Framework protocol

public protocol User {

/// Name
public var firstname: String { get set }

/// Lastname
public var lastname: String { get set }

///Init
public init()
}

How would I create my own struct utilizing this protocol and adding values to the params on init ?

thanks in advance!


Solution

  • You can use as following:

    struct MyAppUser: User {
    
       // default init coming from protocol
       init() {
           self.firstname = ""
           self.lastname = ""
       }
    
       // you can use below init if you want
       init(firstName: String, lastName: String) {
           self.firstname = firstName
           self.lastname = lastName
       }
    
       // coming from protocol
       var firstname: String
       var lastname: String
    }
    
    // user 1
    var user1 = MyAppUser()
    user1.firstname = "Ashis"
    user1.lastname = "laha"
    print(user1)
    
    // user 2
    let user2 = MyAppUser(firstName: "Kunal", lastName: "Pradhan")
    print(user2)
    

    Output:

    MyAppUser(firstname: "Ashis", lastname: "laha")
    MyAppUser(firstname: "Kunal", lastname: "Pradhan")