Adrian
Adrian

Reputation: 16735

Deprecation warning for Objective-C dependencies

Making Swift var backwards compatible with Objective-C

I have an Objective-C class I've converted to Swift. All my tests pass, but I'd like to further optimize it by adding a deprecation warning to update to notify users to update downstream dependencies to the Swift version of the var (Decimal) if they can. Whether they can depends upon whether the class they're using is an Objective-C class (which can only "see" NSDecimalNumber) or a Swift class. Is there a way to do this? This is what I've got so far.

  @available(swift, introduced: 5.0)
  public var mySwiftDecimal: Decimal?

  @available(*, deprecated, renamed: "mySwiftDecimal")
  public var myObjCDecimal: NSDecimalNumber? {
      get {
          return mySwiftDecimal as NSDecimalNumber?
      } set {
          mySwiftDecimal = newValue as Decimal?
      }
  }

Upvotes: 2

Views: 93

Answers (1)

Martin R
Martin R

Reputation: 539975

You can annotate the member as deprecated in Swift:

@available(swift, deprecated: 5.0, renamed: "mySwiftDecimal")
@objc public var myObjCDecimal: NSDecimalNumber? {
    get {
        return mySwiftDecimal as NSDecimalNumber?
    } set {
        mySwiftDecimal = newValue as Decimal?
    }
}

Then using it from Swift gives a warning:

let foo = Foo()
print(foo.myObjCDecimal)
// 'myObjCDecimal' is deprecated: renamed to 'mySwiftDecimal'

but using it from Objective-C does not:

Foo *foo = [[Foo alloc] init];
NSDecimalNumber *dec = foo.myObjCDecimal;

Upvotes: 2

Related Questions