Learn Courses My Dashboard

Function or extension - which is better?

Let’s say I want to add the capability to trim white space from the ends of a String. I can write a function:

  func trimmed(_ item: String) -> String
  { item.trimmingCharacters(in: .whitespacesAndNewlines) }

let trimmedStr = trimmed(str)

or I can use an extension:

extension String {
  func trimmed() -> String {
     self.trimmingCharacters(in: .whitespacesAndNewlines)

let trimmedStr = str.trimmed()

Is there any advantage to using one method over the other?

If you make it an extension then it becomes a globally available function whereas if you just create a function in the scope in which you are using it then it is limited to that scope.

It just depends on if you intend to use it in lots of places. If so then make in an extension.

Can’t I just define the function with global scope?

I think it would be better to use an extension because if you use a function, then your String gets copied 1) when you pass it as a parameter, and 2) when you trim the input String. With an extension, it only gets copied 1) when you trim the String.

Also, global functions are really not the Swift way, whereas extending a type is. You’ll note that Swift tends not to use global functions as much as some other languages do.

Ok, I’m convinced. Thanks.