Swift: Variable parameters

Keywords: iOS Swift github xcode

From: https://addicechan.github.io/...

In Swift, when naming a method parameter, you can use Variadic Parameters directly if you have more than one specific type of parameter. Official Document Links

Using variable parameters is actually very simple. That's to add... to the parameter type. For example, Int... In fact, if the parameter is called internally, Xcode prompts [Int]. It's an Array. This is also very convenient. You don't have to declare an Int.

Waiter.. Upper Code ~~~

// Number addition
func add(_ values: Int...) -> Int {
    return values.reduce(0){ $0 + $1 }
}

print(add(1,5,8,9))
// 23

For example, you can encapsulate a UIAlert Controller. If you think you have to write a lot of alert.addAction() Barabara every time.

extension UIAlertController {

    class func show(_ vc: UIViewController?, title: String, msg: String, style: UIAlertControllerStyle ,btns: String... ,completionHandler:@escaping ((_ btnIndex: Int) -> Void)) {
        let alertController : UIAlertController = UIAlertController(title: title, message: msg, preferredStyle: style)
        
        for (index, element) in btns.enumerated() {
            alertController.addAction(UIAlertAction(title: element, style: .default, handler: { _ in
                completionHandler(index)
            }))
        }
        
        if style == .actionSheet {
            alertController.addAction(UIAlertAction(title: "cancel", style: .cancel, handler: nil))
        }
        
        vc?.present(alertController, animated: true, completion: nil)
    }
}

// Use
UIAlertController.show(self, title: "Alert", msg: "show alert", style: .alert, btns: "previous", "next") { index in
         print(index)
}

However, variable parameters cannot be used in Objective-C.

Objective-C if you want to use variable parameters. Then we need to use a series of C functions such as va_list.

Second grade, continue with the code~~~


- (NSString *)add:(NSString *)value, ... NS_REQUIRES_NIL_TERMINATION {
    NSMutableString *result = [NSMutableString string];
    [result appendString:value];
    if (value) {
        va_list values;
        // values start with the value's pointer address until nil
        va_start(values, value);
        id tempValue;
        while((tempValue = va_arg(values, NSString *))) {
            [result appendString:tempValue];
        }
        
        // Remember to empty
        va_end(values);
    }
    return result;
}

Using the macro va_start, you start with the pointer address of value and take values one by one. For non-pointer, then it can not be achieved. As for NS_REQUIRES_NIL_TERMINATION after the method name, nil is added as the termination when the method is called. Because if there is no nil, it will also lead to constant values, so, after getting the uninitialized memory space, it will lead to crash. Boom...

After writing this method, I can only exclaim that Swift encapsulation is very good. Very convenient... Grammar, plus the use of higher-order functions. It does not seem to be a very fair comparison. (Run away.


func add(_ values: String...) -> String {
    return values.reduce(""){ $0 + $1 }
}

With these lines of code, the above Objective-C writing method has been implemented.

The root of this article is actually turning over (gen) to see (ben)Swift(jiu) Zhi (dao) de (shuo). So you see variable parameters. Later, I think that the NSArray, UIAlertView and so on of Objective-C are actually based on this.

I understand a little more. I hope it's not too late.

Blind crying...

Posted by thiggins09 on Fri, 05 Jul 2019 15:43:21 -0700