2

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
MausD
  • 125
  • 8
  • You are confusing preprocessor directives and stored properties (which you cannot add in class extension). – Kreiri Jun 18 '14 at 08:55
  • Yeah, this is rather confusing code. The ObjC code doesn't even mention NSMutableArray, why would the Swift code mention it? – Catfish_Man Jun 18 '14 at 23:54

3 Answers3

6

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 }
    ...
}
Community
  • 1
  • 1
GK100
  • 3,664
  • 1
  • 26
  • 19
  • Not possible. `Extensions may not contain stored properties.` – SoftDesigner Sep 12 '16 at 13:15
  • True that Swift extensions may not contain stored properties but a read-only computed property is functionally equivalent to a constant stored property. – Mobile Dan Jan 27 '17 at 20:05
  • I suggest the more concise syntax `var integerMax: Int { return Int.max }`. If a stored property has only a getter then the `get` keyword and braces are not required. – Mobile Dan Jan 27 '17 at 20:09
1

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
        //..... 
    }
Rodrigo Gonzalez
  • 723
  • 7
  • 15
0

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.

Cocoadelica
  • 3,006
  • 27
  • 30