Home > other >  @available fails to prevent calls to functions in swift
@available fails to prevent calls to functions in swift

Time:11-17

I am using @available to prevent some functions to be called at certain OS versions. Lets say I have two functions and both should be restricted to macOS version 12 and below. Not available at macOS 13. Hence I want to write

@available(macOS, obsoleted: 12)
extension MyStruct {
    func myFunc1() -> String { ... }
    func myFunc2() {
        let resultOfCallOfMyFunc1 = myFunc1()
    }
}

I thought that this way both functions are only available at the same platfroms. But I am getting error, when I try to use myFunc1 in myFunc2 why is that?

The error is: "myFunc1()" is unavailable in macOS

I also tried to mark each function separately instead of marking the whole extension, but no luck there either.

Any reason why this fails? How to use @available the way, that I will be able to use one function inside another one?

CodePudding user response:

According to the Language Reference, obsoleted indicates the first version in which the member is unavailable.

The obsoleted argument indicates the first version of the specified platform or language in which the declaration was obsoleted.

So you should write obsoleted: 13 instead. obsolete: 12 would mean that the extension is obsolete since macOS 12. Assuming that your minimum deployment target is equal to or higher than macOS 12, this would mean that the extension is obsolete on all the possible devices your app will be installed on, hence "myFunc1 is unavailable".

Note that the obsolete argument prevents code that targets higher OS versions from compiling. It is still possible to compile code targeting a lower version, and run myFunc1 on macOS 13 . If you don't want myFunc1 to execute at all on macOS 13 at all. You should use an #unavailable check:

if #unavailable(macOS 13, *) {
    let resultOfCallOfMyFunc1 = myFunc1()
}
  • Related