gpt4 book ai didi

Swift - 如何在类属性中存储结构实例

转载 作者:行者123 更新时间:2023-11-30 12:20:07 25 4
gpt4 key购买 nike

我对 Swift 非常陌生,所以如果这是一个“愚蠢”的问题,我预先表示歉意。我正在编写一个用于生成随机元素(在本例中为武器)的 Playground 脚本。当我运行代码时,出现此错误:错误:执行被中断,原因:EXC_BAD_INSTRUCTION(代码= EXC_I386_INVOP,子代码= 0x0)。我试图做的是保存结构的实例(这是句柄)在我的类中的变量 WeaponHandle 中的 NormalBladeType 中。我尝试过研究这个主题,但尚未找到答案。任何建议都会很棒。据我所知,我的做法可能完全错误。

谢谢

我的代码:

//: Playground - noun: a place where people can play

import Cocoa



let handleWoods = ["White Ash", "Oak", "White Oak", "Elm", "Maple","Walnut", "Cherry", "Rosewood", "Ash", "Hickory", "Birch", "Hemlock", "Cedar", "Pine"]
let handleGrips = ["Leather", "Buckskin", "Sharkskin", "Goat Skin", "Deerskin", "Elk Skin", "Rayskin", "Snakeskin", "Silk Cord", "Cotton Cord"]
let gripQualities = ["Simple", "Interwoven", "Ornate", "Smooth", "Thin", "Thick", "Ruff", "Worn"]

func returnRandomItem( _ list: [Any])-> Any {
return list[Int(UInt32(list.count))]
}




struct handle {
var name: String
var value, grip: Int
var weight: Double
var withGrip: Bool

init(withGrip: Bool) {
self.weight = 0.25
self.withGrip = withGrip
let handleNameWithWood = "\(returnRandomItem(handleWoods)) Handle"
if self.withGrip {
let randGrip = "\(returnRandomItem(gripQualities)) \(returnRandomItem(handleGrips)) Grip)"
self.name = "\(randGrip) (\(handleNameWithWood))"
self.grip = 75
self.value = 2
} else {
self.name = handleNameWithWood
self.grip = 50
self.value = 1
}
}

func description() {
print("Handle Description \(self.name)")
}

}


class weapon {
var TypeOfWeapon: String
var weaponHandle: handle

init(weaponType: String, doesHaveGrip: Bool) {
self.TypeOfWeapon = weaponType
self.weaponHandle = handle(withGrip: doesHaveGrip)
}
}

class normalBladeType: weapon {
init() {
super.init(weaponType: "normalBladeType", doesHaveGrip: false)
}

func description() {
print("TypeOfWeapon: \(self.TypeOfWeapon)")
print("TypeDescription: normal hilt (guard - handle - pommel) + straight blade")
}
}


var foo = normalBladeType()
foo.description()

最佳答案

您的returnRandomItem函数是错误的。您应该将其更改为

func returnRandomItem( _ list: [Any])-> Any {
let index: UInt32 = arc4random_uniform(UInt32(list.count))
return list[Int(index)]
}

这段代码对我来说工作得很好。

关于Swift - 如何在类属性中存储结构实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44895182/

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