2

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!

user499846
  • 681
  • 3
  • 11
  • 24

1 Answers1

1

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")
Ashis Laha
  • 2,176
  • 3
  • 16
  • 17
  • Great thanks, seems like a waste to have to implement empty values in the init - but I guess there's no way around that given the protocol definition - thanks for the help! – user499846 Feb 24 '18 at 14:18