How to get one class from two different classes in Swift based on API level?

I want to use a library with the SwipeTableViewCell class (obtained from UITableViewCell), but it only supports iOS 9, so I want to extract from this class, if possible, but from the regular UITableViewCell class, if the application runs below 9.0.

This is the best I could come up with (doesn't work):

@available(iOS, obsoleted: 9.0)
class MyTableViewCell : UITableViewCell {
}

@available(iOS 9.0, *)
class MyTableViewCell : SwipeTableViewCell {
}

Then I try to extract from this class:

class SomeOtherTableViewCell : MyTableViewCell {
}

Xcode gives me the following error and links to the two class definitions above:

SomeOtherTableViewCell.swift:34:31: 'MyTableViewCell' is ambiguous for type lookup in this context
Found this candidate
Found this candidate

What a cool way in Swift to conditionally infer from two different classes depending on the API level?

+4
source share
1 answer

(, , , ), , , Swift Objective-C . @available, , , , , , .

@MartinR # available , .

, 2 , , . / API, .., SDK . . , SDK, .

SDK9 iOS 8 . SwipeTableViewCell iOS 8, API, iOS 9. SwipeTableViewCell iOS 8, .

iOS 8. iOS 9 App Store, , iOS 8, .

Update

. , , , iOS.

import UIKit

class ViewController: UITableViewController {

    @IBOutlet var staticCell: Any? // In the storyboard, tell the cell to by a "MySwipeableCell"

    override func viewDidLoad() {
        super.viewDidLoad()

        if staticCell is SwipeTableViewCell {
            print("This class was converted magically, which means we're on iOS 9 or later")
        }
    }
}

class SwipeTableViewCell: UITableViewCell {
    // Standin for your library class
}

class MySwipeableCell: UITableViewCell {

    override func awakeAfter(using aDecoder: NSCoder) -> Any? {
        if #available(iOS 9, *) {
            // This will replace the MySwipeableCell with an instance of SwipeTableViewCell instead
            return SwipeTableViewCell.init(coder: aDecoder)
        }

        return self
    }
}
+2

Source: https://habr.com/ru/post/1680893/


All Articles