简体   繁体   English

我如何快速从一个类中初始化一个元组属性?

[英]How do i init a tuple property from a class in swift?

I have this property in my class我的班级有这个属性

var service = (String, Int, Bool)

and i need to use a constructor with init, so i have the next code我需要在 init 中使用构造函数,所以我有下一个代码

init()
{
  self.service(1) = "Fix PC"
  self.service(2) = 400
  self.service(3) = false
}

On every line of the init code i got the next message在 init 代码的每一行上,我都收到了下一条消息

type of expression is ambiguous without more context表达类型不明确,没有更多上下文

, how can i fix it? ,我该如何解决?

I'm a student, recently using swift, still cant find a solution我是学生,最近在用swift,还是找不到解决办法

That is not the way to assign a value to a tuple.这不是给元组赋值的方法。 You need to assign the tuple as a whole, you cannot assign its properties 1-by-1.您需要将元组作为一个整体进行分配,不能一一分配其属性。

var service: (String, Int, Bool)

init() {
    service = ("Fix PC", 400, false)
}

Once the tuple is initialised, you can update its members 1-by-1, however your syntax was wrong, tuple member access is done using .元组初始化后,您可以 1 对 1 更新其成员,但是您的语法错误,元组成员访问是使用. , not () . , 不是()

service.0 = "Fix Mac"

Also, you should only be using tuples as temporary storage, for your example, you should be using a custom type with 3 separate properties.此外,您应该只使用元组作为临时存储,例如,您应该使用具有 3 个独立属性的自定义类型。

struct Service {
    let name: String
    let value: Int
    let bool: Bool
}

let service = Service(name: "Fix PC", value: 400, bool: false)

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

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