How to implement a computed property like a abstract property in Swift? - ios

I know there is no abstract class and either Abstract keyword in Swift. The following problem just like implementing a abstract property.
For convenient, supposed that there are three classes as following:
class SuperClass: NSManagedObject { // the compiler will complain without 'NSManagedObject', and I don't know why.
public let superInt: Int = 1 // use superInt to represent other stored property for SuperClass.
}
class SubClass1: SuperClass {
let subInt1: Int = 2 // use 'subInt1' to represent other stored property for SubClass1.
}
class SubClass2: SuperClass {
let subInt2: Int = 3 // use 'subInt2' to represent other stored property for SubClass2.
}
protocol TestProtocol {
var count: Int { get } // a computed property
func printInt() // a custom method
}
Here, those classes are all objects defined in CoreData, especially SuperClass is a abstract Entity. I want to extend some interfaces(the TestProtocol above) for SuperClass, so that I can use polymorphism. I come up with 2 methods:
Method 1: let SuperClass confirms TestProtocol.
extension SuperClass: TestProtocol {
var count: Int { return superInt }
func printInt() { print("Here is SuperClass. Count: \(count)") }
}
extension SubClass1 {
override var count: Int { return subInt1 }
override func printInt() { print("Here is SubClass1. Count is \(count)") }
}
extension SubClass2 {
override var count: Int { return subInt2 }
override func printInt() { print("Here is SubClass2. Count is \(count)") }
}
// Here is the test code
let subClasses: [SuperClass] = [SubClass1(), SubClass2()]
subClasses.forEach { $0.printInt() }
Method 2: Convert subClasses to a protocol object.
extension SubClass1: TestProtocol {
var count: Int { return subInt1 }
func printInt() { print("Here is SubClass1. Count is \(count)") }
}
extension SubClass2: TestProtocol {
var count: Int { return subInt2 }
func printInt() { print("Here is SubClass1. Count is \(count)") }
}
// Here is the test code
let subClasses: [SuperClass] = [SubClass1(), SubClass2()]
subClasses.forEach { ($0 as! TestProtocol).printInt() }
In method 1, everything looks good. But I have to implement the code in SuperClass which is totally useless. The method seems like a little trick of grammar.
In method 2, all code is useful, but the conversion at last line broke the elegance of code. It makes me crazy continuously using code like ($0 as! TestProtocol).printInt().
I'm not satisfied with both methods. So which is recommended way or is there a better way to do it?

In your second method you actually do not need to use casting (($0 as! TestProtocol).printInt()). Here is how:
let subClasses: [TestProtocol] = [SubClass1(), SubClass2()]
subClasses.forEach { $0.printInt() }
By typing the subClasses array to TestProtocol instead of SuperClass you can remove the need for casting because the compiler now knows that every element in subClasses conforms to TestProtocol and thus, has a method printInt().

Your super class does not serve any purpose in both method 1 and method 2. In both methods you have defined, you want to eventually call printInt() which should be common to all sub classes. Notice I have highlighted "should be common". The purpose of a protocol is to specify requirements that conforming types must implement. Therefore, a protocol is sufficient to form the contract that your classes 1 and 2 should implement var count and func printInt(). Also a protocol is a type, so you do not need a super class to hold references to the other two classes as you did here:
let subClasses: [SuperClass] = [SubClass1(), SubClass2()]
In my opinion, this would be a better way:
protocol TestProtocol {
var count: Int { get } // a computed property
func printInt() // a custom method
}
Class1: TestProtocol {
var subInt = 2
var count: Int { return subInt1 }
func printInt() { print("Here is SubClass1. Count is \(count)") }
}
Class2: TestProtocol {
var subInt = 3
var count: Int { return subInt2 }
func printInt() { print("Here is SubClass2. Count is \(count)") }
}
let smallClasses: [TestProtocol] = [Class1(), Class2()]
smallClasses.forEach { $0.printInt() }
This way of doing things fulfills the Protocol Oriented way of programming in Swift, which is the favored approach. Generally speaking, inheritance and subclassing is shunned in iOS design patterns and I will direct you to this blog post so you can learn more about why https://krakendev.io/blog/subclassing-can-suck-and-heres-why
EDIT
You have clarified your question a bit more so I am going to attempt to answer it better. You are looking for the equivalent of what is an abstract class in Java which are classes that contain one or more abstract methods. An abstract method in Java is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.
Swift does not come with the same functionality but something that is functionaly equivalent would require a super class where all sub classes are forced to implement properties or methods that must be common to all sub classes. This is of course achieved by the protocol method I have shown above but you also require the ability to call properties or methods from the super class from the sub class which means each sub class must be able to cast as both the protocol type and the super class type.
Here is my solution to that written in Swift 3:
protocol TestProtocol {
var count: Int { get } // a computed property
func printInt() // a custom method
}
//base class
class SuperClass: TestProtocol {
var sharedInt: Int = 0
var subInt: Int = 1
var count: Int { return subInt }
func printInt() { print("Here is SubClass. Count is \(count)") }
}
class class1: SuperClass {
override init(){
super.init()
self.subInt = 2
}
}
class class2: SuperClass {
override init(){
super.init()
self.subInt = 3
}
}
//I can get count and printInt() which superClass, class1 and class2 share becuase of the protocol.
let smallClasses: [TestProtocol] = [SuperClass(), class1(), class2()]
smallClasses.forEach { $0.printInt() }
//I can convert the sub classes to super class type and call their printInt method
let smallClasses2: [SuperClass] = [class1(), class2()]
smallClasses2.forEach { $0.printInt() }
//I can get to the shared values the sub classes have from the super class
smallClasses2.forEach { print($0.sharedInt) }
If you copy and paste the code above into a Playground in Xcode, you will receive the following output:
Here is SubClass. Count is 1
Here is SubClass. Count is 2
Here is SubClass. Count is 3
Here is SubClass. Count is 2
Here is SubClass. Count is 3
0
0

