Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 导致崩溃的属性_Swift_Xcode_Attributes - Fatal编程技术网

Swift 导致崩溃的属性

Swift 导致崩溃的属性,swift,xcode,attributes,Swift,Xcode,Attributes,我最近用swift编写了这段代码,但由于某种原因,它使应用程序崩溃 class ShapeColour : NSObject { var colour = "" var shape = "" var images = UIImage(named: "") } //Blue Square let BlueSquareObject = ShapeColour() BlueSquareObject.setValue(

我最近用swift编写了这段代码,但由于某种原因,它使应用程序崩溃

class ShapeColour : NSObject {
        var colour = ""
        var shape = ""
        var images = UIImage(named: "")
    }

    //Blue Square

    let BlueSquareObject =  ShapeColour()
    BlueSquareObject.setValue("Blue", forKey: "colour")
    BlueSquareObject.setValue("square", forKey: "shape")
    BlueSquareObject.setValue("BlueSquare.jpg", forKey: "images")

    //Red Square

    let RedSquareObject =  ShapeColour()
    RedSquareObject.setValue("Red", forKey: "colour")
    RedSquareObject.setValue("square", forKey: "shape")
    RedSquareObject.setValue("RedSquare.jpg", forKey: "images")

    //Yellow Square

    let YellowSquareObject =  ShapeColour()
    YellowSquareObject.setValue("Yellow", forKey: "colour")
    YellowSquareObject.setValue("square", forKey: "shape")
    YellowSquareObject.setValue("YellowSquare.jpg", forKey: "images")
创建属性时我是否做错了什么?任何帮助都将不胜感激;)


谢谢

images
ShapeColour
的属性是
UIImage
的类型,您可以使用它设置
String

BlueSquareObject.setValue(UIImage(named: "BlueSquare.jpg"), forKey: "images")
您需要遵循一些编码准则,比如对象名以小写字母开头。另外,创建对象的最简单方法是使用
init
,这也会减少代码,因此我建议您在
shapeclour
类中添加一个
init
方法,如下所示

class ShapeColour : NSObject {
    var colour:String
    var shape:String
    var images: UIImage

    init(color: String, shape: String, image: UIImage) {
        self.colour = color
        self.shape = shape
        self.image = image
    }
}
现在只需调用
init
即可创建
shapeclour
的实例

let blueSquareObject =  ShapeColour(color: "Blue", shape: "square", image: UIImage(named: "BlueSquare.jpg"))

你需要用你得到的错误更新你的问题。但是,为什么您试图使用
String
值设置名为
images
UIImage
属性?对不起,我是swift新手。你能解释一下我应该如何使用UIimage吗@rmaddyFirst,使用错误更新您的问题,并指出导致错误的行。我没有收到错误,调试器中唯一的行是“错误:通过进程ID“4585”附加失败无法附加”@RmaddyTanks非常感谢!修复了我的问题,大大缩短了我的代码!(完整的属性列表长了4倍;)@Nosh Welcome mate:)