使用Swift,来自Java背景,为什么要选择Struct而不是Class?看起来它们是相同的,使用Struct提供更少的功能.为什么选择呢?
我想分享一些枚举属性.就像是:
enum State {
case started
case succeeded
case failed
}
enum ActionState {
include State // what could that be?
case cancelled
}
class Action {
var state: ActionState = .started
func set(state: State) {
self.state = state
}
func cancel() {
self.state = .cancelled
}
}
Run Code Online (Sandbox Code Playgroud)
我明白为什么ActionState不能继承State(因为状态cancelled没有表示State)但我仍然可以说"ActionState就像具有更多选项的State,而ActionState可以获得State类型的输入,因为它们也是输入ActionState"
我看到如何使用上述逻辑来复制案例ActionState并在set函数中进行切换.但我正在寻找一种更好的方法.
我知道枚举不能在Swift中继承,我已经阅读了swift-enum-inheritance的协议答案.它没有解决"继承"或包含来自另一个枚举的案例的需要,而只涉及属性和变量.
I am trying to create an inheritance for below enum
enum BankAuthError: String {
case authFailed = "AuthFailed"
case technicalError = "Unavailable"
case accountLocked = "Locked"
case unknownError = "UnknownError"
case userInteractionRequired = "UserInteractionNeeded"
case realmUserAlreadyConnected = "UserExists"
}
Run Code Online (Sandbox Code Playgroud)
I am able to use this enum as below
let errorCode = BankAuthError(rawValue:errorMessageCodeString)
Run Code Online (Sandbox Code Playgroud)
Now I am trying to create inheritance from above struct as below
//MARK:- Enum to handle all sysnc errors
enum SyncErrorStatus: BankAuthError {
case usernameOrPasswordMissing = "UsernameOrPasswordMissing"
case …Run Code Online (Sandbox Code Playgroud)