Objective-C Default Argument Value

前端 未结 6 1739
广开言路
广开言路 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:29

    There are two standard patterns for achieving what you want.

    (1) write a many argument form of a method and then provide fewer argument convenience versions. For example, consider the following methods on NSString:

    - (NSComparisonResult)compare:(NSString *)string;
    - (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask;
    - (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask
                range:(NSRange)compareRange;
    - (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask
                range:(NSRange)compareRange locale:(id)locale;
    

    The first three are conceptually [and likely concretely, I didn't check] implemented as calls through to the fourth version. That, is -compare: calls -compare:options:range:locale: with appropriate default values for the three additional arguments.

    (2) The other pattern is to implement the many argument version of the method and provide default values when an argument is NULL/nil or set to some value that indicates the default is desired. NSData has methods that are implemented with this pattern. For example:

    + (id)dataWithContentsOfFile:(NSString *)path options:(NSDataReadingOptions)readOptionsMask
                error:(NSError **)errorPtr;
    

    If you pass 0 for the readOptionsMask argument, the NSData will read the contents of the file using an internally defined default configuration. That default configuration may change over time.

提交回复
热议问题