How can i define a Constant in a Extension analogous to Objective C
Objective C:
#define integerMax NSIntegerMax
Swift:
extension NSMutableArray {
let integerMax = Int.max // Doesn't work
How can i define a Constant in a Extension analogous to Objective C
Objective C:
#define integerMax NSIntegerMax
Swift:
extension NSMutableArray {
let integerMax = Int.max // Doesn't work
You can add it as a (readonly) computed property:
extension NSMutableArray {
var integerMax : Int { get { return Int.max } }
...
}
see also: https://stackoverflow.com/a/25428013/2274829
Edit
A more concise version, as suggested in the comments:
extension NSMutableArray {
var integerMax : Int { return Int.max }
...
}
you can define first the constant. And then using it in the extension
let integerMax = Int.max
extension NSMutableArray {
func someFunc() {
var someVar : Int = integerMax
//.....
}
I presume Extensions have the same constraint as Categories in Obj-C in that you can't add new instance variables (or in this case constants).
the #define in Obj-C is not the same as a let-generated constant in Swift. #define is a preprocessor macro which simply tells the compiler to do a find and replace on the name with the value. the let statement is in effect creating a new property on the class which you can't do in Extensions/Categories.
In Obj-C you can route around this with associated objects by using some runtime magic. I'm afraid I don't know the equivalent for Swift or even if it's possible.