How do I subclass a struct in Swift?
It is not possible to subclass a struct
in Swift, only classes can be subclassed. An extension
is not a subclass, it's just adding additional functionality on to the existing struct
, this is comparable to a category in Objective-C.
Please see the Apple Swift documentation here to read about the differences between struct
and class
.
Since Swift 5.1 it is now possible to do something similar to what you asked for: using composition, with KeyPath
and dynamicMemberLookup
. Have a look: https://medium.com/@acecilia/struct-composition-using-keypath-and-dynamicmemberlookup-kind-of-struct-subclassing-but-better-6ce561768612?source=friends_link&sk=da479578032c0b46c1c69111dfb6054e
You cannot subclass structures in Swift but you can, in some sense, mimic subclassing by creating a structure that simply vends out the structure that you wish to subclass. For example, if you wanted to subclass Calendar
(a structure), you could create a structure that returns configured calendars.
struct WorldCalendar {
let american1: Calendar = {
var c = Calendar(identifier: .gregorian)
c.timeZone = .current
c.locale = Locale(identifier: "en_US_POSIX")
return c
}()
static let american2: Calendar = {
var c = Calendar(identifier: .gregorian)
c.timeZone = .current
c.locale = Locale(identifier: "en_US_POSIX")
return c
}()
static func american3() -> Calendar {
var c = Calendar(identifier: .gregorian)
c.timeZone = .current
c.locale = Locale(identifier: "en_US_POSIX")
return c
}
}
let worldCalendar = WorldCalendar()
let cal1 = worldCalendar.american1
let cal2 = WorldCalendar.american2
let cal3 = WorldCalendar.american3()
How you vend the configured structures (as an instance property, a static property, a static function, etc.) is just a matter of what better fits into your application and, frankly, personal preference.