简体   繁体   English

变量(枚举?)在Swift 2中持有两种类型之一

[英]Variable (enum?) holding one of two types in Swift 2

In a UIViewController subclass need to declare a variable called webView which can be of type UIWebView or WKWebView (depending on iOS version). UIViewController子类中需要声明一个名为webView的变量,该变量可以是UIWebViewWKWebView类型(取决于iOS版本)。

Is there a better way to do this (perhaps using an enum?) than one of these options: 是否有更好的方法来执行此操作(可能使用枚举?),而不是其中一个选项:

  1. Declaring the variable of type UIView and then conditionally casting to the two types every time I need to access it 声明UIView类型的变量,然后每次需要访问它时有条件地转换为两种类型
  2. Not declaring the variable in the common parent UIViewController super class, but declaring the variable of the specific type twice over in the two specific UIViewController subclasses? 不是在公共父UIViewController超类中声明变量,而是在两个特定的UIViewController子类中声明特定类型的变量两次? Feels like it violates the "Don't Repeat Yourself"/DRY principle. 感觉它违反了“不要重复自己”/ DRY原则。

You could define a protocol containing the common methods that you want to call on the view: 您可以定义一个协议,其中包含要在视图上调用的常用方法:

protocol MyWebView {
    // ...
}

Then make both UIWebView and WKWebView conform to that protocol (via extensions): 然后使UIWebViewWKWebView符合该协议(通过扩展):

extension UIWebView : MyWebView {

}

@available(iOS 8.0, *)
extension WKWebView : MyWebView {

}

Now you can declare the instance variable as 现在您可以将实例变量声明为

var webView : MyWebView!

and initialize it depending on the iOS version: 并根据iOS版本初始化它:

if #available(iOS 8, *){
    webView = WKWebView()
} else {
    webView = UIWebView()
}

I had a similar problem in an app of mine, using a different deprecated framework. 我在我的应用程序中遇到了类似的问题,使用了不同的弃用框架。 This solution worked for me: 这个解决方案对我有用:

Create a property as shown below: 创建一个属性,如下所示:

var webView: AnyObject!

In viewDidLoad , initialize the web view using this code: viewDidLoad ,使用以下代码初始化Web视图:

if #available(iOS 9, *){
    webView = WKWebView()
} else {
    webView = UIWebView()
}

Elsewhere in your code, when you need to do something with this web view, you need to do something similar: 在代码的其他地方,当您需要对此Web视图执行某些操作时,您需要执行类似的操作:

if #available(iOS 9, *){
    let newWebView = webView as! WKWebView
    // use newWebView
} else {
    let oldWebView = webView as! UIWebView
    // use oldWebView
}

Note : Martin R's suggestion to use a type alias may work as well, but this solution I have tested myself. 注意 :Martin R建议使用类型别名也可以,但我已经测试了这个解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM