Home > Software engineering >  Swift: is there any functional difference between "private static let" (in a class definit
Swift: is there any functional difference between "private static let" (in a class definit

Time:02-10

The question says it all really, but is there a functional difference between:

One way to define it:

class SomeClass {
    
    private static let someValues: [String] = [
        "mrah!",
        "blah",
        "shmah!"
    ]
    
    var possibleValues: [String] {
        return Self.someValues
    }
}

or defined as:

class SomeClass {

    var possibleValues: [String] {
        return someValues
    }
}

fileprivate let someValues: [String] = [
    "mrah!",
    "blah",
    "shmah!"
]

Functionally identical, no? The defined array is inaccessible outside of the instance variable someValues Is there a reason not to do the latter?

(I want to include a bunch of long arrays in my class definition and you can't declare stored properties in extensions, and for the sake of code readability / brevity, I want to put these at the bottom of the implementation file, underneath other extensions.)

CodePudding user response:

The functional difference is minor: Your fileprivate (which could be private) global is accessible to all types defined within that file, whereas the former is limited to that one particular SomeClass.

The “private global” arguably requires non-local reasoning (i.e., you might have to scan through the whole file to see which types are there and might have access to it). On the other hand, the “private static property” makes the intent more clear at glance. As a result, many would favor this “private static property” approach.


For what it is worth, there is a hybrid approach:

class SomeClass {
    var possibleValues: [String] {
        return Self.someValues
    }
}

private extension SomeClass {
    private static let someValues: [String] = [
        "mrah!",
        "blah",
        "shmah!"
    ]
}

It keeps the core type definition very clean, but keeps the namespace for the static constant. Sometimes it is nice to put various subtypes, methods, and statics in extensions within the same file. It can make it easy to grok the code, facilitates code folding, etc.

CodePudding user response:

Your plan is fine, though you might as well mark the file-level value as private rather than fileprivate. They will behave the same. They are both even lazily initialized.

For full details on them, see "Global and Local Variables" and "Type Properties" in the Properties section of The Swift Programming Language.

  • Related