Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Singleton Implementation: Swift

DZone's Guide to

Singleton Implementation: Swift

Ted Neward explains how to create a Singleton using Swift.

· Mobile Zone
Free Resource

Launching an app doesn’t need to be daunting. Whether you’re just getting started or need a refresher on mobile app testing best practices, this guide is your resource! Brought to you in partnership with Perfecto

Implementation: Swift

Like most languages, Swift makes it pretty straightforward to code up a classic Singleton:

import Foundation

public class Product
{
  private init() { }

  public static func Instance() -> Product {
    return instance
  }

  public static var TheInstance : Product {
    get { return instance }
  }

  public func DoSomething() {
    print("Doing something for the \(++self.state) time")
  }

  static let instance : Product = Product()
  var state = 0
}

Product.Instance().DoSomething()
Product.TheInstance.DoSomething()
Product.Instance().DoSomething()

This is an eagerly-instantiated Singleton, created whenever Swift initializes the static space for theclass; this is described here as being when the class isfirst referenced (a la how Java works). This is probably sufficient for most tasks, particularly given that(as of this writing) Swift apparently has no language-level thread-synchronization constructs.

Note that most Singletons will not have both a static property and method; this is simply here to demonstratewhat each will look like.

(NOTE: As of this writing, Swift 2.2 will generate a warning around the “++self.state” in the above, warning that“++” is deprecated and will be removed in Swift 3).

As noted earlier, Swift lacks any sort of language-level concurrency-protection mechanics, so make sure to build suchsemantics into the implementation of the Swift instance methods.

I am reasonably certain that there’s a way to help deal with subclassed Singletons using the Swift/Objective-C“class” methods, which can be overrideen (!) in subclasses. But I can’t quite figure out when/where/how to make theimplementation work offhand, nor do I really have a use-case around it yet. Not giving up on it yet, though.

Keep up with the latest DevTest Jargon with the latest Mobile DevTest Dictionary. Brought to you in partnership with Perfecto.

Topics:
swift ,mobile ,ios

Published at DZone with permission of Ted Neward, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}