What are the differences between functions and methods in Swift?

后端 未结 6 1714
遇见更好的自我
遇见更好的自我 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条回答
  •  萌比男神i
    2020-12-07 14:46

    Here is a simple answer on the difference between functions and methods:

    Some folks use “function” and “method” interchangeably, but there’s a small difference: both of them are reusable chunks of code, but methods belong to classes, structs, and enums, whereas functions do not.

    So:

    func thisIsAFunction() {
    }
    
    struct Person {
        func thisIsAMethod() {
        }
    }
    

    Because methods always belong to a data type, they have a concept of self that functions do not.

    source: https://www.hackingwithswift.com/example-code/language/whats-the-difference-between-a-function-and-a-method

提交回复
热议问题