Related

Generic class type doesn't conform to Any

I have a problem with storing my generic classes in an array. How should I format the type for my array while keeping the reference to the original type (I know I could do var myClasses: [Any] = [] but that wouldn't be helpful when retrieving the variable from my array :(
Example is below:
import UIKit
protocol Reusable { }
extension UITableViewCell: Reusable { }
extension UICollectionViewCell: Reusable { }
class SomeClass<T> where T: Reusable {
init() { }
}
var myClasses: [SomeClass<Reusable>] = []
myClasses.append(SomeClass<UITableViewCell>())
myClasses.append(SomeClass<UICollectionViewCell>())
myClasses.append(SomeClass<UITableViewCell>())
myClasses.append(SomeClass<UICollectionViewCell>())
Edit: Just to clarify, I have used the collection and table cells as an example, I am not actually planning on storing them together :)
Edit 2 var myClasses: [SomeClass<Reusable>] = [] generates error: using 'Reusable' as a concrete type conforming to protocol 'Reusable' is not supported
Edit 3 var myClasses: [SomeClass<AnyObject>] = [] generates error: type 'AnyObject' does not conform to protocol 'Reusable'
I think you can create some sort of Holder class that can accept and retrieve your object:
class Holder {
lazy var classes: [Any] = []
func get<T>(_ type: T.Type) -> [T]? {
return classes.filter({ $0 is T }) as? [T]
}
}
And the main part:
let holder = Holder()
holder.classes.append(SomeClass<UITableViewCell>())
if let someTableViewCells = holder.get(SomeClass<UITableViewCell>.self)?.first {
// or filter out again to get specific SomeClass of UITableViewCell
print(someTableViewCells)
}
Or without holder class:
var classes: [Any] = []
classes.append(SomeClass<UITableViewCell>())
if let someTableViewCell = classes.filter({ $0 is SomeClass<UITableViewCell> }).first as? SomeClass<UITableViewCell> {
print(someTableViewCell)
}
You should use array of AnyObject in your case. Because as you know swift is strong typed language and for example
SomeClass<UITableViewCell>
and
SomeClass<UICollectionViewCell>
are different types of objects. As for example Array< Int > and Array< String >, they are both arrays, but still it's a different types of objects. So in this case you'll have to use declaration:
var myClasses: [AnyObject] = []
and check type of object or typecast them every time you'll need.
if (myClasses[0] is SomeClass<UICollectionViewCell>) { do something }
or
if let cell = myClasses[0] as? SomeClass<UICollectionViewCell> { do something }
My suggestion is adding parent protocol SomeClass Container for your SomeClass generic. Then put an array of SomeClass objects inside SomeClass.
protocol Reusable { func cakePlease() }
extension UITableViewCell: Reusable {
func cakePlease() { }
}
extension UICollectionViewCell: Reusable {
func cakePlease() { }
}
protocol SomeClassContainer {
func teaPlease()
func afternoonPlease()
}
class SomeClass<T: Reusable>: SomeClassContainer {
var item: T?
init() { }
func teaPlease() { }
func afternoonPlease() {
teaPlease()
item?.cakePlease()
}
}
var myClasses = [SomeClassContainer]()
myClasses.append(SomeClass<UITableViewCell>())
myClasses.append(SomeClass<UICollectionViewCell>())
myClasses.append(SomeClass<UITableViewCell>())
myClasses.append(SomeClass<UICollectionViewCell>())
myClasses[0].teaPlease()
if let item = (myClasses[0] as? SomeClass<UITableViewCell>)?.item {
item.cakePlease()
}
for myClass in myClasses {
if let tableCell = (myClass as? SomeClass<UITableViewCell>)?.item {
tableCell.cakePlease()
} else if let collectionCell = (myClass as SomeClass<UICollectionViewCell>)?.item {
collectionCell.cakePlease()
}
}
myClasses.forEach({ $0.afternoonPlease() })
Generally the way to type your array would be to go as specific as possible whilst still covering all bases.
What I mean by this for example is storing an array of UIViewController objects, even though each will actually be a different type. You wouldn't use Any here because you really don't need to be that general.
In your case, why not use Reusable? Since all your generic classes conform to it anyway, it is as general as you can go whilst still maintaining convenience.

