I used to be studying the variations between utilizing some
and any
and I typically learn that utilizing any
causes efficiency points. The authors recommend at all times utilizing some
until utilizing any
is completely obligatory.
I wished to know what these efficiency points are as I’m now terrified to make use of any
and exit of my approach to keep away from it even when it means making my code slightly uglier to take a look at. Take into account the next instance:
protocol DogDelegate {
func didBark()
func willBark()
}
struct Canine<D: DogDelegate> {
var delegate: D? // << Making this `(any DogDelegate)?` would look so a lot better
func bark() {
delegate?.willBark()
print("Woof!")
delegate?.didBark()
}
}
On this instance I’ve a struct that has a technique known as bark()
. On this methodology, there are two delegate capabilities that will or will not be known as earlier than and after the bark()
methodology begins/finishes. I exploit a kind parameter to retailer the delegate (if handed into the Canine
initialiser), or nil
. Nonetheless, this – in my view – makes situations of Canine
look kinda ugly. eg. Canine<SomeImplementingType>
versus the a lot cleaner Canine
. The usage of generics additionally appears clunky as in comparison with simply (any DogDelegate)?
.
I care about writing optimised code, even when it might be pointless. So would utilizing generics be most well-liked on this case? Or is the efficiency disadvantage so small that even when I had one million Canines in an array it would not trigger a big efficiency drop? Briefly explaining what sort of efficiency issues are prompted when utilizing existential varieties would even be useful because the authors of the articles I learn did not point out what they’re, nor do I understand how to determine it out myself.
Thanks upfront.
P.S. I bolded “struct” as a result of in my precise code I’m utilizing structs that make use of delegates. I do not know if that is thought of “dangerous follow” as a result of to my information, solely lessons use delegates. Nonetheless, I see no rule in opposition to structs utilizing them so I did it.