为什么建议的Swift单例实现使用结构体? [英] Why does the suggested Swift singleton implementation use a struct?

查看:474
本文介绍了为什么建议的Swift单例实现使用结构体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Swift 常用的Singleton模式在类变量/ type属性中使用了一个Struct。

The commonly accepted Singleton pattern for Swift uses a Struct inside a class variable/type property.

而不是:

class MySingleton {
  class var sharedInstance: MySingleton {
    struct Singleton {
      static let instance = MySingleton()
    }
    return Singleton.instance
  }
}

class MySingleton {
  class var sharedInstance: MySingleton {
      let instance = MySingleton()
      return instance
  }
}

如果这是一个非常愚蠢的问题,但是不要同时利用常量的线程安全性和 let

Apologies if this is a very stupid question. But don't both leverage the thread-safety of constants and let?

推荐答案

与你的实现,'sharedInstance'不是一个singleton原因每次被调用,它创建了MySingleton的新实例。而且,要创建一个静态变量,你必须把它放在结构枚举中,否则会得到编译器错误

with your implementation, the 'sharedInstance' is not a singleton cause each time it gets called, it creates new instance of MySingleton. And, to create a static variable, you have to put it in struct o enums, otherwise, you will get compiler error

这篇关于为什么建议的Swift单例实现使用结构体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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