Separation of function declaration and definition in Swift

后端 未结 5 2077
遥遥无期
遥遥无期 2021-01-06 06:00

I\'m having a look at the new Swift. I come from C, C++, Objective-C... I notice that in swift is not possible (?) to separate the declaration and the definition of function

5条回答
  •  甜味超标
    2021-01-06 06:17

    Just a crazy way to have public API and private implementation:

    crazy - stands for factory method create() which I do not like to see in swift without real need.

    In AClass.swift file:

    // Public API
    class AClass {
    
        private init() {
    
        }
    
        class func create() -> AClass {
            return AClassPrivateImplementation()
        }
    
        // Only method declaration
        func sayHello() {}
    }
    
    // Private implementation
    private class AClassPrivateImplementation: AClass {
    
        override func sayHello() {
            privateImplementation()
        }
    
        func privateImplementation() {
            println("Hello")
        }
    }
    

    Usage:

    let a = AClass.create()
    a.sayHello()
    

    Why it works: private modifier makes things visible only within source file.

    Advantages: you can define more than one implementation hence additional createOther() will be needed.

    Disadvantages: it looks like Java or C#, not a Swift way :)

提交回复
热议问题