空Init的协议

时间:2018-02-24 12:24:23

标签: swift protocols protocol-extension

我使用的框架具有列出了所有所需属性的“用户”协议,该协议也有一个空的init方法。我需要创建一个用户,但是我使用协议创建的任何实例都抱怨init不会初始化所有属性

框架协议

public protocol User {

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

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

///Init
public init()
}

如何使用此协议创建自己的结构并在init上向params添加值?

提前感谢!

1 个答案:

答案 0 :(得分:1)

您可以使用以下内容:

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)

输出:

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