User1238 User1238 - 3 months ago 7
Swift Question

Nested functions in Swift

I am learning swift and want to understand how to make nested functions

extension Auto {
// MARK: Auto extensions
func isRegistred() -> Bool {
return true
}
}


if I want to verify if an Auto is registered I have to use this line
if
Auto.isRegistered()

If the auto is registered I also want to be able to verify if it's a new one, so I want to add a
isNew()
function. Is it possible to add a nested function so that I can still verify if the auto is registered with
Auto.isRegistered()
and use
Auto.isRegistered().isNew()
to verify that it's a registered auto and a new one? Something like

extension Auto {
// MARK: Auto extensions
func isRegistred() -> Bool {
func isNew() -> Bool{
return true
}
return true
}
}

Answer

No, that wouldn't really make sense. You can't access functions within functions. auto.isRegistered() returns a Bool, so auto.isRegistered().isNew() would try to call the isNew() method on Bool which, obviously, doesn't exist.

I also advise you to use computed properties instead of functions if you name it "isSomething", that's more in line with Apple's APIs. So you'd get something like this:

extension Auto {
    var isRegistered: Bool {
        // ...
    }

    var isNew: Bool {
        // ...
    }
}

Then you can simply check if an auto is both registered and new with

auto.isRegistered && auto.isNew

Nested functions

Nested functions are hidden from the outside world by default, but can still be called and used by their enclosing function

Comments