What is the alternative of this objective-c code in swift

| | August 6, 2015

What is the equivalent of this code in swift ?

sprite.physicsBody = [SKPhysicsBody bodyWithFile: bodyFile];

2 Responses to “What is the alternative of this objective-c code in swift”

  1. The answer isn’t totally clear.

    For one thing, you don’t tell us the type of the bodyFile parameter. I’ll assume its type is BodyFileType for the rest of this post.

    With init methods like initWithBodyFile, the Swift compiler recognizes the “initWithXXX” naming pattern and creates an init method you’d call like this:

    Class SKPhysicsBody
    {
      init(bodyFile: BodyFileType)
      {
        //init code
      }
    }
    

    And you’c call it like this:

    SKPhysicsBody.body(file: bodyFile)
    

    The Objective-C method isn’t an init method, it’s a convenience “class factory” method that creates and returns an object.

    I don’t think Swift has any special handling of methods like this. Instead, you’d just call it based on it’s Objective-C signature.

    sprite.physicsBody = SKPhysicsBody.bodyWithFile(bodyFile)
    
  2. Official SKPhysicsBody class doesn’t have such method, so it must be an extension. But as long as we are speaking about Swift alternative it either must be a

    sprite.physicsBody = SKPhysicsBody.bodyWithFile(bodyFile)

    or

    sprite.physicsBody = SKPhysicsBody(file: bodyFile)

    depending on how good Swift handles your extension.

Leave a Reply