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"
}
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).
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With