简体   繁体   中英

What does this function syntax mean?

I am practicing using some Apple sample code and I seen this function which I never see before. Its seems not to have a name but instead two == signs?!

func ==(_ lhs: Dream, _ rhs: Dream) -> Bool {
return lhs.description == rhs.description &&
       lhs.creature == rhs.creature &&
       lhs.effects == rhs.effects &&
       lhs.numberOfCreatures == rhs.numberOfCreatures
}

Can someone please explain what does it mean? or do?

Thanks!

Check out Swift Comparison Protocols

Generally, it makes it possible to compare two Classes or two Structs. Because when you compare two class, it compare with the memory address, not the content. But this function would make you be able to compare two classes or structs with their contents.

The code you list there, means:

Two Dream() classes are equatable if and only if their description , creature , effects , numberOfCreatures are the same.

It's an operator. It allows you use the function using cleaner syntax instead of a function call.

In this case, it looks like it allows you to compare dreams.

let dream1 = Dream()
let dream2 = Dream()

if dream1 == dream2 {
    // The dreams are equal.
}

Swift has an == operator that reveals whether two things are equal:

if x == 1 {
    // ... do stuff ...
}

But the cool thing is that this operator — and all Swift operators — is just an ordinary function, in this case a function named == . When you say

x == 1

what really happens is that this function is called. Pseudo-syntax would be:

==(x, 1)

...so here we're handing the == function two Int values for comparison, and the result of that call is a Bool.

Okay, are you with me so far? Well, Swift also has overloading of functions. That means we can redefine == to apply to parameter types that we ourselves have created. So if we have a Dream type, we get to say what == means when applied to two Dream objects . And the code you cited is how you do that.

Comparing two objects(structs) are equal.

It is called Operator Overloading.It also exists in C++ or other languages.This is a fancy way of saying you can make operators like +, -, /, or * to work with any type you'd like! You can even define your own operators if you're feeling especially creative.

For more infomation, https://www.raywenderlich.com/80818/operator-overloading-in-swift-tutorial

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM