Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift and method prototype - forward declaration

Tags:

ios

swift

Exploring Swift headers I'm seeing this pattern used by Apple, in particular the init declaration of the following struct HAS NO IMPLEMENTATION. Obviously the init() implementation is hidden somehow, since it's Apple stuff, but I was trying to understand how. This is only an example, but it seems a common behavior in the headers

struct AutoreleasingUnsafePointer<T> : Equatable, LogicValue {
    let value: Builtin.RawPointer
    init(_ value: Builtin.RawPointer)    // <---- how is it possible? where is the implementation?
    func getLogicValue() -> Bool

    /// Access the underlying raw memory, getting and
    /// setting values.
    var memory: T

}

I know that it is possible to declare a protocol plus a class extension, doing this it's possible to "hide" the implementation from the class declaration and moving it elsewhere

class TestClass :TestClassProtocol
{
     // nothing here

}

protocol TestClassProtocol
{
    func someMethod()  // here is the method declaration

}

extension TestClass
{
    func someMethod()  // here is the method implementation
    {
        println("extended method")
    }

}

But it's different from what I have seen in the Apple Headers, since the method "declaration" is inside the "class", not inside the "protocol". if I try to put the method declaration inside the class TestClass, however, I have two errors (function without body on the class, and invalid redeclaration on the extension)

In Objective C this was "implicit", since the method declaration was in the .h and the implementation in the .m How to do the same in Swift?

like image 644
LombaX Avatar asked Jun 03 '14 21:06

LombaX


People also ask

What is difference between function prototype and forward declaration?

A function prototype is a declaration statement that includes a function's name, return type, and parameters. It does not include the function body. What is a forward declaration? A forward declaration tells the compiler that an identifier exists before it is actually defined.

What is forward declaration Xcode?

In computer programming, a forward declaration is a declaration of an identifier (denoting an entity such as a type, a variable, a constant, or a function) for which the programmer has not yet given a complete definition.

Is a forward declaration?

A forward declaration tells the compiler about the existence of an entity before actually defining the entity. Forward declarations can also be used with other entity in C++, such as functions, variables and user-defined types.


1 Answers

I think the explanation is very simple. What you see in Xcode is not actually a valid Swift code.

It's a result from an automatic conversion of an Obj-C header into Swift-like code but it's not compilable Swift.

like image 65
Sulthan Avatar answered Oct 26 '22 21:10

Sulthan