Objective-C Default Argument Value

前端 未结 6 1740
广开言路
广开言路 2020-12-10 03:58

Hey there, quick question here. I\'m sure there\'s a simple answer.

Coming from PHP, I\'m used to declaring a function with a default argument value like this:

6条回答
  •  时光取名叫无心
    2020-12-10 04:10

    Terrible necro but for anyone googling this, Xcode 4.5 supports (via Clang) overloading of C functions with __attribute__((overloadable)).

    Overloaded functions are allowed to have different numbers of arguments, so if C functions are appropriate for what you're trying to do you can use that to get default argument values.

    Here's a contrived example of an .h file with two functions, both called PrintNum:

    // Prints a number in the decimal base
    __attribute__((overloadable)) extern void PrintNum(NSNumber *number);
    
    // Prints a number in the specified base
    __attribute__((overloadable)) extern void PrintNum(NSNumber *number, NSUInteger base);
    

    and in the .m file:

    __attribute__((overloadable)) 
    void PrintNum(NSNumber *number) {
        PrintNum(number, 10);
    }
    
    __attribute__((overloadable))
    void PrintNum(NSNumber *number, NSUInteger base) {
        // ...
    }
    

    Note that the attribute must be specified in all definitions and declarations of the function.

提交回复
热议问题