How to create Singleton in generic class using swift 4.2? - ios

I have been trying to convert a singleton class to generic. Since swift doesn't support stored property in generic class Singleton could not be implemented. I tried all the possible solutions that I know but nothing works. Other Stackoverflow answers related to this topic doesn't help either. Can someone help me to get on the right path, please? Thanks in advance.
I have added the sample code below.
class SingleTonClass<T: Equatable & RawRepresentable>: NSObject where T.RawValue == String {
private var catlog: CatlogModelClass<T>?
private var catlogArray = [CatlogModelClass<T>]()
**// This stored property Now has to be changed to support Generic**
private static var shared : SingleTonClass = {
return SingleTonClass()
}()
// Accessor for Singleton
static func sharedInstance() -> SingleTonClass {
return shared
}
private override init () {}
}

If you want it to be non-singleton, you need to create a public constructor.
You should pass in the catalog and catalogArray into the constructor and initialize self.catalog and self.catalogArray. You then need to remove the static shared instance of the class, because your new setup would require you to create an instance of it.

Related

Swift singleton pattern in a framework

I have a workspace in Xcode with my framework and with a test-app, so two xcode projects in one workspace.
In the framework I am building a singleton class, like so:
public let sharedInstance = MKUserPreferences()
class func A() {}
class func B() {}
But when I am in the app project and trying to call MKUserPreferences.sharedInstance.A(), it won't autocomplete and the method is not available. How do I solve this?
EDIT: please keep in mind that MKUserPreferences is in a dynamically linked framework and I want to use it in my app (other project).
A and B are defined as class methods. Therefore, they can be accessed from the class MKUserPreferences.A() but not from an instance.
If you want them to be instance methods, just remove class from their definition:
public class MKUserPreferences {
public static let sharedInstance = MKUserPreferences()
private init() {} // Prevents using the default '()' initializer
public func A() {}
public func B() {}
}
Also, you need to explicitly define the methods you want to be public. In 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.
In swift ,you can build a OneLine singleton class like this:
static let sharedInstance = MKUserPreferences()
private override init() {
super.init()
}
func otherFunc(){}
and you can use like this:
MKUserPreferences.sharedInstance.otherFunc()
hope this will helped you .

Singleton in one line on Swift 2.0

Please help me with Swift,
I need singleton with can inheritance.
I can do like this
class A {
var defaultPort: Int
required init() {
self.defaultPort = 404
}
class var defaultClient: A {
struct Static {
static var onceToken: dispatch_once_t = 0
static var instance: A? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = self.init()
}
return Static.instance!
}
}
but in swift 2.0 we can do like this
static let defaultClient = A() //self.init()
but it creates an instance of the class A any way.
How i can use like this self.init()
static let defaultClient = self.init()
in order to be able to inherit
UPD
best way for now
class A {
class func defaultClient() -> Self {
struct Static {
static var onceToken: dispatch_once_t = 0
static var instance: A? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = self.init()
}
return instance(Static.instance, asType: self)
}
}
here we need helper as
func instance<T>(instance: Any, asType type: T.Type) -> T {
let reurnValue = instance as! T
return reurnValue
}
because another way cast A to Self not exist, for now.
p.s. crazy swift way!
why i can not do instance as! Self
Your question isn't very clear. You're looking for something like the class constant solution posted in this answer, but which automatically uses "my own class" instead of explicitly creating an instance of a specific class... right?
That is, you want to turn this:
class Singleton {
static let sharedInstance = Singleton()
}
into this:
class Singleton {
static let sharedInstance = SomeMagicThing()
}
class SingletonSubclass {}
where SomeMagicThing automatically creates a Singleton instance when you call Singleton.sharedInstance, and a SingletonSubclass instance when you call SingletonSubclass.sharedInstance. Correct?
Sorry, that can't be done (as of Swift 2.1).
Part of your issue is that static and class mean two different things. The static modifier means that the declaration it modifies is associated only with a specific type declaration. So, the Singleton type owns a pointer to a specific object -- its subclasses don't inherit that pointer. (And if they did, would it point to the same object or a subclass-specific one?)
If you could create a class var or class let, that'd (in theory) give you the kind of dispatch/inheritance you want. But trying that gives you an error (emphasis mine):
class stored properties not yet supported in classes; did you mean static?
So it sounds like this sort of thing might show up someday.
Of course, the other side of the problem is finding a way to dynamically refer to the "current" type responsible for executing some statement. In the context of an instance method, you have self.dynamicType for such things... but there's no equivalent for classes. (Self is a type constraint, not an actual type.) This is a side effect of the type system in Swift being much more strict and static than that of Objective-C (for example, metatypes aren't just a special flavor of otherwise normal objects). File a bug if you'd like to see a change to that effect?

