Declare a function in Swift before defining it

前端 未结 1 1931
别跟我提以往
别跟我提以往 2021-02-20 11:18

If I run this code in the Swift playground it works fine. The function is defined before it is called.

import Cocoa

func addValues(valueA:Double, valueB:Double)         


        
1条回答
  •  清歌不尽
    2021-02-20 11:43

    I believe that in Swift you generally cannot call functions before they have been declared, as they are unknown to the compiler at that time. In Objective C this was different because declaring the function in the header introduced it to the compiler at import time as a pointer to the function definition. Then, when the function was called the compiler could reference the imported pointer which would then take it to the function definition in the file.
    In Swift, this is different because we are not required to declare our properties in a header file - we simultaneously declare and define in one file. While simpler, this creates a problem resembling yours, where the compiler is unaware of the function until its declaration/definition.
    In classes, the rules are changed because we can call functions like this:

        class HypnosisViewController: UIViewController {
    
            override func viewDidLoad() {
                // Function call
                addValues(30.0, 40.0) 
            } 
    
            // Function declaration
            func addValues(valueA:Double, valueB:Double){
                let result = valueB + valueB
                println("Result \(result)")
            }
        }
    

    even though the function isn't declared until after the function call. We can do this because when an instance of a class is created, all of the instance variables and methods of that class are initialized to that object. This means the compiler has already initialized - and therefore recognized - the addValues function, so it doesn't complain.
    However, when code is executed linearly, such as in Playground, we do not have this initialization so it is not possible to call a function before it's declaration for the reasons previously stated (the compiler is unaware of the function). Playground's atypical behavior with this kind of situation is a little more ambiguous to me, because it complains about the function call preceding the function declaration however it still shows the result of the call to the right. I believe this is due to the unique way that Playground compiles its code.
    I apologize because I am unaware of a technique to retain this Objective C functionality in Swift, which I know was part of your question. However I hope this gave you some background as to why this is happening.

    0 讨论(0)
提交回复
热议问题