Class vs Struct for Acronym Model

Hi all

As an iOS developer new to server side development, I was wandering why the Acronym model is a class and not a struct?

On the iOS client side I would make Acronym a struct for the associated benefits of using a struct over a class (speed, value semantics etc.). I’m halfway through chapter 7 and haven’t seen any reason why it should be class over a struct.

Would be great to understand is there is a benefit to using a class in this instance on the server side.

Thanks and Vapor is Amazing!!

@0xtim Can you please help with this when you get a chance? Thank you - much appreciated! :]

@swiftlearnerforlife I’m interested in what value semantics are useful for models? You can use structs if you want, but it makes much more sense to have reference semantics for models. Things like being able to mutate properties on a let object, not having to copy the object inside closures when it’s retrieved as a parameter etc

Completely new to server side development coming from iOS and a non computer science degree / background.

Is there any difference in speed and memory use between a class and struct in server side Swift?

With value semantics you don’t need to worry about retain cycles. Is that an issue that you need to ever consider on the server?

I changed the Acronym model to a struct and it does make it more complicated when having to mutate properties via the update request although adding a custom init in an extension to the Acronym model doesn’t seem too bad.

Have a look at this talk from dotSwift about performance and using class/structs

1 Like

@swiftlearnerforlife if you still want to use Acronym as a struct, the update route of Chapter 7 will be:

router.put("api", "acronyms", Int.parameter) {
    req -> Future<Acronym> in
    return try req.content.decode(Acronym.self).flatMap(to: Acronym.self) { updatedAcronym in
        let id = try
        let acronym = Acronym(id: id, short: updatedAcronym.short, long: updatedAcronym.long)
        return req)
1 Like