Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
538 views
in Technique[技术] by (71.8m points)

swift - What's the difference between using or not using the 'where' clause with generics?

What's the difference between these two methods of declaring a generics superclass with or without the 'where' clause?

func foo<T: SomeClass>(object: T) -> Array<T>

func foo<T>(object: T) -> Array<T> where T: SomeClass
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is clearly stated in the Swift guide:

The requirements in a generic where clause specify that a type parameter inherits from a class or conforms to a protocol or protocol composition. Although the generic where clause provides syntactic sugar for expressing simple constraints on type parameters (for instance, <T: Comparable> is equivalent to <T> where T: Comparable and so on), you can use it to provide more complex constraints on type parameters and their associated types. For instance, you can constrain the associated types of type parameters to conform to protocols. For example, <S: Sequence> where S.Iterator.Element: Equatable specifies that S conforms to the Sequence protocol and that the associated type S.Iterator.Element conforms to the Equatable protocol. This constraint ensures that each element of the sequence is equatable.

Simply put, where lets you specify constraints about the associated types of a generic parameter, while in <> you can't do this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...