简体   繁体   English

如何使用 Swift 在结构中打印方法的 output?

[英]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?我是编程和 Swift 的新手。为什么 getDetails function 底部的简单 print(getDetails()) 不足以获取 output? It always returns an error "Expected '{' in body of function declaration".它总是返回错误“在 function 声明的正文中预期为‘{’”。

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())
}

At the top level of a struct or class , you're only allowed to define functions and properties.structclass的顶层,您只能定义函数和属性。 For example, your let make:String = "MINI" or func getDetails() -> String { ... } are valid top-level declarations.例如,您的let make:String = "MINI"func getDetails() -> String { ... }是有效的顶级声明。

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.但是,不允许将未定义函数或属性(如print("") )的命令式代码放在此类类型的顶层。

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).如果你在 Swift 的操场上,你可以将命令式代码放在文件的顶层(不是结构体或类)。 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:由于getDetails所做的只是返回details ,这有点多余,所以我们可以重构为:

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)
import UIKit
import Foundation
struct Car {
   private var make = "Toyota"
  private  var model = "Camry"
    private var year = "1999"
   private var details:String {
        year + " " + make + " " + model
    }
  func getDetails () -> String {
    return details
 }
}
let a:Car = Car()
print (a.getDetails())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM