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
In swift, there is no separation of declaration vs implementation. This works like most other modern languages like Python. If you want to get a quick picture of your class, you should use code folding. Simply fold all your methods and functions. And unfold a method of you want to modify / work on it.
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 :)
About the best we can do is use protocols as Implementation declarations and mark all private methods:
protocol TestInterface {
var propertyPublic1: String { get }
func funcPublic1() -> Int
}
class Test : TestInterface {
var propertyPublic1: String = "text."
func funcPublic1() -> Int {return 754}
private var propertyPrivate1: Int = 5678
private func funcPrivate1() -> Int {return 334}
}
var t = Test()
let propPublic1 = t.propertyPublic1
The problem is that it is not provided as a standard idiom and the naming is unfortunate, I have just appended "Interface" to the class name.
Yes, it's true that swift doesn't have header files but you can make Xcode generate something similar to this.
This will give you an overview of the class as you mention.
On Xcode go to Navigation > Jump to Generated Interface
.
This link should explain a bit more.
Swift doesn't let you separate declarations from implementations. This cuts both ways -- on the one hand, you can't (manually) write a header file that describes the interface you want to expose for users of your code. On the other, you don't have to manually keep your header files up to date and in sync with your implementations.
Instead, Swift has an access control mechanism. Use the public
, internal
(implied), and private
keywords to mark which types and functions you intend to expose.