What are the differences between functions and methods in Swift?

后端 未结 6 1723
遇见更好的自我
遇见更好的自我 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:22

    Mainly the names are used interchangeably without people having a real intent of distinguishing them. But ultimately they do have a difference.

    someFile.swift:

    func someFunc{
    //some code
    }
    
    class someClass{
    
        func someMethod{
        //some code    
        }
    
    }
    

    Note: someClass != someFile

    someMethod works only on its associated type which is 'someClass'. However the same can't be said for someFunc. someFunc is only in the someClass.Swift because semantically it is better suited to be written in that file. It could have been written in any other class as long as it's marked with private

    And obviously the method can access self. With functions, there is no self.. For more see: What's the difference between a method and a function?

提交回复
热议问题