1

I have some simple code in my Utilities.swift because I can never remember "uftwhatever" or count(self).

extension String {
    func length() -> Int {
        return count(self)
    }
}

But this means to call it I need to use something like...

let l = myString.length()

I'd my prefer to do...

let l = myString.length

But I can't figure it out. Is this possible?

Maury Markowitz
  • 9,082
  • 11
  • 46
  • 98

1 Answers1

1

Yes, It is possible. You just have to create it as a read-only computed property as follow:

Read-Only Computed Properties

A computed property with a getter but no setter is known as a read-only computed property. A read-only computed property always returns a value, and can be accessed through dot syntax, but cannot be set to a different value.

NOTE

You must declare computed properties—including read-only computed properties—as variable properties with the var keyword, because their value is not fixed. The let keyword is only used for constant properties, to indicate that their values cannot be changed once they are set as part of instance initialization.

You can simplify the declaration of a read-only computed property by removing the get keyword and its braces:

extension String {
    var length: Int {
        return count(self)   // Swift 1.2
    }
}


"Hello World".length // 11
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • Very interesting! I never would have found this simply because of the naming, it's just not something I would have looked for. Thanks! – Maury Markowitz Feb 21 '15 at 19:43
  • If there is no parameters I use a read-only computed property otherwise I use a function – Leo Dabus Feb 21 '15 at 19:45
  • I have to say, both the name and syntax for this feature are bizarre. I don't know about you, but when I see this I think "a function without parameters" not "read-only computed property". And in my mind I should be able to simply leave off the () on a function. Swift has some very odd syntax... – Maury Markowitz Feb 21 '15 at 19:57
  • That's funny I love this way of doing it – Leo Dabus Feb 21 '15 at 19:58