继承类取决于iOS版本(swift)

时间:2019-04-24 11:00:54

标签: ios swift inheritance

是否可以根据iOS版本继承类?

我有代码:

let cell1 = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier1", for: indexPath) as! MyCell1
// ....
let cell2 = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier2", for: indexPath) as! MyCell2

对于我来说,对于iOS版本<11.0使用带有第三方框架的类是必要的,但是在iOS版本中> = 11.0使用了标准解决方案。

class MyCell1: BaseTableViewCell {
    // Different code
}

class MyCell2: BaseTableViewCell {
    // Different code
}

// Available for iOS >= 11.0
class BaseTableViewCell: UITableViewCell {
}

// Available for all other versions
class BaseTableViewCell: SwipeTableViewCell {
}

在第三方框架中,我有此类:

class SwipeTableViewCell: UITableViewCell {
    // Different code
}

实质上,我想为iOS <11.0添加一个中间层类

2 个答案:

答案 0 :(得分:2)

  

是否可以根据iOS版本继承类?

基类是在编译代码时而不是在运行时建立的,因此您不能根据代码所运行的操作系统版本来切换基类。

  

对于我来说,对于iOS版本<11.0使用带有第三方框架的类是必要的,但是在iOS版本中> = 11.0使用了标准解决方案。

执行此操作的方法是使用包容而不是继承,以便您可以在代码运行时以所需的行为配置对象。可以将其想象为委派,在委派中,您可以使用一个帮助对象来专门化一个类而无需创建子类。

例如,假设您已经根据BaseTableViewCell定义了UITableViewCell类,如下所示:

// Available for iOS >= 11.0
class BaseTableViewCell: UITableViewCell {
}

但是也许11.0之前的iOS版本没有与滑动相关的某些功能,因此您首先创建一个协议,该协议声明一些提供需要添加的行为的功能:

protocol SwipingProtocol {
    func swipe()
}

...并创建实现该协议中功能的类

class OldSwiper : SwipingProtocol {
    func swipe() { // put your < 11.0 swiping code here }
}

class NewSwiper : SwipingProtocol {
    func swipe() { // put your >= 11.0 swiping code here }
}

...,最后将对它的支持添加到您的基类中:

class BaseTableViewCell: UITableViewCell {
    var swiper : SwipingProtocol

    init() {
        if systemVersion < 11.0 {
            swiper = OldSwiper()
        }
        else {
            swiper = NewSwiper()
        }
    }

    func swipe() {
        swiper.swipe()
    }
}

因此,现在您已经在OldSwiperNewSwiper中包含了两种(或更多种)刷卡行为的实现,并且基类根据运行时所处的环境来决定使用哪一种

当然,您可以跳过整个协议,并将新旧行为都构建到BaseTableViewCell中,并在每种方法中都使用if语句在每种依赖于OS的自定义方法之间进行切换。但是,使用协议和帮助程序类会更好,因为它将所有特定于版本的内容保留在单独的类中。这也使您的代码更灵活-如果将来您想在iOS 14.0及更高版本上做一些不同的事情,则只需创建新的SwipingProtocol实现即可。

答案 1 :(得分:0)

这应该满足您的需求:Check OS version in Swift?

var cell: BaseTableViewCell? = nil

if #available(iOS 11.0, *) {
    cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier1", for: indexPath)
} else {
    cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier2", for: indexPath)
}