(ObjC - > Swift)转换函数“init”& “textureNamed”

时间:2015-04-13 10:46:28

标签: ios objective-c swift sprite-kit

当我尝试在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”功能中:

  1. 功能声明中的预期标识符 - > (public func init - > 自)
  2. 无法将类型为“NSMutableDictionary”的值分配给“NSMutableDictionary”类型的值? - > (返回textureCache = NSMutableDictionary())
  3. 对于“textureNamed”函数:

    1. 无法使用类型为'(String!)'的参数列表调用'textureCache' - > (返回textureCache(textureName))
    2. 如果有人可以帮助我,那就太棒了。

3 个答案:

答案 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!
}

但我仍然不确定,错误消失了,希望以后不会崩溃......