Enforce template to be a protocol

How do I ensure that a given template parameter is a protocol?
A GKEntity has a function called component(ofType: class) and i want to add component(ofProtocol: Protocol). It does look like this:
extension GKEntity {
func component<T: Protocol>(ofProtocol: T) -> T? {
return self.components.first() { component in
return component.conforms(to: ofProtocol)
} as? T
}
}
I want to use it in an component which holds a reference to the entity like this:
let component = self.entity?.component(ofProtocol: SpriteComponentProtocol)
but somehow i always get:
Showing All Messages
Cannot convert value of type 'SpriteComponentProtocol.Protocol' to expected argument type 'Protocol'
Update:
The idea is that i have a component for a Sprite:
protocol SpriteComponentProtocol {
var spriteNode: SKSpriteNode { get set }
}
class SpriteComponent: GKComponent {
var spriteNode: SKSpriteNode?
}
And a other component for the control:
protocol PlayerControlComponentProtocol {
var steerAngle: Double { get set }
}
class PlayerControlComponent: GKComponent, PlayerControlComponentProtocol {
var steerAngle: Double = 90.0
override func update(deltaTime seconds: TimeInterval) {
//here i do manipulate the spriteComponent.spriteNode
let comp = self.entity?.component(ofProtocol: SpriteComponentProtocol)
}
}
I want to be able to exchange the SpriteComponent at any time.
The problem with your code is that Protocol is an opaque type that describes an Obj-C protocol, so if you want to bridge SpriteComponentProtocol.self over to it, you need to mark SpriteComponentProtocol as #objc (but even if you did; you wouldn't be able to cast to T, because the returned instance isn't of type Protocol).
But that being said, you don't need to use the Obj-C Protocol type or conforms(to:) method here, you can simply use the conditional type-casting operator as? in an overload of component(ofType:) without the GKComponent constraint on T:
extension GKEntity {
func component<T>(ofType type: T.Type) -> T? {
return self.components.lazy.flatMap{ $0 as? T }.first
}
}
We're using lazy here in order to avoid evaluating all the components, and then flatMap(_:) and first in order to get the first element that's castable to T (and in the case of T being a protocol type, this gives us the first element that conforms to the protocol).
You can then simply use it like so:
protocol SpriteComponentProtocol {
var spriteNode: SKSpriteNode { get set }
}
class PlayerControlComponent: GKComponent {
override func update(deltaTime seconds: TimeInterval) {
let comp = self.entity?.component(ofType: SpriteComponentProtocol.self)
}
}
And in Swift 4, you can remove this overload entirely, and instead simply call GKEntity's component(ofType:) method with a class existential metatype:
let comp = self.entity?.component(ofType: (GKComponent & SpriteComponentProtocol).self)
As now T satisfies the : GKComponent constraint. You can then access both GKComponent methods and SpriteComponentProtocol protocol requirements on the unwrapped instance.

Custom collection in swift: is it a right way?

