LukasDreams
LukasDreams

Reputation: 39

How to print output of method in a struct with Swift?

I'm VERY new to programming and Swift. Why won't a simple print(getDetails()) at the bottom of the getDetails function suffice to get the output? It always returns an error "Expected '{' in body of function declaration".

Here's the code...

struct Car {
    let make:String = "MINI"
    let model:String = "COOPER"
    let year:String = "2015"
    
    var details:String {
        return year + " " + make + " " + model
    }
    func getDetails() -> String {
        return details
    }
    print(getDetails())
}

Upvotes: 0

Views: 594

Answers (1)

jnpdx
jnpdx

Reputation: 52397

At the top level of a struct or class, you're only allowed to define functions and properties. For example, your let make:String = "MINI" or func getDetails() -> String { ... } are valid top-level declarations.

You are not, however, allowed to put imperative code that doesn't define a function or property (like print("")) at the top level of a type like this.

If you were in a Swift playground, you can put imperative code at the top level of the file (not of the struct or class). So, this would be valid:

struct Car {
    let make:String = "MINI"
    let model:String = "COOPER"
    let year:String = "2015"
    
    var details:String {
        return year + " " + make + " " + model
    }
    func getDetails() -> String {
        return details
    }
}

let myCar = Car()
print(myCar.getDetails())

Since all getDetails does is return details, it's a bit superfluous, so we could refactor to just this:

struct Car {
    let make:String = "MINI"
    let model:String = "COOPER"
    let year:String = "2015"
    
    var details:String {
        return year + " " + make + " " + model
    }
}

let myCar = Car()
print(myCar.details)

Upvotes: 1

Related Questions