How can different functions have the same name?

swift cocoa

1183 просмотра

3 ответа

From Apple's documentation:

Responding to Location Events

func locationManager(CLLocationManager, didUpdateLocations: [CLLocation])

Tells the delegate that new location data is available.

func locationManager(CLLocationManager, didFailWithError: Error)

Tells the delegate that the location manager was unable to retrieve a location value.

func locationManager(CLLocationManager, didFinishDeferredUpdatesWithError: Error?)

Tells the delegate that updates will no longer be deferred.

func locationManager(CLLocationManager, didUpdateTo: CLLocation, from: CLLocation)

Tells the delegate that a new location value is available.


I have a piece of my code which looks like:

ViewController.swift

class ViewController:UIViewController, CLLocationManagerDelegate {

    [...]

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        [...]

    }

    func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
        [...]
    }

    [...]
}

How can I have in the same class, two functions that have the same name but are called in independent ways depending on the arguments passed? In other programming languages, afaik you can't do that.

Автор: J. C. Rocamonde Источник Размещён: 08.11.2019 11:29

Ответы (3)


3 плюса

Решение

In Swift, the argument names and types are part of the function name. So in your example, the functions are named differently because the arguments are different.

This is why you see the argument names included in the method names in the documentation, for example:

locationManager(_:didUpdateLocations:)
locationManager(_:didFailWithError:)
locationManager(_:didFinishDeferredUpdatesWithError:)

Also, even if the arguments are named the same, if their types are different, this is allowed. A simple example:

class Greeter {
    func greet(arg: Int) -> String {
        if (arg < 12) {
            return "Good morning!"
        } else if (arg < 18) {
            return "Good afternoon!"
        } else {
            return "Good evening!"
        }
    }

    func greet(arg: String) -> String {
        return "Hello, \(arg)."
    }
}

In this example, you could call Greeter().greet(4) or Greeter().greet("Aaron") and control would flow to the appropriate function.

Автор: Aaron Brager Размещён: 20.08.2016 03:27

1 плюс

It's called "function overloading" (or "method overloading"), having multiple functions/methods with the same name that are distinguished by their signature (the number and types of their arguments). It's very common in programming languages, including C++, Java, C#, and apparently Swift.

How overloading is handled under the covers varies quite a bit by language. For example, last I looked (a long time ago), C++ used name mangling — the actual name of the function was created by taking the base name and adding things to it to indicate the types of the arguments. (Very early on, C++ was a pre-processor that output C code.) Java doesn't need to do that because it was built with overloading in mind. But at the high level where we deal with them, the functions have the same name.

Автор: T.J. Crowder Размещён: 20.08.2016 03:27

0 плюса

Function overload. c++, can do that.


edit:

ok. i added more details. sorry, I am new in programming. i am afraid of giving wrong answer.

func foo1(_ x: Int) {
    print("the argument is Int")
}
func foo1(_ x: Double) {
    print("the argument is Double")
}

// it depends the type of the value to pass to the function.
foo1(3) // print "the argument is Int"
foo1(4.7) // print "the argument is Double"

// when you assign the function to a variable,
// and there are other functions with the same name and same parameter names, 
// then, you have to tell the type of the function explicitly.
let pToFunc1: (Int) -> Void = foo1

// but normally, you can assign it without telling the type.
func foo2(x: Int){}
let pToFunc2 = foo2

// but same function name with different parameter names,
// when you assign this function, you need to tell the parameter explicitly.  
func foo3(x: Int){}
foo3(x: 4)
func foo3(y: Int){}
foo3(y: 5)
let pToFunc3 = foo3(x:)
Автор: Carl Hung Размещён: 20.08.2016 03:30
Вопросы из категории :
32x32