Evgeniy Kleban
Evgeniy Kleban

Reputation: 6940

Add class property to protocol in Swift

I want to have a protocol that have a variable. And class that conform to that protocol should use it like "normal" variable. What i want is something like:

protocol MyProtocol {
var foo: Int
}

class A {}
extension A: MyProtocol {
  var foo: Int!
}

Code above not compile, i only want to show point i want to achieve.

I ended up with this, but i suppose there must be better way:

enum NextController {
  case AuthSelection
  case Main
}

protocol SmsEntryPresenterProtocol {
  var nextController: NextController { get set }
}

class SmsEntryPresenter {

  var _nextController: NextController!
  weak var view: SmsEntryViewProtocol?

}

extension SmsEntryPresenter: SmsEntryPresenterProtocol {

  var nextController: NextController {
    get {
      return _nextController
    }
    set {
      _nextController = newValue
    }
  }
}

Upvotes: 1

Views: 169

Answers (1)

Kamran
Kamran

Reputation: 15238

You can fix this as below,

class SmsEntryPresenter {

    var nextController: NextController = .Main
    weak var view: SmsEntryViewProtocol?

}

extension SmsEntryPresenter: SmsEntryPresenterProtocol {}

Upvotes: 2

Related Questions