简体   繁体   中英

Swift: Using Protocols to create private class instance

I am really new to Swift, and trying to understand how to work things out with protocol extensions. So here is my protocol:

public protocol User: class {
    var name : String {get}
}
private class MyUser: User {
    var name : String

    init(name: String) {
        self.name = name
    }
}
extension User where Self:User {
    func createUser(name: String) -> User {
        return MyUser(name)
    }
} 

How do I call this function createUser from a totally different class/protocol, where I want to create an instance of User?

You could remake the function in whatever class you need it for

func createUser(name: String) -> User {
      return MyUser(name)
}

then say

let newUser = createUser("WhateverName")

or you could do:

let newUser = User().createUser("WhateverName")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM