gpt4 book ai didi

swift - 快速从类创建数组

转载 作者:行者123 更新时间:2023-11-30 10:11:09 24 4
gpt4 key购买 nike

我似乎无法创建包含用户的数组。我必须创建 10 个用户的数组..如何正确创建它?

import UIKit

enum DeviceType {
case Phone, Tablet, Watch
}

enum OperatingSystemType {
case iOS, Android, Windows
}

struct OperatingSystemVersion {
var Major: Int
var Minor: Int
var Patch: Int
}

struct OperatingSystem{
var type: OperatingSystemType
var version: OperatingSystemVersion

}

class Device {
var DeviceID: Int
var Type: DeviceType
var Operating_System: OperatingSystem
var UserID: Int
var Description: String
var InventoryNR: String
init () {
DeviceID = 1233
Type = .Phone
Operating_System = OperatingSystem(type: .iOS, version: OperatingSystemVersion(Major: 9, Minor: 0, Patch: 2))
UserID = 2
Description = "took"
InventoryNR = "no17"
}
}

class User {
var UserID: Int
var Username: String
var Location: String
var Devices: [Device]
init() {
UserID = 566
Username = "david"
Location = "Fortech"
Devices = [Device.init()]
}
}

var Users = [User] ()
Users.append(UserID: 23, Username: "David", Location: "HQ", Devices : User)

最佳答案

您需要为您的 User 类(以及其他类,但我们在这里重点关注 User 作为示例)创建一个有效的初始值设定项。

class User {
var UserID: Int
var Username: String
var Location: String
var Devices: [Device]
init(userID: Int, username: String, location: String, devices: [Device]) {
self.UserID = userID
self.Username = username
self.Location = location
self.Devices = devices
}
}

现在您可以创建一个用户:

let david = User(userID: 23, username: "David", location: "HQ", devices : [Device()])

并将其添加到您的Users数组中:

Users.append(david)

注意:类名以大写字母开头,但变量应以小写字母开头。因此,您的 var UserID: Int 应该是 var userID: Int 例如,Users 数组应该是 users,等等

关于swift - 快速从类创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33000827/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com