Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I declare functions in Swift and later define their implementation?

Coming from Objective-C, I am very fond of header files which expose the interface of a piece of code. Swift has always bothered me a bit because even the most organized code still tends to bury the public/private API's among the rest of the code, making you dig for details.

Are there any practices or tricks where I can define the public interface of a class or module external to the implementation? Right now I'm just making comments at the top of the Swift file and it feels arcane.

like image 229
user Avatar asked Oct 23 '25 06:10

user


2 Answers

As far as I know you can not just declare a method in a class and implement it at other places in Swift.

I feel you want that for clarity and organizing your methods into class. To achieve that in Swift I follow some techniques that I would be happy to share with you:

  1. Organize methods in groups based on access i.e. public, private and internal. Public methods on top as you want your client to look at them first, then internal and last private.

  2. You may sub organize related methods together for making it easy to understand, maintain and navigate through.

  3. Some time it is good to break above rules to group public and private method if they are related and has heavy dependancies.

  4. You may group related methods that do a specific task in to extensions. I generally follow this pattern for implementing specific protocol or delegate in a class. This you could do in a separate file as well.

This is not direct answer to your question but I have tried to address the core of it by targeting organization of methods in a class.

like image 117
Abdullah Avatar answered Oct 25 '25 23:10

Abdullah


So I've been exploring the options here and it looks like you can define an interface using a protocol, and having your class conform to that protocol. Kind of out of the way, but if a public interface is the goal, this achieves that.

// Foo.swift

protocol PublicFoo {

    func publiclyExposedMethod(arg:AnyObject) -> AnyObject

    var publiclyExposedVariable:AnyObject

}


class Foo : PublicFoo {

    var publiclyExposedVariable:AnyObject = // something

    func publiclyExposedMethod(arg:AnyObject) -> AnyObject {
        // do stuff...
    }

}
like image 29
user Avatar answered Oct 26 '25 00:10

user



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!