Protocol Conformity
Sometimes it is necessary to check whether a type is of a protocols type. For example, if you create a Human
class, which is Humanizable
, you want to check an array of objects to see whether one of those elements conforms to the protocol. You use the is
and as
keywords to downcast the type to check its conformance to the protocol.
Using the keyword is
returns true
if the instance conforms to the protocol, and it is a good method to use if you do not need any downcast instance passed along to the inner scope of the if
statement. If you do need a reference to the downcast instance, you can use the optional as?
keyword. Here is an example of using both keywords. Notice that there is a little an extra detail you have to add in ...
Get Learning Swift™ Programming now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.