What are the differences between functions and methods in Swift?

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

    Well, @Ricky's answer says it pretty much. I was confused what exactly they are. So here is my thought:

    Functions could be defined outside of classes or inside of classes/structs/enums, while Methods have to be defined inside of and part of classes/structs/enums.

    We could define a Function outside of any Type's definition and could use it within Methods of any Type's definition.

    Just my understanding and illustration here, hope this helps someone else or you may edit if you feel there is an improvement needed OR let me know if anything is wrong:

    //This is a Function which prints a greeting message based on the category defined in an 'enum'
    func greet(yourName name: String, category: GreetingsCategory) {
        switch  category {
            case .Person:
                print("Hello, " + name + " Today is Tuesday")
            case .Vehicle:
                print("Hello, " + name + " your Vehicle is a Car")
        }
    }
    
    //This is an 'enum' for greetings categories
    enum GreetingsCategory: String {
        case Person
        case Vehicle
    }
    
    //Type: Person
    class Person {
    
        //This is a method which acts only on Person type
        func personGreeting() {
            greet(yourName: "Santosh", category: .Person)
        }
    }
    
    //Type: Vehicle
    class Vehicle {
    
        //This is a method which acts only on Vehicle type
        func vehicleGreeting() {
            greet(yourName: "Santosh", category: .Vehicle)
        }
    }
    
    //Now making use of our Function defined above by calling methods of defferent types.
    let aPerson = Person()
    aPerson.personGreeting()
    //prints : Hello, Santosh Today is Tuesday
    
    let aVehicle = Vehicle()
    aVehicle.vehicleGreeting()
    //prints: Hello, Santosh your Vehicle is a Car
    
    //We can also call the above function directly
    greet(yourName: "Santosh", category: .Person)
    

提交回复
热议问题