当我尝试在Swift中转换2个函数时,我遇到了一些错误!
ObjC
@property (nonatomic, strong) NSMutableDictionary *textureCache;
- (instancetype)init {
if (self = [super init])
{
self.textureCache = [NSMutableDictionary dictionary];
}
return self;
}
- (SKTexture *)textureNamed:(NSString *)textureName {
return _textureCache[textureName];
}
夫特
var textureCache: NSMutableDictionary?
public func init() -> Self {
return textureCache = NSMutableDictionary()
}
public func textureNamed(textureName: String!) -> SKTexture! {
return textureCache(textureName)
}
在“init”功能中:
对于“textureNamed”函数:
如果有人可以帮助我,那就太棒了。
答案 0 :(得分:0)
我会尝试这样的事情:
class Test: NSObject {
var textureCache = [String:SKTexture]()
override init() {
super.init()
}
func textureNamed(name: String) -> SKTexture? {
return self.textureCache[name]
}
}
答案 1 :(得分:0)
好的,让我们分解问题。
Swift不需要init的返回类型,如果你有超类,你需要调用super.init()
:
public func init() {
super.init() //required if you have a superclass as the override after public
textureCache = NSMutableDictionary()
}
第二个问题,该方法看起来正确,问题与textureCache
是可选的事实有关,所以你在这里有两个解决方案。
展开变量并返回缓存的缓存纹理:
public func textureNamed(textureName: String!) -> SKTexture! {
return textureCache?(textureName)
}
或者将textureCache
声明为非可选值,因为您实际上是在init方法中初始化它:
var textureCache: NSMutableDictionary
public func textureNamed(textureName: String!) -> SKTexture! {
return textureCache(textureName)
}
答案 2 :(得分:0)
感谢您的回答,这两种情况都不起作用! ^^ 但是你帮助了我很多,因为我“找到了”解决方案:
public init() {
textureCache = NSMutableDictionary()
}
public func textureNamed(textureName: String!) -> SKTexture! {
return textureCache?[textureName] as! SKTexture!
}
但我仍然不确定,错误消失了,希望以后不会崩溃......