Home > Enterprise >  Is the highlighted block of code a computed property?
Is the highlighted block of code a computed property?

Time:11-06

class Fruit {
    var name: String
    var colour: String
    
    init(name: String, colour: String) {
        self.name = name
        self.colour = colour
    }
    
    **var info: () -> String {
        {
            return "\(self.name) is \(self.colour) in colour"
        }
    }
}**

let fruit = Fruit(name: "apple", colour: "red")
print(fruit.info())

Hi,

Can someone explain the type of property of the variable name "info" in the above block of code.

If it is a computed property, can a computed property be written in swift without a get block?

CodePudding user response:

Yes, it is a computed property, of type () -> String (ie. a function with no argument returning a string).

For a computed property returning just a String, which seem to be preferable in your case, you could write :

var computedProperty: String
{
   get
   {
        return "\(self.name) is \(self.colour) in colour"
   }
}

When a property is get-only, you do not need to write the get{} block.

var computedProperty: String
{
   return "\(self.name) is \(self.colour) in colour"
}

And if it is only one line, you don't even need to write the return.

var computedProperty: String
{ "\(self.name) is \(self.colour) in colour" }

CodePudding user response:

info is a read-only computed property. It is declared to have a type that is a closure that takes no parameters and returns a String.

Read-only computed properties do not need an explicit get. The info property is using a shorthand notation. You can actually get rid of one of the two pairs of curly braces.

It's odd to declare the info property to be a closure in this case. It would be much simpler to declare it as:

var info: String {
    "\(self.name) is \(self.colour) in colour"
}

Then you can use it as normal:

print(fruit.info) // <-- Note the lack of () after `info` here.

You should read the Properties section of the Swift book. In this case, the Computed Properties section covers most of your question.

  • Related