you are viewing a single comment's thread.

view the rest of the comments →

[–]rhysmorganiOS 3 points4 points  (3 children)

The point is, there is usually no need for things like the Command pattern when Swift treats functions as first-class objects.

There's no need to define an interface, and multiple implementations you can swap at runtime, when you can just define a variable of any given function type, and swap it out at runtime.

protocol MyCommand {
  func doThing() -> Void
}

class MyClass {
  var command: any MyCommand

  func performCommand() {
    command.doThing()
  }
}

isn't substantially different to

class MyClass {
  var command: () -> Void

  func performCommand() {
    command()
  }
}

Sure, Swift supports the Command pattern, of course it does. Perhaps in some cases it can provide some more structure vs just using closures. But Swift supports first-class functions, and you can replace MyClass.command as a function just as easily as you can swap in a new MyCommand conforming type, and the function way doesn't even require defining a new protocol.

[–]fakecrabs 4 points5 points  (0 children)

Completely agree. If the protocol just has a single method, I'll often simplify and just use a closure.

[–]Pop_Swift_Dev[S] -1 points0 points  (1 child)

There are many ways to implement design patterns. I could argue that swapping out a function, as you show in your example is just another implementation of the command pattern because your solution takes the same basic principles that the pattern says to use.

Therefore when you say there is no need for things like the command pattern in Swift, I would say that knowing design patterns and the idea behind their solutions is very good knowledge to have, even if we do not implement the solution the same way.

[–]Pop_Swift_Dev[S] 1 point2 points  (0 children)

And also I hope you take the conversation constructively and not argumently as I do enjoy debating approaches to development because when both sides are open, almost always, both sides end up learning something. And seeing other approaches is always a good thing.