【问题标题】:(ObjC -> Swift) Convert function "init" & "textureNamed"(ObjC -> Swift) 转换函数“init”和“textureNamed”
【发布时间】:2015-04-13 10:46:28
【问题描述】:

当我尝试在 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”类型的值? -> (return textureCache = NSMutableDictionary())

对于“textureNamed”函数:

  1. 无法使用“(String!)”类型的参数列表调用“textureCache” -> (return textureCache(textureName))

如果有人可以帮助我,那就太棒了。

【问题讨论】:

    标签: ios objective-c swift sprite-kit


    【解决方案1】:

    我会尝试这样的:

    class Test: NSObject {
    
      var textureCache = [String:SKTexture]()
    
      override init() {
        super.init()
      }
    
      func textureNamed(name: String) -> SKTexture? {
        return self.textureCache[name]
      }
    
    }
    

    【讨论】:

    • 感谢您的帮助! ^^
    【解决方案2】:

    好的,让我们分解问题。

    Swift 不需要 init 的返回类型,如果您有超类,则需要调用 super.init()

    public func init() {
        super.init() //required if you have a superclass as the override after public
        textureCache = NSMutableDictionary()
    }
    

    第二个问题,方法看起来是正确的,问题与textureCache是一个Optional有关,所以这里有两个解决方案。

    解包变量并返回缓存的纹理缓存:

    public func textureNamed(textureName: String!) -> SKTexture! {
        return textureCache?(textureName)
    }
    

    或者将textureCache声明为非可选值,因为你实际上是在init方法中初始化它:

    var textureCache: NSMutableDictionary  
    
    public func textureNamed(textureName: String!) -> SKTexture! {
           return textureCache(textureName)
        }
    

    【讨论】:

    • 感谢您的帮助! ^^
    【解决方案3】:

    感谢您的回答,这两种情况都不起作用! ^^ 但是你帮了我很多,因为我“找到”了一个解决方案:

    public init() {
        textureCache = NSMutableDictionary()
    }
    
    public func textureNamed(textureName: String!) -> SKTexture! {
        return textureCache?[textureName] as! SKTexture!
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-06
      • 1970-01-01
      • 2019-07-31
      • 1970-01-01
      相关资源
      最近更新 更多