带有空初始化的协议
Protocol with Empty Init
我使用的框架有一个 'user' 协议,其中列出了所有需要的属性,该协议还有一个空的 init 方法。我需要创建一个用户,但是我使用该协议创建的任何实例都会抱怨 init 没有初始化所有属性
框架协议
public protocol User {
/// Name
public var firstname: String { get set }
/// Lastname
public var lastname: String { get set }
///Init
public init()
}
我如何使用此协议创建自己的结构并在初始化时向参数添加值?
提前致谢!
您可以如下使用:
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")
我使用的框架有一个 'user' 协议,其中列出了所有需要的属性,该协议还有一个空的 init 方法。我需要创建一个用户,但是我使用该协议创建的任何实例都会抱怨 init 没有初始化所有属性
框架协议
public protocol User {
/// Name
public var firstname: String { get set }
/// Lastname
public var lastname: String { get set }
///Init
public init()
}
我如何使用此协议创建自己的结构并在初始化时向参数添加值?
提前致谢!
您可以如下使用:
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")