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

标签 swift class struct initialization instance

我对 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/

相关文章:

C支持基础类吗?

c++ - 派生结构与指向其他结构的结构

c - 使用 scanf 读取 uint8_t 数据

ios - Swift - 使用哪些类型? NSString 或字符串

swift - 在 SKScene 中定位 SKSpriteNode 的问题

ios - 将 json 数据转换为 [[String : AnyObject]] it seems to be empty - why?

c++ - 我无法理解 C++ 中的结构声明

swift - 如何在 Swift 3 中将 UInt16 转换为 UInt8?

c++ - 除了定义变量的地方之外,如何在不调用 new 的情况下调用 C++ 构造函数?

c - 将数组(不是指针)传递给 c 中的结构