Home > Blockchain >  difference between generic while clause and parameter conforming to protocol
difference between generic while clause and parameter conforming to protocol

Time:03-23

i want to know the difference between these two generic func and which one to use

when I use both results is the same so which one to use

func setObject<T: Codable>(object: T, forkey: String){
    
}

func setObject1<T>(object: T, forkey: String) where T : Codable{
    
}

CodePudding user response:

The first example is "sugar" for the second example. They mean the same thing, and compile to the same output. "Sugar" just makes common things easier to write, like T? rather than Optional<T>. (The history here is a little backwards, because the second is the original syntax, but today it's still good to think of it as sugar.)

The first is a little shorter to write for simple signatures. The second is more flexible, and scales better for long signatures, particularly when there are multiple type parameters and more complex requirements.

For your example, I think many (possibly most) folks would use the first since it's so short, but don't be afraid to move to the second if there's any level of complexity beyond this.

For more on the reasoning and intent, see the SE that added the where clause, SE-0081. See the linked pitch thread for the discussion about this. The SE itself only refers to where the where clause goes.

Looking through stdlib, I see both approaches, even for simple requirements (f<T: P>(...) vs f<T>(...) where T:P).

But documentation is generally f<T>(...) where T:P:

init<S>(_ elements: S) where S : Sequence, Element == S.Element

even when the implementation uses the other:

public init<S: Sequence>(_ s: S) where S.Element == Element {

(I see the same differences in brand new concurrency code as very old Array code, so I don't think it's just about the age of the code.)

CodePudding user response:

They mean exactly the same thing. The second one is just uglier.


Edit: I disagree with Rob's opinion—I don't think you should ever use a where clause when you can put the same information into the original constraint, so I'm voting to close this question because I just learned that "which one to use" is a matter of opinion.

I always thought the only reason you'd see these constraints in a where clause is because they were auto-generated. But apparently some people find them acceptable or even preferable under some conditions.

  • Related