How should you handle closure arguments for UIAlertAction

后端 未结 3 1728
轻奢々
轻奢々 2020-12-21 07:34

I have been trying to create a UIAlertAtion which also has a handler. I read the answers from this question and know how to do it.

My question is only a

3条回答
  •  情深已故
    2020-12-21 07:49

    rmaddy's answer is enough, but being the OP :) I find the root cause of my question :

    My lack in understanding the parameter handler, handler is of type: (UIAlertAction) -> Void)? ie a closure/function

    The handler is only expecting a function name, once you provide that function, it will fill in the inputs of that function itself.

    you only pass anything as the handler ie function name.

    UIAlertAction's internal implementation has some line like handler(action) which would use anything which is of type(UIAlertAction) -> Void)?, inject action (which is passed onto it) eventually doing anything(action).

    That being said, your anything(input: UIAlertAction) should be do something meaningful. (already discussed in the comments with rmaddy)


    The other solution is to not provide a function, but instead use the captured action in the trailing closure and do whatever you like doing with it.

    let retryAction = UIAlertAction(title: returnTitle(), style: UIAlertActionStyle.Default) { action in
    switch action.title {
            case "OK":
            okFunc()
            case "cancel":
            cancelFunc()
            default:
            defaultFunc()
            }
          }
    

    Such switching is only valuable if you are getting the code dynamically otherwise there is no added value switching for a tile you know it's value.

提交回复
热议问题