【问题标题】:Declaring Class conforming to protocol in Swift在 Swift 中声明符合协议的类
【发布时间】:2014-08-05 11:59:01
【问题描述】:

在 Objective-C 中,我们可以将符合某些协议的类声明为

@property (nonatomic, strong) Class<UIObjectRestoration> objectRestorationClass;

并且可以给它赋值为

someObject.objectRestorationClass = [SomeClass class];

问题是: 我怎样才能在 Swift 中做到这一点?我尝试使用

var objectRestorationClass: UIObjectRestoration!

someObject.objectRestorationClass = SomeClass.self

但它给了我错误

“SomeClass.Type”不转换为协议“UIObjectRestoration”

SomeClass 是:

class SomeClass: UIViewController, UIObjectRestoration {

 class func objectWithRestorationIdentifierPath(identifierComponents: [AnyObject]!, coder: NSCoder!) -> UIStateRestoring! {

        return restoringObject
    }

}

我尝试了类型转换,但它给了我同样的错误。

【问题讨论】:

  • 在 Objective-C 中使用 Class&lt;UIObjectRestoration&gt; 和仅使用 Class 有什么明显区别吗?

标签: swift


【解决方案1】:

你可以使用

var objectRestorationClass: UIObjectRestoration.Type!

【讨论】:

    【解决方案2】:

    [UIObjectRestoration] 是 UIObjectRestoration 项的数组。采用 var objectRestorationClass : UIObjectRestoration 并使用 objectRestorationClass = SomeClass.classForCoder 赋值

    【讨论】:

    • “AnyClass”与“UIObjectRestoration”不同
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-24
    • 1970-01-01
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多