Swift var添加不起作用

时间:2015-06-03 12:13:33

标签: ios swift var addition

我有多个var

现在我希望我的var totalScore是=我的其他var添加

这是我的代码

var section1score: Int = 0
var section2score: Int = 0
var section3score: Int = 0
var totalScore: Int = section1score + section2score + section3score

此代码无效...在var totalScore中,它告诉我ViewController没有名为section1Score的成员......并停在那里

我做错了什么?

谢谢!

3 个答案:

答案 0 :(得分:4)

您可以将totalScore写为计算属性,以便它始终是其他3个属性的总和。

var totalScore: Int {
    get {
        return section1score + section2score + section3score
    }
}

答案 1 :(得分:1)

此代码是否在函数中?在init()完成之前,您不能使用实例变量。因此,如果他们在一个函数中,这应该工作。

func test() {
    var section1score: Int = 0
    var section2score: Int = 0
    var section3score: Int = 0
    var totalScore: Int = section1score + section2score + section3score
}

或者如果他们需要是实例变量:

var section1score: Int = 0
var section2score: Int = 0
var section3score: Int = 0
var totalScore: Int = 0

init() {
    totalScore = section1score + section2score + section3score
}

答案 2 :(得分:1)

试试这个

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    services.ConfigureMvc(options =>
    {
        // This adds both Input and Output formatters based on DataContractSerializer
        options.AddXmlDataContractSerializerFormatter();

        // To add XmlSerializer based Input and Output formatters.
        options.InputFormatters.Add(new XmlSerializerInputFormatter());
        options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
    });