![]() ![]() Since the above API is for performing an action, rather than assigning a value, a good old fashioned method would arguably be much more appropriate: send( Notification(value: user), forEvent. For example, it’s not very clear that this line of code causes a notification to be sent: notificationsToSend = Notification(value: user) However, while subscripting is really convenient for a somewhat narrow set of use cases, it could also lead to quite confusing code if used outside the realm of dynamically getting and setting values. Just compare the above two APIs to what their method equivalents would look like: let fifthElement = array. Rather than having to call specific methods with names that we either need to remember or look up, subscripting lets us simply retrieve a value using just its index or key: let fifthElement = array Subscripts vs methodsĪrguably the biggest benefit of subscripting is the incredibly lightweight syntax that it gives us at the call site. This week, let’s take a look at how subscripting works in Swift, and a few different ways to incorporate it into the way we design APIs - including some brand new capabilities that are being added in Swift 5.1. However, the way subscripting is actually implemented in Swift is both quite unique, and really powerful - as it lets us add subscripting APIs to our own types, just like those found in the standard library. Using subscripting to access elements within various collections, like arrays and dictionaries, is something that’s very common not only in Swift - but in almost all relatively modern programming languages.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |