iosswiftcore-locationswift-compiler

What is better in this case: extension or function?


I have a ViewController where there's a logic for the "known" and "unknown" location. At a high level it looks like this:

class MyViewController {
    private var myVar: CLLocationCoordinate2D? // is updated somewhere

    private var myFunc1() {
        let someCond = myVar == nil // "isLocationUnknown" logic
    }

    private var myFunc2() {
        guard let myVar == nil else { return } // "isLocationUnknown" logic
    }
} 

Now there's a requirement to handle the "invalid location" case. Which means in addition to the nullability check, the CLLocationCoordinate2D check should be performed.

And I can't decide what is better ( as I don't know where to learn about Swift implementation details except of reading the sources :) ) :

Approach #1:

private func isLocationUnknown(_ location: CLLocationCoordinate2D?) -> Bool {
    guard let location = location else {
        return true
    }
    return !CLLocationCoordinate2DIsValid(location)
}

Approach #2:

private extension Optional where Wrapped == CLLocationCoordinate2D {
    var isUnknown: Bool {
        guard let self = self else {
            return true
        }
        return !CLLocationCoordinate2DIsValid(self)
    }
}

The criterias of comparison:

  1. semantics: I guess #2 is more "swifty"/expressive etc
  2. compilation time: can there be any difference (at scale)?
  3. run-time performance: can there be any difference (at scale)?

I believe in this particular case all criterias are not important, but if this enum would be public, and called e.g. many times per second, or within multiple places in the codebase, then I'd like to be more confident when making the decision.


Solution

  • A class and func are reference types and stored on the heap and is therefore slower to access. Since the type Optional is an enum it is stored on the stack and will be quicker to access. But in this case it would probably not be a noticeable difference. Do which ever you feel is right.

    If you want to read about memory management, here's a good article: https://manasaprema04.medium.com/memory-management-in-swift-heap-stack-arc-6713ca8b70e1m

    And here is a question about stack vs. heap memory: Swift stack and heap understanding

    EDIT: Another thought is that your first approach takes CLLocationCoordinate2D as a parameter which creates a new copy of CLLocationCoordinate2D. So the space complexity is probably larger as well. But if that's the case, minuscule.