How to silence a warning in swift

前端 未结 4 1278
一整个雨季
一整个雨季 2020-12-04 07:04

I have a piece of code which is generating lots of warnings (deprecated API)

Using clang* I could do

#pragma clang diagnostic push
#pragma clang dia         


        
4条回答
  •  独厮守ぢ
    2020-12-04 08:05

    There is no general construct to silence deprecation warnings in Swift, but there is a workaround that can be applied in many cases.

    Let's say you have a method getLatestImage() on class Foo which uses deprecated methods/classes.

    Use @available as Daniel Thorpe described to silence all the warnings inside the method:

    @available(iOS, deprecated: 9.0)
    func getLatestImage() -> UIImage? {
        ...
    }
    

    Now you would like to call the method getLatestImage() without having a deprecation warning. You can achieve that by first defining a protocol and an extension:

    private protocol GetLatestImage {
        func getLatestImage() -> UIImage?
    }
    extension Foo: GetLatestImage {}
    

    And then call the method without a deprecation warning (if foo is an instance of Foo):

    (foo as GetLatestImage).getLatestImage() // no deprecation warning
    

    The result is you have Swift code that uses deprecated API without any deprecation warnings.

提交回复
热议问题