简单的Swift类无法编译 [英] Simple Swift class does not compile

查看:83
本文介绍了简单的Swift类无法编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的简单类ClassWithOneArray产生此错误:

My simple class, ClassWithOneArray, produces this error:

位广播要求两个操作数都必须是指针,或者都不是%19 = 将i64%18位广播到%objc_object *,!dbg!470 LLVM错误:损坏 函数找到,编译中止!命令 /Applications/Xcode6-Beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift 失败,退出代码为1

Bitcast requires both operands to be pointer or neither %19 = bitcast i64 %18 to %objc_object*, !dbg !470 LLVM ERROR: Broken function found, compilation aborted! Command /Applications/Xcode6-Beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift failed with exit code 1

但是,我的班级ClassWithOneInt却没有.为什么?

However, my class, ClassWithOneInt, does not. Why?

class ClassWithOneInt {
    var myInt = Int()
    init(myInt: Int) {
        self.myInt = Int()
    }
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(myInt, forKey: "myInt")
    }
    init(coder aDecoder: NSCoder) {
        self.myInt = aDecoder.decodeObjectForKey("myInt") as Int
    }
}

class ClassWithOneArray {
    var myArray = String[]()
    init(myArray: String[]) {
        self.myArray = String[]()
    }
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(myArray, forKey: "myArray")
    }
    init(coder aDecoder: NSCoder) {
        self.myArray = aDecoder.decodeObjectForKey("myArray") as String[]
    }
}

推荐答案

正如我在评论中指出的那样,您的示例在beta 2上似乎可以很好地编译,尽管由于某些原因它仍然无法工作,原因是有任何用途,ClassWithOneArray需要:

As I point out in comments, your example seems to compile fine on beta 2, although it still won't work for a couple of reasons, for encoderWithCoder to be of any use, ClassWithOneArray needs to:

  1. 声明符合NSCoding,
  2. 实施NSCoding,
  3. 继承自NSObject或实现NSObjectProtocol,并且
  4. 使用一个没有名称的名字.

总而言之,这意味着:

@objc(ClassWithOneArray)
class ClassWithOneArray:NSObject, NSCoding {
    var myArray: String[]
    init(myArray: String[]) {
        self.myArray = myArray
    }
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(myArray, forKey: "myArray")
    }
    init(coder aDecoder: NSCoder) {
        self.myArray = aDecoder.decodeObjectForKey("myArray") as String[]
    }
}

似乎也没有在操场上使用测试归档的简单方法,这可能是因为未正确注册类.

Also it seems as if the simple methods of testing archiving aren't available in the playground, probably because the classes don't get properly registered.

let foo = ClassWithOneArray(myArray:["A"])

let data = NSKeyedArchiver.archivedDataWithRootObject(foo)

let unarchiver = NSKeyedUnarchiver(forReadingWithData:data)
unarchiver.setClass(ClassWithOneArray.self, forClassName: "ClassWithOneArray")
let bar = unarchiver.decodeObjectForKey("root") as ClassWithOneArray

这篇关于简单的Swift类无法编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