I am learning swift. I would like to use a custom class to be loopable [able to a for...in loop] like Array. Below is the given sample code that so far, I have tried. The class in question is "GuestManager" which is holding a private collection of guests [objects of class Guest]
import Foundation
class Guest{
var guestId: String
var guestName: String
init(gId: String, name: String){
self.guestId = gId
self.guestName = name
}
}
class GuestManager: GeneratorType, SequenceType{
private var guests = [Guest]?()
private var nextIndex: Int
init(guests: [Guest]){
self.guests = guests
self.nextIndex = 0
}
func next() -> Guest? {
if self.nextIndex > (self.guests?.count)! - 1 {
self.nextIndex = 0
return nil
}
let currentGuest = self.guests![self.nextIndex]
self.nextIndex += 1
return currentGuest
}
subscript(aGuestId gID: String) -> Guest{
return (self.guests?.filter({$0.guestId == gID}).first)!
}
}
I do not want to create separate classes that are conforming to GeneratorType & SequenceType protocols. Instead I have created a single class that is conforming to both protocols.
Below are some of my questions:
I would like to know if this a correct way to have a custom collection type ?
Can we use subscript as a way to perform a search based on a property for example "subscript(aGuestId gID: String)" in the sample code above ?
It is clear from the code for next() function implementation in above sample code that is resetting the "nextIndex" when the iteration reached at the end. How one will handle the situation wherein we use a break statement inside the for...in loop as below:
for aGuest in guestManager{//guestManager an instance of GuestManager class instantiated with several guest objects
print(aGuest.guestName)
}
for aG in guestManager{
print(aG.guestId)
break
}
In the 2nd for loop the code break out after getting the first Element [Guest object in this case]. The subsequent for loop will start at index 1 in the collection and not at 0. Is there anyway to handle this break situation so that for each subsequent for looping the index is always set to 0?
Thanks
Edit: It seems the "nextIndex" reset issue can be fixed with below code [added inside GuestManager class] for generate() method implementation
func generate() -> Self {
self.nextIndex = 0
return self
}
You should not store the nextIndex inside the class. You can use a local variable in the generate method and then let that variable be captured by the closure you pass to the generator you create in that method. That’s all you need to adopt SequenceType:
class GuestManager: SequenceType{
private var guests: [Guest]
init(guests: [Guest]) {
self.guests = guests
}
func generate() -> AnyGenerator<Guest> {
var nextIndex = 0
return AnyGenerator {
guard nextIndex < self.guests.endIndex else {
return nil
}
let next = self.guests[nextIndex]
nextIndex += 1
return next
}
}
}
For subscripting, you should adopt Indexable. Actually, the easiest way to fulfill all your requirements is to pass as much of the logic for SequenceType, Indexable, and eventually (if you want to support it) CollectionType, to your array, which already has these capabilities. I would write it like this:
class GuestManager {
private var guests: [Guest]
init(guests: [Guest]){
self.guests = guests
}
}
extension GuestManager: SequenceType {
typealias Generator = IndexingGenerator<GuestManager>
func generate() -> Generator {
return IndexingGenerator(self)
}
}
extension GuestManager: Indexable {
var startIndex: Int {
return guests.startIndex
}
var endIndex: Int {
return guests.endIndex
}
subscript(position: Int) -> Guest {
return guests[position]
}
}
Some more observations:
Your guests property should not be an optional. It makes the code more complicated, with no benefits. I changed it accordingly in my code.
Your Guest class should probably be a value type (a struct). GuestManager is also a good candidate for a struct unless you require the reference semantics of a class (all collection types in the standard library are structs).
I think the subscripting approach you're trying here is kind of convoluted. Personally, I would use a function to do this for the sake of clarity.
guestManager[aGuestId: guestId]
guestManager.guestWithID(guestId)
So stylistically I would probably land on something like this
import Foundation
class Guest{
var guestId: String
var guestName: String
init(guestId: String, guestName: String){
self.guestId = guestId
self.guestName = guestName
}
}
class GuestManager: GeneratorType, SequenceType{
private var guests: [Guest]
private var nextIndex = 0
init(guests: [Guest]){
self.guests = guests
}
func next() -> Guest? {
guard guests.count < nextIndex else {
nextIndex = 0
return nil
}
let currentGuest = guests[nextIndex]
nextIndex += 1
return currentGuest
}
func guestWithID(id: String) -> Guest? {
return guests.filter{$0.guestId == id}.first ?? nil
}
}

Make Class iterable with a for in Loop?

