2 New Xcode 11.4 Features for Swift that We Love
Xcode’s latest release, 11.4 Beta 3, has brought advancements across the board. Here’s our rundown of the two new features we love and think could benefit you the most.
Xcode’s latest release, 11.4 Beta 3, has brought advancements across the board. In particular, we found a couple of handy additions to Apple’s beloved programming language, Swift. Here’s our rundown of the two new features we love and think could benefit you the most.
func callAsFunction
methods
func
callAsFunction
methods, i.e. those that are written into a struct, such as Subtracter
below, can be called directly as you normally would with a function. The call syntax is shorthand for applying func callAsFunction
methods.
struct Subtracter {
var base: Int
func callAsFunction(_ x: Int) -> Int {
return x - base
}
}
var subtracter = Subtracter(base: 3)
subtracter(10) // returns 7, same as subtracter.callAsFunction(10)
Each method within the type that you wish to call directly (i.e. Subtracter
in our above example) must be defined with the func
callAsFunction
argument label. You can add multiple func callAsFunction
methods on a single type, and you can mark them as mutating.
Use struct to create a structure. Structures support many of the same behaviors as classes, including methods and initializers. One of the most important differences between structures and classes is that structures are always copied when they are passed around in your code, but classes are passed by reference. – A Swift Tour
Subscripts declare default arguments
struct Subscriptable {
subscript(x: Int, y: Int = 0) {
... }
}
let s = Subscriptable()
print(s[0])
The above example (drawn straight from the release notes) instantiates the struct Subscriptable
as s
, and then demonstrates the presence of a default value by printing the item that exists at index 0.