子类化 v.s。协议

Subclassing v.s. Protocols

让我们从 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)
}
}

第二种方法是 Protocol Oriented 如果我没记错的话

protocol 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 = secret
    self.id = userID
}
}

我只需要知道哪个比较多Swift ?

在 swift 中可以接受或可以接受。

这是您想要区分两者的方式。

使用协议时,您希望将它们视为 objects 的蓝图。

Ballplayers must know what a ball is, so any person that wants to be a Ballplayer must know what a ball is.

你有一套规则希望某些人objects遵守,制定一个协议。

如果你想让 objects 有功能,并且你想让 children 继承这个功能,然后有更多的功能,然后做 inheret class 结构。

Dad can throw a ball at 100MPH Junior can throw a ball at 100MPH and throw a curve ball.

这将通过 class 而不是协议

来完成

结构实例始终按值传递,class 实例始终按引用传递。这意味着它们适用于不同类型的任务。当您考虑项目所需的数据结构和功能时,请决定每个数据结构应定义为 class 还是结构。

作为一般准则,考虑在满足以下一个或多个条件时创建结构:

该结构的主要目的是封装一些相对简单的数据值。 当您分配或传递该结构的实例时,期望封装的值将被复制而不是被引用是合理的。 结构存储的任何属性本身都是值类型,它们也应该被复制而不是被引用。 该结构不需要从另一个现有类型继承属性或行为。 结构的良好候选示例包括:

  • The size of a geometric shape, perhaps encapsulating a width property and a height property, both of type Double.
  • A way to refer to ranges within a series, perhaps encapsulating a start property and a length property, both of type Int.
  • A point in a 3D coordinate system, perhaps encapsulating x, y and z properties, each of type Double.

In all other cases, define a class, and create instances of that class to be managed and passed by reference. In practice, this means that most custom data constructs should be classes, not structures.

Why Choose Struct Over Class?

最终,这两种方法都不是 "more Swift"。在 Swift 中,您有时会想使用继承,而其他时候您会想使用协议。这两种方法的真正决策点是:

你想要值类型语义(结构和协议)还是引用类型语义(类 和协议)。我通常默认使用值类型语义,因为它们更安全,但在某些情况下,引用类型语义肯定很重要。您可以在此处阅读更多相关信息:Why Choose Struct over Class.