I have a custom class:
class MyArrayClass {
...
}
This class is a custom list implementation.
I want to do the following:
var arr:MyArrayClass = MyArrayClass()
arr.append("first")
arr.append("second")
arr.append("third")
for entry in arr {
println("entry: \(entry)")
}
Edit: The class I want to make iterable is JavaUtilArrayList it uses this class IOSObjectArray.
Which protocol must be confirmed by my class such that it works in a for in loop?
You should have a look at this blog post on this exact topic. I'll write a summary of it here though:
When you write:
// mySequence is a type that conforms to the SequenceType protocol.
for x in mySequence {
// iterations here
}
Swift converts this to:
var __g: Generator = mySequence.generate()
while let x = __g.next() {
// iterations here
}
Therefore, to be able to enumerate through your custom type you need to make your class implement the SequenceType protocol too. Looking at the SequenceType protocol below, you can see you only need to implement one method that returns an object that conform to the GeneratorType protocol (GeneratorType is covered in the blog post).
protocol SequenceType : _Sequence_Type {
typealias Generator : GeneratorType
func generate() -> Generator
}
Here's an example of how to make MyArrayClass useable in a for loop:
class MyArrayClass {
var array: [String] = []
func append(str: String) {
array.append(str)
}
}
extension MyArrayClass : SequenceType {
// IndexingGenerator conforms to the GeneratorType protocol.
func generate() -> IndexingGenerator<Array<String>> {
// Because Array already conforms to SequenceType,
// you can just return the Generator created by your array.
return array.generate()
}
}
Now to use this in practise:
let arr = MyArrayClass()
arr.append("first")
arr.append("second")
arr.append("third")
for x in arr {
println(x)
}
// Prints:
// First
// Second
// Third
I hope that answers your question.
You can make it much faster using NSFastGenerator:
extension MyArrayClass: SequenceType {
public func generate() -> NSFastGenerator {
return NSFastGenerator(self)
}
}

How to use singleton in swift? [duplicate]

