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

前端 未结 2 1850
醉话见心
醉话见心 2020-12-10 13:49

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

func foo(object         


        
2条回答
  •  隐瞒了意图╮
    2020-12-10 14:16

    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, is equivalent to 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, 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.

提交回复
热议问题