Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift initialization of constants in a protocol

In Java you can initialize final static Strings in an interface.

Is there a method in Swift?

For example:

protocol StaticStringProtocol {
    // ERROR: Immutable property requirement must be declared as 'var' with a '{ get }' specifier
    static let staticStringInProtocol = "staticStringInProtocol"
}

extension StaticStringProtocol {
    // ERROR: Static stored properties not supported in protocol extensions
    static let staticStringInProtocolExtension = "staticStringInProtocolExtension"
}
like image 850
S. Birklin Avatar asked Nov 07 '14 09:11

S. Birklin


2 Answers

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).

like image 173
rghome Avatar answered Sep 20 '22 14:09

rghome


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)

like image 25
Antonio Avatar answered Sep 20 '22 14:09

Antonio