你能在Swift中创建匿名内部类吗? [英] Can you create anonymous inner classes in Swift?

查看:770
本文介绍了你能在Swift中创建匿名内部类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经厌倦了宣布整个课程能够通过延长 UIAlertViewDelegate 来处理 UIAlertView 点击。当我有多个可能的 UIAlertView 时,它开始感到麻烦和错误,并且必须区分在处理程序中点击了哪个。

I'm tired of declaring entire classes as having the ability to handle UIAlertView clicks by making them extend UIAlertViewDelegate. It starts to feel messy and wrong when I have multiple possible UIAlertViews, and have to distinguish which was clicked in the handler.

我真正想要的是创建一个实现 UIAlertViewDelegate 协议的对象,并将这个一次性对象提供给我的 UIAlertView 显示时。

What I really want is to create a single object that implements the UIAlertViewDelegate protocol, and give this one-off object to my UIAlertView when showing it.

我想要这样的事情:

let confirmDelegate = UIAlertViewDelegate() {
    func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) {
        // Handle the click for my alertView
    }
}

然后在显示提醒时使用它:

And then use it when showing the alert:

let alertView = UIAlertView(title: "Confirm", message: "Are you sure?", delegate: confirmDelegate, cancelButtonTitle: "No", otherButtonTitles: "Yes")
alertView.show()

这可以在不声明新类的情况下实现吗?

Is this possible without declaring a new class?

我知道我可以这样做:

class ConfirmDelegate: UIAlertViewDelegate {
    func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) {
        // ...
    }
}

然后实例化 ConfirmDelegate(),但我只是想知道这是否可以作为单行类声明和实例化。

And then instantiate a ConfirmDelegate(), but I'm just wondering if this is possible as one-liner class declaration and instantiation.

推荐答案

正如@ChrisWagner在评论中指出的那样,你不应该在iOS8中做任何这样的事情,至少对于 UIAlertView 因为有一个新的 UIAlertViewController ,它使用没有任何委托的闭包。但从学术角度来看,这种模式仍然很有趣。

As @ChrisWagner states in his comment, you shouldn't need to do any of this in iOS8, at least for UIAlertView since there is a new UIAlertViewController that uses closures without any delegates. But from an academic point of view, this pattern is still interesting.

我根本不会使用匿名类。我只想创建一个可以指定为委托的类,并接受在事件发生时执行的闭包。

I wouldn't use anonymous class at all. I would just create a class that can be assigned as the delegate and accept closures to execute when something happens.

你甚至可以升级它以接受每种类型的闭包操作: onDismiss onCancel 等等。或者您甚至可以使此类生成警报视图,将其自身设置为委托。

You could even upgrade this to accept a closure for each kind of action: onDismiss, onCancel, etc. Or you could even make this class spawn the alert view, setting itself as the delegate.

import UIKit

class AlertViewHandler: NSObject, UIAlertViewDelegate {
    typealias ButtonCallback = (buttonIndex: Int)->()
    var onClick: ButtonCallback?

    init(onClick: ButtonCallback?) {
        super.init()
        self.onClick = onClick
    }

    func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) {
        onClick?(buttonIndex: buttonIndex)
    }
}


class ViewController: UIViewController {

    // apparently, UIAlertView does NOT retain it's delegate.
    // So we have to keep it around with this instance var
    // It'll be nice when all of UIKit is properly Swift-ified :(
    var alertHandler: AlertViewHandler?

    func doSoemthing() {
        alertHandler = AlertViewHandler({ (clickedIndex: Int) in
            println("clicked button \(clickedIndex)")
        })

        let alertView = UIAlertView(
            title: "Test",
            message: "OK",
            delegate: alertHandler!,
            cancelButtonTitle: "Cancel"
        )
    }
}

传递闭包应该减少了对匿名类的需求。至少对于最常见的情况。

Passing around closures should alleviate the need for anonymous classes. At least for the most common cases.

这篇关于你能在Swift中创建匿名内部类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