Swift initialization of constants in a protocol

Update This answer is no longer accurate. See rghome's answer instead


No swift doesn't support that. My advice is to define a struct alongside your protocol and define all constants as immutable static stored properties. For example:

protocol MyProtocol {
}

struct MyProtocolConstants {
    static let myConstant = 10
}

Note that structs are preferred to classes, for at least one reason: classes don't support static stored properties (yet)


Actually, you can do this in Swift using protocol extensions:

Create a protocol and define the variable you want with a getter:

protocol Order {
    var MAX_ORDER_ITEMS: Int { get }
    func getItem(item: Int) -> OrderItem
    // etc
}

Define a protocol extension:

extension Order {
    var MAX_ORDER_ITEMS: Int { return 1000 }
}

An advantage of this is that you don't have to prefix the protocol name as is usual with Swift and statics.

The only problems is that you can only access the variable from within a class implementing the protocol (which is probably the most common case anyway).