Swift error with new xcode ' static properties are only allowed within structs and enums; use class. property'

I am getting the error on the following line.
static let sharedData : SharedData = SharedData()
I am using the new Xcode (6.2) so I don't know why I am getting this error. I thought this should've worked. Please let me know how to resolve this issue. Perhaps I should be using a different version.
Yes, static properties aren't yet allowed inside a class. (What is more, class is the keyword used to create static properties) Here is a work around for you to create static variables:
private struct SubStruct { static var sharedData:SharedData?}
class var sharedData:SharedData? {
get { return SubStruct.sharedData }
set { SubStruct.sharedData = newValue }
}
You can now refer the static variable as YourClass.sharedData.

Static properties in Swift

I'm trying to convert the following Objective-C code to Swift. In my Objective-C code, there's a static variable and its accessed from a class method.
#implementation SomeClass
static NSMutableArray *_items;
+ (void)someMethod {
[_items removeAll];
}
#end
Since you can't access types declared like this private var items = [AnyObject]() from class functions in Swift, I created a stored property for it like this.
class var items: [AnyObject] {
return [AnyObject]()
}
And I'm trying to call a method on it from a class function like so.
class func someFunction() {
items.removeAll(keepCapacity: false)
}
But I get this error Immutable value of type '[AnyObject]' only has mutating members named 'removeAll'.
Can anyone please tell me what's the cause of this error and how to correct it?
Thank you.
With this code:
class var items: [AnyObject] {
return [AnyObject]()
}
you are not creating a stored property - instead it's a computed property, and the worst part is that every time you access to it, a new instance of [AnyObject] is created, so whatever you add to it, it's lost as soon as its reference goes out of scope.
As for the error, the static computed property returns an immutable copy of the array that you create in its body, so you cannot use any of the array method declared as mutating - and removeAll is one of them. The reason why it is immutable is because you have defined a getter, but not a setter.
Currently Swift classes don't support static properties, but structs do - the workaround I often use is to define an inner struct:
class SomeClass {
struct Static {
static var items = [AnyObject]()
}
}
SomeClass.Static.items.append("test")
If you want to get rid of the Static struct every time you refer to the items property, just define a wrapper computed property:
class var items: [AnyObject] {
get { return Static.items }
set { Static.items = newValue }
}
so that the property can be accessed more simply as:
SomeClass.items.append("test")
Updated to Swift1.2
In Swift1.2[Xcode6.3], you can declare static properties using keyword static, also you can declare static methods using keyword class or static.
class SomeClass {
// use static modifier to declare static properties.
static var items: [AnyObject]!
// use class modifier to declare static methods.
class func classMethod() {
items.removeAll(keepCapacity: false)
}
// use static modifier to declare static methods.
static func staticMethod() {
items.removeAll(keepCapacity: false)
}
}
EDIT:
The difference between static and class modifier is that static is just an alias for "class final",so methods modified with static can not be overridden in subclasses.
Thanks #Maiaux's
Yet the manual for Swift 2 still claims just enumeration ond structures may use static store properities.

How do you make a static class in swift?

I want to create a static class in swift, is this possible? If so how?
I tried:
static class MyClass
but get the error Declaration cannot be marked 'static'
There's no static class, but you can make one by just adding static methods only.
The problem is that (as of today) classes cannot have static properties, so you have 2 options:
use a struct instead of a class, defining all its methods and properties as static
use the singleton pattern
The second option is in my opinion a better solution, unless you have specific reason for not wanting it.
static means no instance, so I would make it a struct with no initializer:
struct MyStruct {
#available(*, unavailable) private init() {}
static var foo = "foo"
static func doSomething(a: String) -> String {
return a + foo
}
}

Resources