What are the differences between functions and methods in Swift?

后端 未结 6 1707
遇见更好的自我
遇见更好的自我 2020-12-07 13:58

I always thought functions and methods were the same, until I was learning Swift through the \"Swift Programming Language\" eBook. I found out that I cannot use greet(

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-07 14:24

    As you said yourself, methods are functions, but in a class. In objective-c you never realized this, because we were only coding in classes. Every function that we wrote was a method of a class (ViewController or some other class we created).

    In Swift we have the ability to create functions that are not inside some class. The main reason for doing this is to write functions that are not tied to any class, and can be used wherever we need them. So if you have a function that is related to a class you write it inside the class and you can access is from every instance of the class:

    class Square {
       var length: Double
       func area() -> Double {
          return length * length
       }
    }
    

    But if you need to access the function from everywhere, then you don't write it inside a class. For example:

    func squared(number: Int) -> Int {
        return number * number
    }
    

    About your syntax issues between functions and methods: You guessed it right, methods and functions are called a little bit differently. That is because in Objective-C we had long method names and we liked them because we could read what the methods were doing and what the parameters were for. So the first parameter in a method is in most cases described by the function name itself. And the other parameters shouldn't only be some numbers or strings or instances, they should be described as well, so Swift writes the name of the variable automatically. If you want to describe it by yourself you can do that as well:

    class Something {
        func desc(firstString string1: String, secondString string2:String) {...}
    }
    

提交回复
热议问题