Is there a way to deprecate or hide system framework API in Swift?

Viewed 130

For some context, I am using SpriteKit. I created an extension for SKTexture:

public extension SKTexture {
  var sizeInPoint: CGSize {
    return CGSize(size().width/2, size().height/2)
  }
}

Now I would like to prevent accidental usage of size(), because texture.size() is in pixel, which is never what I want in my game.

How do I deprecate a system API? Or is it even possible?

Note:

I know when I subclass the SKTexture, I can mark size() as deprecated IN MY SUBCLASS. However, this is not ideal because the superclass SKTexture still has size() API.

For example, we can still get SKTexture from SKTextureAtlas:

let size = textureAtlas.textureNamed("dummy.png").size() // avoid this! 
2 Answers

I think the only way to deprecate any API is to recompile the header file with the @available (*, deprecated) declaration for the selected method.

For system calls, for obvious reasons, I see no way to do this. In your case, I would advise you to use tools like SwiftLint and add a rule to avoid calls, especially since SwiftLint allows you to mark these calls as compilation errors, not warnings.

UPD:

If you couldn't use an third-party libs, there is an solution. Add Run Script Phase, and find keywords that should emit an "warning" or "error" message:

KEYWORDS="size\(\)|\?\?\?:|\!\!\!:" 
find "${SRCROOT}" \( -name "*.swift" \) -print0 | xargs -0 egrep --with-filename --line-number --only-matching "($KEYWORDS).*\$" | perl -p -e "s/($KEYWORDS)/ warning: using of size() is deprecated/"

I guess it's impossible to deprecate a system API.

You may override a default behaviour:

public extension SKTexture {
  var sizeInPoint: CGSize {
    return CGSize(size().width/2, size().height/2)
  }

  override func size() -> CGSize {
    return sizeInPoint
  }
}
Related