Using @available with stored properties

后端 未结 2 1101
北荒
北荒 2021-02-11 17:46

I have an app that uses local notifications and supports iOS 10. I am trying to add iOS 9 support which requires me to use the old location notification API. I am trying to use

2条回答
  •  没有蜡笔的小新
    2021-02-11 18:08

    Here is one potential solution (thanks to blog post). The idea is to use a stored property with a type of Any and then create a computed property that will cast the stored property (and instantiate it if necessary).

    private var _selectionFeedbackGenerator: Any? = nil
    @available(iOS 10.0, *)
    fileprivate var selectionFeedbackGenerator: UISelectionFeedbackGenerator {
        if _selectionFeedbackGenerator == nil {
            _selectionFeedbackGenerator = UISelectionFeedbackGenerator()
        }
        return _selectionFeedbackGenerator as! UISelectionFeedbackGenerator
    }
    

    Another option is to use lazy (however, this makes the variable read-write):

    @available(iOS 10.0, *)
    private(set) lazy var center = UNUserNotificationCenter.current()
    

提交回复
热议问题