问题描述
让我们从 Class
方法开始: class LoginCredentials {
var id:String
init(userID:String){
self.id = userID
}
}
我们将具有以下内容:
class FacebookLoginCredentials:LoginCredentials {
var token:String
init(userID:String,userToken:String){
self.token = userToken
super.init(userID:userID)
}}
class TwitterLoginCredentials:LoginCredentials {
var token:String
var secret:String
init (userID:String,userToken:String,secret:String){
self.token = userToken
self.secret = secret
super.init(userID:userID)
}
}
第二个方法是面向协议的
如果我没有错误
协议LoginCredentials {
var id:String {get}
}
然后我们将有:
struct FacebookLoginCredentials:LoginCredentials {
var id:String
var token:String
init(userID:String,userToken:String){
self .id = userID
self.token = userToken
}
}
和
struct TwitterLoginProfile:LoginCredentials {
var id:String
var token:String
var secret:String
init(userID:String,userToken:String,secret:String){
self.token = userToken
self.secret =秘密
self.id = userID
}
}
我只需要知道哪一个更多的是Swift?
最终,这些方法都不是更多Swift。在Swift中,您有时会想要使用继承,而有时候您将需要使用协议。这两种方法的真正决定点是:
你想要值类型语义(结构和协议)还是想要引用类型语义(类和协议)。我通常默认值类型语义,因为它们更安全,但绝对有引用类型语义很重要的情况。您可以在这里阅读更多信息:。
Let is begin with the Class
approach:
class LoginCredentials {
var id : String
init(userID:String) {
self.id = userID
}
}
the we will have the following:
class FacebookLoginCredentials : LoginCredentials {
var token : String
init(userID:String,userToken:String) {
self.token = userToken
super.init(userID: userID)
}}
And
class TwitterLoginCredentials : LoginCredentials {
var token : String
var secret : String
init(userID:String,userToken:String,secret : String) {
self.token = userToken
self.secret = secret
super.init(userID: userID)
}
}
The second Approach is the Protocol Oriented
if I am not wrong
protocol LoginCredentials {
var id : String { get }
}
then we will have :
struct FacebookLoginCredentials : LoginCredentials {
var id: String
var token : String
init(userID:String,userToken:String) {
self.id = userID
self.token = userToken
}
}
And
struct TwitterLoginProfile : LoginCredentials {
var id: String
var token : String
var secret : String
init(userID:String,userToken:String,secret : String) {
self.token = userToken
self.secret = secret
self.id = userID
}
}
I just need to know which one is more Swift ?
Ultimately, neither of these approaches is "more Swift". In Swift, you will sometimes want to use inheritance and other times you will want to use protocols. The real decision point for these two approaches is:
Do you want value type semantics (structs and protocols) or do you want reference type semantics (classes and protocols). I usually default to value type semantics because they are safer but there are definitely circumstances where reference type semantics are important. You can read more about that here: Why Choose Struct over Class.
这篇关于子类v.s.协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!