I'm trying to work out an appropriate singleton model for usage in Swift. So far, I've been able to get a non-thread safe model working as:
class var sharedInstance: TPScopeManager {
get {
struct Static {
static var instance: TPScopeManager? = nil
}
if !Static.instance {
Static.instance = TPScopeManager()
}
return Static.instance!
}
}
Wrapping the singleton instance in the Static struct should allow a single instance that doesn't collide with singleton instances without complex naming schemings, and it should make things fairly private. Obviously though, this model isn't thread-safe. So I tried to add dispatch_once to the whole thing:
class var sharedInstance: TPScopeManager {
get {
struct Static {
static var instance: TPScopeManager? = nil
static var token: dispatch_once_t = 0
}
dispatch_once(Static.token) { Static.instance = TPScopeManager() }
return Static.instance!
}
}
But I get a compiler error on the dispatch_once line:
Cannot convert the expression's type 'Void' to type '()'
I've tried several different variants of the syntax, but they all seem to have the same results:
dispatch_once(Static.token, { Static.instance = TPScopeManager() })
What is the proper usage of dispatch_once using Swift? I initially thought the problem was with the block due to the () in the error message, but the more I look at it, the more I think it may be a matter of getting the dispatch_once_t correctly defined.
tl;dr: Use the class constant approach if you are using Swift 1.2 or above and the nested struct approach if you need to support earlier versions.
From my experience with Swift there are three approaches to implement the Singleton pattern that support lazy initialization and thread safety.
Class constant
class Singleton {
static let sharedInstance = Singleton()
}
This approach supports lazy initialization because Swift lazily initializes class constants (and variables), and is thread safe by the definition of let. This is now officially recommended way to instantiate a singleton.
Class constants were introduced in Swift 1.2. If you need to support an earlier version of Swift, use the nested struct approach below or a global constant.
Nested struct
class Singleton {
class var sharedInstance: Singleton {
struct Static {
static let instance: Singleton = Singleton()
}
return Static.instance
}
}
Here we are using the static constant of a nested struct as a class constant. This is a workaround for the lack of static class constants in Swift 1.1 and earlier, and still works as a workaround for the lack of static constants and variables in functions.
dispatch_once
The traditional Objective-C approach ported to Swift. I'm fairly certain there's no advantage over the nested struct approach but I'm putting it here anyway as I find the differences in syntax interesting.
class Singleton {
class var sharedInstance: Singleton {
struct Static {
static var onceToken: dispatch_once_t = 0
static var instance: Singleton? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = Singleton()
}
return Static.instance!
}
}
See this GitHub project for unit tests.
Since Apple has now clarified that static struct variables are initialized both lazy and wrapped in dispatch_once (see the note at the end of the post), I think my final solution is going to be:
class WithSingleton {
class var sharedInstance: WithSingleton {
struct Singleton {
static let instance = WithSingleton()
}
return Singleton.instance
}
}
This takes advantage of the automatic lazy, thread-safe initialization of static struct elements, safely hides the actual implementation from the consumer, keeps everything compactly compartmentalized for legibility, and eliminates a visible global variable.
Apple has clarified that lazy initializer are thread-safe, so there's no need for dispatch_once or similar protections
The lazy initializer for a global variable (also for static members of structs and enums) is run the first time that global is accessed, and is launched as dispatch_once to make sure that the initialization is atomic. This enables a cool way to use dispatch_once in your code: just declare a global variable with an initializer and mark it private.
From here
For Swift 1.2 and beyond:
class Singleton {
static let sharedInstance = Singleton()
}
With a proof of correctness (all credit goes here), there is little to no reason now to use any of the previous methods for singletons.
Update: This is now the official way to define singletons as described in the official docs!
As for concerns on using static vs class. static should be the one to use even when class variables become available. Singletons are not meant to be subclassed since that would result in multiple instances of the base singleton. Using static enforces this in a beautiful, Swifty way.
For Swift 1.0 and 1.1:
With the recent changes in Swift, mostly new access control methods, I am now leaning towards the cleaner way of using a global variable for singletons.
private let _singletonInstance = SingletonClass()
class SingletonClass {
class var sharedInstance: SingletonClass {
return _singletonInstance
}
}
As mentioned in the Swift blog article here:
The lazy initializer for a global variable (also for static members of
structs and enums) is run the first time that global is accessed, and
is launched as dispatch_once to make sure that the initialization is
atomic. This enables a cool way to use dispatch_once in your code:
just declare a global variable with an initializer and mark it
private.
This way of creating a singleton is thread safe, fast, lazy, and also bridged to ObjC for free.
Swift 1.2 or later now supports static variables/constants in classes. So you can just use a static constant:
class MySingleton {
static let sharedMySingleton = MySingleton()
private init() {
// ...
}
}
There is a better way to do it. You can declare a global variable in your class above the class declaration like this:
var tpScopeManagerSharedInstance = TPScopeManager()
This just calls your default init or whichever init and global variables are dispatch_once by default in Swift. Then in whichever class you want to get a reference, you just do this:
var refrence = tpScopeManagerSharedInstance
// or you can just access properties and call methods directly
tpScopeManagerSharedInstance.someMethod()
So basically you can get rid of the entire block of shared instance code.
Swift singletons are exposed in the Cocoa frameworks as class functions, e.g. NSFileManager.defaultManager(), NSNotificationCenter.defaultCenter(). So it makes more sense as a class function to mirror this behavior, rather than a class variable as some other solutions. e.g:
class MyClass {
private static let _sharedInstance = MyClass()
class func sharedInstance() -> MyClass {
return _sharedInstance
}
}
Retrieve the singleton via MyClass.sharedInstance().
Per the Apple documentation, it has been repeated many times that the easiest way to do this in Swift is with a static type property:
class Singleton {
static let sharedInstance = Singleton()
}
However, if you're looking for a way to perform additional setup beyond a simple constructor call, the secret is to use an immediately invoked closure:
class Singleton {
static let sharedInstance: Singleton = {
let instance = Singleton()
// setup code
return instance
}()
}
This is guaranteed to be thread-safe and lazily initialized only once.
Swift 4+
protocol Singleton: class {
static var sharedInstance: Self { get }
}
final class Kraken: Singleton {
static let sharedInstance = Kraken()
private init() {}
}
Looking at Apple's sample code I came across this pattern. I'm not sure how Swift deals with statics, but this would be thread safe in C#. I include both the property and method for Objective-C interop.
struct StaticRank {
static let shared = RankMapping()
}
class func sharedInstance() -> RankMapping {
return StaticRank.shared
}
class var shared:RankMapping {
return StaticRank.shared
}
In brief,
class Manager {
static let sharedInstance = Manager()
private init() {}
}
You may want to read Files and Initialization
The lazy initializer for a global variable (also for static members of
structs and enums) is run the first time that global is accessed, and
is launched as dispatch_once to make sure that the initialization is
atomic.
If you are planning on using your Swift singleton class in Objective-C, this setup will have the compiler generate appropriate Objective-C-like header(s):
class func sharedStore() -> ImageStore {
struct Static {
static let instance : ImageStore = ImageStore()
}
return Static.instance
}
Then in Objective-C class you can call your singleton the way you did it in pre-Swift days:
[ImageStore sharedStore];
This is just my simple implementation.
First solution
let SocketManager = SocketManagerSingleton();
class SocketManagerSingleton {
}
Later in your code:
func someFunction() {
var socketManager = SocketManager
}
Second solution
func SocketManager() -> SocketManagerSingleton {
return _SocketManager
}
let _SocketManager = SocketManagerSingleton();
class SocketManagerSingleton {
}
And later in your code you will be able to keep braces for less confusion:
func someFunction() {
var socketManager = SocketManager()
}
final class MySingleton {
private init() {}
static let shared = MySingleton()
}
Then call it;
let shared = MySingleton.shared
Use:
class UtilSingleton: NSObject {
var iVal: Int = 0
class var shareInstance: UtilSingleton {
get {
struct Static {
static var instance: UtilSingleton? = nil
static var token: dispatch_once_t = 0
}
dispatch_once(&Static.token, {
Static.instance = UtilSingleton()
})
return Static.instance!
}
}
}
How to use:
UtilSingleton.shareInstance.iVal++
println("singleton new iVal = \(UtilSingleton.shareInstance.iVal)")
The best approach in Swift above 1.2 is a one-line singleton, as -
class Shared: NSObject {
static let sharedInstance = Shared()
private override init() { }
}
To know more detail about this approach you can visit this link.
From Apple Docs (Swift 3.0.1),
You can simply use a static type property, which is guaranteed to be
lazily initialized only once, even when accessed across multiple
threads simultaneously:
class Singleton {
static let sharedInstance = Singleton()
}
If you need to perform additional setup beyond initialization, you can
assign the result of the invocation of a closure to the global
constant:
class Singleton {
static let sharedInstance: Singleton = {
let instance = Singleton()
// setup code
return instance
}()
}
I would suggest an enum, as you would use in Java, e.g.
enum SharedTPScopeManager: TPScopeManager {
case Singleton
}
Just for reference, here is an example Singleton implementation of Jack Wu/hpique's Nested Struct implementation. The implementation also shows how archiving could work, as well as some accompanying functions. I couldn't find this complete of an example, so hopefully this helps somebody!
import Foundation
class ItemStore: NSObject {
class var sharedStore : ItemStore {
struct Singleton {
// lazily initiated, thread-safe from "let"
static let instance = ItemStore()
}
return Singleton.instance
}
var _privateItems = Item[]()
// The allItems property can't be changed by other objects
var allItems: Item[] {
return _privateItems
}
init() {
super.init()
let path = itemArchivePath
// Returns "nil" if there is no file at the path
let unarchivedItems : AnyObject! = NSKeyedUnarchiver.unarchiveObjectWithFile(path)
// If there were archived items saved, set _privateItems for the shared store equal to that
if unarchivedItems {
_privateItems = unarchivedItems as Array<Item>
}
delayOnMainQueueFor(numberOfSeconds: 0.1, action: {
assert(self === ItemStore.sharedStore, "Only one instance of ItemStore allowed!")
})
}
func createItem() -> Item {
let item = Item.randomItem()
_privateItems.append(item)
return item
}
func removeItem(item: Item) {
for (index, element) in enumerate(_privateItems) {
if element === item {
_privateItems.removeAtIndex(index)
// Delete an items image from the image store when the item is
// getting deleted
ImageStore.sharedStore.deleteImageForKey(item.itemKey)
}
}
}
func moveItemAtIndex(fromIndex: Int, toIndex: Int) {
_privateItems.moveObjectAtIndex(fromIndex, toIndex: toIndex)
}
var itemArchivePath: String {
// Create a filepath for archiving
let documentDirectories = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
// Get the one document directory from that list
let documentDirectory = documentDirectories[0] as String
// append with the items.archive file name, then return
return documentDirectory.stringByAppendingPathComponent("items.archive")
}
func saveChanges() -> Bool {
let path = itemArchivePath
// Return "true" on success
return NSKeyedArchiver.archiveRootObject(_privateItems, toFile: path)
}
}
And if you didn't recognize some of those functions, here is a little living Swift utility file I've been using:
import Foundation
import UIKit
typealias completionBlock = () -> ()
extension Array {
func contains(#object:AnyObject) -> Bool {
return self.bridgeToObjectiveC().containsObject(object)
}
func indexOf(#object:AnyObject) -> Int {
return self.bridgeToObjectiveC().indexOfObject(object)
}
mutating func moveObjectAtIndex(fromIndex: Int, toIndex: Int) {
if ((fromIndex == toIndex) || (fromIndex > self.count) ||
(toIndex > self.count)) {
return
}
// Get object being moved so it can be re-inserted
let object = self[fromIndex]
// Remove object from array
self.removeAtIndex(fromIndex)
// Insert object in array at new location
self.insert(object, atIndex: toIndex)
}
}
func delayOnMainQueueFor(numberOfSeconds delay:Double, action closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue()) {
closure()
}
}
In swift, you can create a singleton class following way:
class AppSingleton: NSObject {
//Shared instance of class
static let sharedInstance = AppSingleton()
override init() {
super.init()
}
}
I prefer this implementation:
class APIClient {
}
var sharedAPIClient: APIClient = {
return APIClient()
}()
extension APIClient {
class func sharedClient() -> APIClient {
return sharedAPIClient
}
}
My way of implementation in Swift...
ConfigurationManager.swift
import Foundation
let ConfigurationManagerSharedInstance = ConfigurationManager()
class ConfigurationManager : NSObject {
var globalDic: NSMutableDictionary = NSMutableDictionary()
class var sharedInstance:ConfigurationManager {
return ConfigurationManagerSharedInstance
}
init() {
super.init()
println ("Config Init been Initiated, this will be called only onece irrespective of many calls")
}
Access the globalDic from any screen of the application by the below.
Read:
println(ConfigurationManager.sharedInstance.globalDic)
Write:
ConfigurationManager.sharedInstance.globalDic = tmpDic // tmpDict is any value that to be shared among the application
The only right approach is below.
final class Singleton {
static let sharedInstance: Singleton = {
let instance = Singleton()
// setup code if anything
return instance
}()
private init() {}
}
To Access
let signleton = Singleton.sharedInstance
Reasons:
static type property is guaranteed to be lazily initialized only once, even when accessed across multiple threads simultaneously, so no need of using dispatch_once
Privatising the init method so instance can't be created by other classes.
final class as you do not want other classes to inherit Singleton class.
After seeing David's implementation, it seems like there is no need to have a singleton class function instanceMethod since let is doing pretty much the same thing as a sharedInstance class method. All you need to do is declare it as a global constant and that would be it.
let gScopeManagerSharedInstance = ScopeManager()
class ScopeManager {
// No need for a class method to return the shared instance. Use the gScopeManagerSharedInstance directly.
}
func init() -> ClassA {
struct Static {
static var onceToken : dispatch_once_t = 0
static var instance : ClassA? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = ClassA()
}
return Static.instance!
}
Swift to realize singleton in the past, is nothing more than the three ways: global variables, internal variables and dispatch_once ways.
Here are two good singleton.(note: no matter what kind of writing will must pay attention to the init () method of privatisation.Because in Swift, all the object's constructor default is public, needs to be rewritten init can be turned into private, prevent other objects of this class '()' by default initialization method to create the object.)
Method 1:
class AppManager {
private static let _sharedInstance = AppManager()
class func getSharedInstance() -> AppManager {
return _sharedInstance
}
private init() {} // Privatizing the init method
}
// How to use?
AppManager.getSharedInstance()
Method 2:
class AppManager {
static let sharedInstance = AppManager()
private init() {} // Privatizing the init method
}
// How to use?
AppManager.sharedInstance
Swift 5.2
You can point to the type with Self. So:
static let shared = Self()
And should be inside a type, like:
class SomeTypeWithASingletonInstance {
static let shared = Self()
}
This is the simplest one with thread safe capabilities. No other thread can access the same singleton object even if they want. Swift 3/4
struct DataService {
private static var _instance : DataService?
private init() {} //cannot initialise from outer class
public static var instance : DataService {
get {
if _instance == nil {
DispatchQueue.global().sync(flags: .barrier) {
if _instance == nil {
_instance = DataService()
}
}
}
return _instance!
}
}
}
I required my singleton to allow inheritance, and none of these solutions actually allowed it. So I came up with this:
public class Singleton {
private static var sharedInstanceVar = Singleton()
public class func sharedInstance() -> Singleton {
return sharedInstanceVar
}
}
public class SubSingleton: Singleton {
private static var sharedInstanceToken: dispatch_once_t = 0
public class override func sharedInstance() -> SubSingleton {
dispatch_once(&sharedInstanceToken) {
sharedInstanceVar = SubSingleton()
}
return sharedInstanceVar as! SubSingleton
}
}
This way when doing Singleton.sharedInstance() first it will return the instance of Singleton
When doing SubSingleton.sharedInstance() first it will return the instance of SubSingleton created.
If the above is done, then SubSingleton.sharedInstance() is Singleton is true and the same instance is used.
The issue with this first dirty approach is that I cannot guarantee that subclasses would implement the dispatch_once_t and make sure that sharedInstanceVar is only modified once per class.
I will try to refine this further, but it would be interesting to see if anyone has strong feelings against this (besides the fact that it is verbose and requires to manually update it).
This is my implementation. It also prevents the programmer from creating a new instance:
let TEST = Test()
class Test {
private init() {
// This is a private (!) constructor
}
}
I use the following syntax:
public final class Singleton {
private class func sharedInstance() -> Singleton {
struct Static {
//Singleton instance.
static let sharedInstance = Singleton()
}
return Static.sharedInstance
}
private init() { }
class var instance: Singleton {
return sharedInstance()
}
}
This works from Swift 1.2 up to 4, and has several advantages:
Reminds the user not to subclass implementation
Prevents creation of additional instances
Ensures lazy creation and unique instantiation
Shortens syntax (avoids ()) by allowing to access instance as Singleton.instance

Resources