gpt4 book ai didi

ios - 如何自动生成基于类的对象 iOS Swift

转载 作者:行者123 更新时间:2023-11-28 17:48:34 24 4
gpt4 key购买 nike

抱歉,我无法让代码片段正常工作。不知道如何让它识别 Swift。

我的问题是我有一个名为“Crewman”的类,我想在“generateCrew”函数中基于这个类生成 25 个对象。 (我目前正在 Xcode 中的测试文件中尝试这个)我不知道如何修复它以便它们都以不同的方式命名。如果我给这些对象一个特定的名称,那么在接下来的 24 次我运行该函数时它只会覆盖第一个。

我是 iOS/Swift 的新手,所以很想得到帮助……尤其是对我来说尽可能地愚蠢哈哈哈哈谢谢! :D

//This is the class constructor, if thats the right word...

class Crewman {
var name: String!
var navSkill: Int! // #/10
var combatSkill: Int! // #/10
var morale: Int! // #/10
var loyalty: Int! // #/10
}


//This is where I am trying to create the objects within a function

var crewNames =
["Chance", "Bruno", "Toby", "Damien", "Rafael", "Domenic", "Weston", "Edison", "Chris", "Grant", "Cortez", "Darren", "Nicolas", "Everette", "Jason", "Vicente", "Noe", "Ricky", "Ivory", "Thomas", "Guillermo", "Isreal", "Ben", "Winfred", "Lincoln", "Kareem", "Antwan", "Greg", "Lawrence", "Corey", "Todd", "Jeffery", "Rayford", "Julio", "Manual", "Chi", "Bradford", "Devon", "Bryan", "Andreas", "Don", "Erik", "Bobbie", "Tyree", "Felipe", "Clifton", "Carrol", "Kasey", "Cliff", "Jack"]

//Lincoln is no.25

var crewmenAll = [Crewman]()

func generateCrew()
{
for i in 1...25
{
var crewNames[i]:Crewman!
crewmenAll.append(nameOfCrew)
print(crewmenAll)
}
}

override func setUp() {

for i in 1...25
{
let x = Int.random(in: 0..<50)
let name = crewNames[x]

let navInt = Int.random(in: 3...7)
let combatInt = Int.random(in: 3...7)
let moraleInt = Int.random(in: 3...7)


crewmenAll[i] = Crewman(name: name, navSkill: navInt, combatSkill: combatInt, morale: moraleInt, loyalty: 5)

}


最佳答案

首先你应该改变你的类,因为没有必要像你那样强制解包(!)普通属性,而是添加一个合适的初始化方法

class Crewman {
var name: String
var navSkill: Int
var combatSkill: Int
var morale: Int
var loyalty: Int

init(name: String, navSkill: Int, combatSkill: Int, morale: Int, loyalty: Int) {
self.name = name

self.navSkill = navSkill
self.combatSkill = combatSkill
self.morale = morale
self.loyalty = loyalty
}
}

我不明白为什么你有这两个功能 generateCrewsetUp因为它们看起来很相似所以我只保留 setUp .

setUp我保留了大部分代码并使用了新的 init 方法,然后添加了每个新的 Crewman。使用 append 反对数组购买的末尾.

为了获得随机名称,我打乱了名称数组,使它们以随机顺序排列,然后我可以使用索引 i 从该数组中挑选它们。 .还要注意数组的索引从 0 而不是 1 开始,所以我更改了 for循环一下

var crewmenAll = [Crewman]()
var crewmen = [String: Crewman]()

func setUp() {
let randomOrder = crewNames.shuffled()

for i in 0..<25 {
let name = randomOrder[i]

let navInt = Int.random(in: 3...7)
let combatInt = Int.random(in: 3...7)
let moraleInt = Int.random(in: 3...7)

crewmenAll.append(Crewman(name: name, navSkill: navInt, combatSkill: combatInt, morale: moraleInt, loyalty: 5))
}
crewmen = crewmenAll.reduce(into: [:]) {$0[$1.name] = $1 }
}

关于ios - 如何自动生成基于类的对象 iOS Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59695735/

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