Swift 框架中的单例模式
Swift singleton pattern in a framework
我在 Xcode 中有一个工作区,其中包含我的框架和一个测试应用程序,因此一个工作区中有两个 xcode 项目。
在框架中,我正在构建一个 singleton
class,如下所示:
public let sharedInstance = MKUserPreferences()
class func A() {}
class func B() {}
但是当我在应用程序项目中并尝试调用 MKUserPreferences.sharedInstance.A()
时,它不会自动完成并且该方法不可用。我该如何解决?
编辑:请记住 MKUserPreferences
在动态链接框架中,我想在我的应用程序(其他项目)中使用它。
在 swift 中,您可以像这样构建一个 OneLine 单例 class:
static let sharedInstance = MKUserPreferences()
private override init() {
super.init()
}
func otherFunc(){}
你可以这样使用:
MKUserPreferences.sharedInstance.otherFunc()
希望这对您有所帮助。
A
和 B
被定义为 class
方法。因此,可以从 class MKUserPreferences.A()
但不能从实例访问它们。
如果您希望它们成为实例方法,只需从它们的定义中删除 class
:
public class MKUserPreferences {
public static let sharedInstance = MKUserPreferences()
private init() {} // Prevents using the default '()' initializer
public func A() {}
public func B() {}
}
此外,您需要明确定义您想成为的方法 public。在 Apple's words:
A public type defaults to having internal members, not public members. If you want a type member to be public, you must explicitly mark it as such. This requirement ensures that the public-facing API for a type is something you opt in to publishing, and avoids presenting the internal workings of a type as public API by mistake.
我在 Xcode 中有一个工作区,其中包含我的框架和一个测试应用程序,因此一个工作区中有两个 xcode 项目。
在框架中,我正在构建一个 singleton
class,如下所示:
public let sharedInstance = MKUserPreferences()
class func A() {}
class func B() {}
但是当我在应用程序项目中并尝试调用 MKUserPreferences.sharedInstance.A()
时,它不会自动完成并且该方法不可用。我该如何解决?
编辑:请记住 MKUserPreferences
在动态链接框架中,我想在我的应用程序(其他项目)中使用它。
在 swift 中,您可以像这样构建一个 OneLine 单例 class:
static let sharedInstance = MKUserPreferences()
private override init() {
super.init()
}
func otherFunc(){}
你可以这样使用:
MKUserPreferences.sharedInstance.otherFunc()
希望这对您有所帮助。
A
和 B
被定义为 class
方法。因此,可以从 class MKUserPreferences.A()
但不能从实例访问它们。
如果您希望它们成为实例方法,只需从它们的定义中删除 class
:
public class MKUserPreferences {
public static let sharedInstance = MKUserPreferences()
private init() {} // Prevents using the default '()' initializer
public func A() {}
public func B() {}
}
此外,您需要明确定义您想成为的方法 public。在 Apple's words:
A public type defaults to having internal members, not public members. If you want a type member to be public, you must explicitly mark it as such. This requirement ensures that the public-facing API for a type is something you opt in to publishing, and avoids presenting the internal workings of a type as public API by mistake.