Sunday, September 14, 2014

A Fascinating Feature of Swift

I was just re-reading the swift book, The Swift Programming Language, and came across a feature that I overlooked the first time.

You can define a collection whose type is a protocol type.  This collection can include a bunch of objects of different types that all conform to a single protocol.  

Why is this useful?  When working with values whose type is a protocol type, methods and properties outside the protocol definition are not available.  This allows you to have a collection of different objects, but narrowly define the set of operations on that collection through the protocol type of the collection.  What a great way to create a particular perspective on a collection of different objects.

I can use the protocol to encapsulate the reasons I brought these different objects together, preventing unintended access to methods and properties outside the scope of why I brought these objects together.  This has great security benefits.  While we usually think of protocols as a way to extend objects, we can also use protocols to define a subset of existing capabilities of a set of objects.

Swift is a huge language and it continues to grow.  But even with the current features, there are further depths to explore.

No comments:

Post a Comment