I've toyed around with Swift Playground and noticed the following issue:
The code below describes a series of object connected to one another in the following way:
objectC --> ObjectB -- weak ref to another C --> another C --> Object B etc..
Each objectC consists of
- a ref to a object B
- a weak ref to a delegate => this one becomes nil!!
Each objectB consists of
- A var integer
- A weak ref to another object C
The code does the following:
objectC call a function, say run(), which will evaluate (objectB.weak_ref_to_another_C), and call objectB.weak_ref_to_another_C.run() in a serial Queue.
After calling .run() a couple of times, C's delegate mysteriously becomes nil....
Any idea what I'm doing wrong? To start the code, simply call test_recursive_serial() on Swift Playground.
let serialQueue = DispatchQueue(label: "myQueue");
public protocol my_protocol:class {
func do_something(ofValue:Int,completion:((Int) -> Void))
}
public class classA:my_protocol {
public let some_value:Int;
public init(value:Int){
self.some_value = value;
}
public func do_something(ofValue:Int,completion:((Int) -> Void)) {
print("A:\(some_value) in current thread \(Thread.current) is executing \(Thread.current.isExecuting)");
if self.some_value == ofValue {
completion(ofValue);
}
}
}
public class classB {
public weak var jump_to_C:classC?;
public var value:Int = 0;
}
public class classC {
weak var delegate:my_protocol?{
willSet {
if (newValue == nil) { print("target set to nil") }
else { print("target set to delegate") }
}
}
var someB:classB?
public func do_something_else() {
print(self.delegate!)
}
public func do_another(withValue:Int,completion:((Int) -> Void)) {
}
public func run(completion:#escaping ((Int) -> Void)) {
print("\(self.someB?.value)");
assert(self.delegate != nil, "not here");
if let obj = someB?.jump_to_C, obj !== self {
someB?.value += 1;
print("\(someB!)")
usleep(10000);
if let value = someB?.value, value > 100 {
completion(someB!.value);
} else {
serialQueue.async {
print("lauching...")
obj.run(completion: completion);
}
}
}else{
print("pointing to self or nil...\(someB)")
}
}
}
public func test_recursive_serial() {
let my_a = classA(value:100);
let arrayC:[classC] = (0..<10).map { (i) -> classC in
let c = classC();
c.delegate = my_a;
return c;
}
let arrayB:[classB] = (0..<10).map { (i) -> classB in
let b = classB();
let ii = (i + 1 >= 10) ? 0 : i + 1;
b.jump_to_C = arrayC[ii]
return b;
}
arrayC.forEach { (cc) in
cc.someB = arrayB[Int(arc4random())%arrayB.count];
}
arrayC.first!.run() { (value) in
print("done!");
}
}
Important note: if test_recursive_serial() content is directly called from the playground, that is not through a function, the problem doesn't appear.
Edit: You'll need to add 'PlaygroundPage.current.needsIndefiniteExecution = true' to the playground code.
Edit: Ok, I feel I need to add this. Big mistake on my side, test_recursive_serial() doesn't keep a reference on any of the called objects, so obviously, they all become nil after the code leaves the function. Hence the problem. Thanks to Guy Kogus for pointing that out.
Final edit: Adding this, in the hope it might help. Swift playground are great to test-drive code, but can sometime become very busy. Within the current issue, the solution requires to set the variables first, and then pass them to test_recursive_serial() which in turn adds to the chatty appearance of the playground. Here's another option to keep your code tidy and self-contained, while dealing with async functions of various flavours...
If you have an async task - one that doesn't fit into URL fetch -, say:
myObject.myNonBlockingTask(){ print("I'm done!"}
First, include XCTest at the top of your file.
import XCTest
then add the following:
func waitForNotificationNamed(_ notificationName: String,timeout:TimeInterval = 5.0) -> Bool {
let expectation = XCTNSNotificationExpectation(name: notificationName)
let result = XCTWaiter().wait(for: [expectation], timeout: timeout)
return result == .completed
}
finally, change your completion block to:
myObject.myNonBlockingTask(){
print("I'm done!")
let name = NSNotification.Name(rawValue: "foobar");
NotificationCenter.default.post(name:name , object: nil)
}
XCTAssert(waitForNotificationNamed("foobar", timeout: 90));
the full playground code will look like:
public func my_function() {
let somevar:Int = 123
let myObject = MyClass(somevar);
myObject.myNonBlockingTask(){
print("I'm done!")
let name = NSNotification.Name(rawValue: "foobar");
NotificationCenter.default.post(name:name , object: nil)
}
XCTAssert(waitForNotificationNamed("foobar", timeout: 90));
}
Playground will wait on the notification before going any further, and also generate an exception if it times out. All locally created objects will remain valid until the execution completes.
Hope this helps.
The main issue is that you're testing this in Playgrounds, which doesn't necessarily play nicely with multithreading. Following from this SO question, change the test_recursive_serial function to:
arrayC.first!.run() { (value) in
print("done! \(value)")
XCPlaygroundPage.currentPage.needsIndefiniteExecution = false
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
while XCPlaygroundPage.currentPage.needsIndefiniteExecution {
}
(You'll need to add import XCPlayground at the top of the code to make it work.)
If you don't add that code change, then my_a is released after you leave that function, which is why delegate becomes nil on the second call to run.
I also found that in run, if you don't call the completion closure in the else case like so:
public func run(completion:#escaping ((Int) -> Void)) {
...
if let obj = someB?.jump_to_C, obj !== self {
...
}else{
print("pointing to self or nil...\(someB)")
completion(-1) // Added fallback
}
}
Then the program gets stuck. By adding that it runs to the end, although I haven't actually worked out why.
Also, please get rid of all your ;s, this isn't Objective-C 😜
Related
I would like to test if my init function works as expected. There is an async call in the init within a Task {} block. How can I make my test wait for the result of the Task block?
class ViewModel: ObservableObject {
#Published private(set) var result: [Item]
init(fetching: RemoteFetching) {
self.result = []
Task {
do {
let result = try await fetching.fetch()
self.result = result // <- need to do something with #MainActor?
} catch {
print(error)
}
}
}
}
Test:
func testFetching() async {
let items = [Item(), Item()]
let fakeFetching = FakeFetching(returnValue: items)
let vm = ViewModel(fetching: FakeFetching())
XCTAssertEqual(vm.result, [])
// wait for fetching, but how?
XCTAssertEqual(vm.result, items])
}
I tried this, but setting the items, only happens after the XCTWaiter. The compiler warns that XCTWaiter cannot be called with await, because it isn't async.
func testFetching() async {
let items = [Item(), Item()]
let fakeFetching = FakeFetching(returnValue: items)
let expectation = XCTestExpectation()
let vm = ViewModel(fetching: FakeFetching())
XCTAssertEqual(vm.result, [])
vm.$items
.dropFirst()
.sink { value in
XCTAssertEqual(value, items)
expectation.fulfill()
}
.store(in: &cancellables)
let result = await XCTWaiter.wait(for: [expectation], timeout: 1)
XCTAssertEqual(result, .completed)
}
Expectation-and-wait is correct. You're just using it wrong.
You are way overthinking this. You don't need an async test method. You don't need to call fulfill yourself. You don't need a Combine chain. Simply use a predicate expectation to wait until vm.result is set.
Basically the rule is this: Testing an async method requires an async test method. But testing the asynchronous "result" of a method that happens to make an asynchronous call, like your init method, simply requires good old-fashioned expectation-and-wait test.
I'll give an example. Here's a reduced version of your code; the structure is essentially the same as what you're doing:
protocol Fetching {
func fetch() async -> String
}
class MyClass {
var result = ""
init(fetcher: Fetching) {
Task {
self.result = await fetcher.fetch()
}
}
}
Okay then, here's how to test it:
final class MockFetcher: Fetching {
func fetch() async -> String { "howdy" }
}
final class MyLibraryTests: XCTestCase {
let fetcher = MockFetcher()
func testMyClassInit() {
let subject = MyClass(fetcher: fetcher)
let expectation = XCTNSPredicateExpectation(
predicate: NSPredicate(block: { _, _ in
subject.result == "howdy"
}), object: nil
)
wait(for: [expectation], timeout: 2)
}
}
Extra for experts: A Bool predicate expectation is such a common thing to use, that it will be found useful to have on hand a convenience method that combines the expectation, the predicate, and the wait into a single package:
extension XCTestCase {
func wait(
_ condition: #escaping #autoclosure () -> (Bool),
timeout: TimeInterval = 10)
{
wait(for: [XCTNSPredicateExpectation(
predicate: NSPredicate(block: { _, _ in condition() }), object: nil
)], timeout: timeout)
}
}
The outcome is that, for example, the above test code can be reduced to this:
func testMyClassInit() {
let subject = MyClass(fetcher: fetcher)
wait(subject.result == "howdy")
}
Convenient indeed. In my own code, I often add an explicit assert, even when it is completely redundant, just to make it perfectly clear what I'm claiming my code does:
func testMyClassInit() {
let subject = MyClass(fetcher: fetcher)
wait(subject.result == "howdy")
XCTAssertEqual(subject.result, "howdy") // redundant but nice
}
Tnx to matt this is the correct way. No need for async in the test function and just using a predicate did the job.
func testFetching() {
let items = [Item(), Item()]
let fakeFetching = FakeFetching(returnValue: items)
let expectation = XCTestExpectation()
let vm = ViewModel(fetching: FakeFetching())
let pred = NSPredicate { _, _ in
vm.items == items
}
let expectation = XCTNSPredicateExpectation(predicate: pred, object: vm)
wait(for: [expectation], timeout: 1)
}
Slight variation on Matt's excellent answer. In my case, I've broken out his extension method into even more granular extensions for additional convenience.
Helper Framework
public typealias Predicate = () -> Bool
public extension NSPredicate {
convenience init(predicate: #escaping #autoclosure Predicate) {
self.init{ _, _ in predicate() }
}
}
public extension XCTNSPredicateExpectation {
convenience init(predicate: #escaping #autoclosure Predicate, object: Any) {
self.init(predicate: NSPredicate(predicate: predicate()), object: object)
}
convenience init(predicate: #escaping #autoclosure Predicate) {
self.init(predicate: NSPredicate(predicate: predicate()))
}
convenience init(predicate: NSPredicate) {
self.init(predicate: predicate, object: nil)
}
}
public extension XCTestCase {
func XCTWait(for condition: #escaping #autoclosure Predicate, timeout: TimeInterval = 10) {
let expectation = XCTNSPredicateExpectation(predicate: condition())
wait(for: [expectation], timeout: timeout)
}
}
With the above in place, the OP's code can be reduced to this...
Unit Test
func testFetching() {
let items = [Item(), Item()]
let fakeFetching = FakeFetching(returnValue: items)
let vm = ViewModel(fetching: FakeFetching())
XCTWait(for: vm.items == items, timeout: 1)
}
Notes on Naming
Above, I'm using a somewhat controversial name in calling my function XCTWait. This is because the XCT prefix should be considered reserved for Apple's XCTest framework. However, the decision to name it this way stems from the desire to improve its discoverability. By naming it as such, when a developer types XCT In their code editor, XCTWait is now presented as one of the offered auto-complete entries** making finding and using much more likely.
However, some purists may frown on this approach, citing if Apple ever added something named similar, this code may suddenly break/stop working (although unlikely unless the signatures also matched.)
As such, use such namings at your own discretion. Alternately, simply rename it to something you prefer/that meets your own naming standards.
(** Provided it is in the same project or in a library/package they've imported somewhere above)
I write unit test in Swift.
I call my app method and through delegate get back JSON object that represents request.
Now I want to validate all fields of JSON. Each validation should be in separate test.
This is what I wrote:
class LaunchTests: XCTestCase, TestServerHandlerDelegate {
var theExpectation:XCTestExpectation?
var launchRequest:String? = nil
public func onSend(_ data: Data!) {
launchRequest = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
theExpectation?.fulfill()
}
override func setUp() {
super.setUp()
// we wait in setUp till get 'launchRequest'
if launchRequest == nil {
theExpectation = expectation(description: "initialized")
MyApp.shared().setDelegate(self)
MyApp.shared().launch()
// Loop until the expectation is fulfilled in onDone method
waitForExpectations(timeout: 500, handler: { error in XCTAssertNil(error, "Oh, we got timeout")})
}
}
override func tearDown() {
super.tearDown()
}
func test___01_platform(){
if let _ = fetchJsonValue(key: "somekey", value: launchRequest){
//...
}
}
func test___02_platform(){
if let _ = fetchJsonValue(key: "platform", value: launchRequest){
//...
}
}
The problem is: for each run launchRequest is nil. I know that its right behavior but I want to call MyApp.shared().launch() once only and run multiple tests for launchRequest data.
How can I achieve it?
(I know its not good practice for unit testing but anyways)
Thanks,
Well, if you really want that, you can just put launchRequest outside of your LaunchTests class:
var launchRequest:String? = nil
class LaunchTests: XCTestCase, TestServerHandlerDelegate {
...
}
The solution was to define launchRequest as static (as Maxim Shoustin mentioned):
static var launchRequest:String? = nil
In this case everything works as expected
What is the new syntax for dispatch_once in Swift after the changes made in language version 3? The old version was as follows.
var token: dispatch_once_t = 0
func test() {
dispatch_once(&token) {
}
}
These are the changes to libdispatch that were made.
While using lazy initialized globals can make sense for some one time initialization, it doesn't make sense for other types. It makes a lot of sense to use lazy initialized globals for things like singletons, it doesn't make a lot of sense for things like guarding a swizzle setup.
Here is a Swift 3 style implementation of dispatch_once:
public extension DispatchQueue {
private static var _onceTracker = [String]()
/**
Executes a block of code, associated with a unique token, only once. The code is thread safe and will
only execute the code once even in the presence of multithreaded calls.
- parameter token: A unique reverse DNS style name such as com.vectorform.<name> or a GUID
- parameter block: Block to execute once
*/
public class func once(token: String, block:#noescape(Void)->Void) {
objc_sync_enter(self); defer { objc_sync_exit(self) }
if _onceTracker.contains(token) {
return
}
_onceTracker.append(token)
block()
}
}
Here is an example usage:
DispatchQueue.once(token: "com.vectorform.test") {
print( "Do This Once!" )
}
or using a UUID
private let _onceToken = NSUUID().uuidString
DispatchQueue.once(token: _onceToken) {
print( "Do This Once!" )
}
As we are currently in a time of transition from swift 2 to 3, here is an example swift 2 implementation:
public class Dispatch
{
private static var _onceTokenTracker = [String]()
/**
Executes a block of code, associated with a unique token, only once. The code is thread safe and will
only execute the code once even in the presence of multithreaded calls.
- parameter token: A unique reverse DNS style name such as com.vectorform.<name> or a GUID
- parameter block: Block to execute once
*/
public class func once(token token: String, #noescape block:dispatch_block_t) {
objc_sync_enter(self); defer { objc_sync_exit(self) }
if _onceTokenTracker.contains(token) {
return
}
_onceTokenTracker.append(token)
block()
}
}
From the doc:
Dispatch
The free function dispatch_once is no longer available in
Swift. In Swift, you can use lazily initialized globals or static
properties and get the same thread-safety and called-once guarantees
as dispatch_once provided. Example:
let myGlobal: () = { … global contains initialization in a call to a closure … }()
_ = myGlobal // using myGlobal will invoke the initialization code only the first time it is used.
Expanding on Tod Cunningham's answer above, I've added another method which makes the token automatically from file, function, and line.
public extension DispatchQueue {
private static var _onceTracker = [String]()
public class func once(
file: String = #file,
function: String = #function,
line: Int = #line,
block: () -> Void
) {
let token = "\(file):\(function):\(line)"
once(token: token, block: block)
}
/**
Executes a block of code, associated with a unique token, only once. The code is thread safe and will
only execute the code once even in the presence of multithreaded calls.
- parameter token: A unique reverse DNS style name such as com.vectorform.<name> or a GUID
- parameter block: Block to execute once
*/
public class func once(
token: String,
block: () -> Void
) {
objc_sync_enter(self)
defer { objc_sync_exit(self) }
guard !_onceTracker.contains(token) else { return }
_onceTracker.append(token)
block()
}
}
So it can be simpler to call:
DispatchQueue.once {
setupUI()
}
and you can still specify a token if you wish:
DispatchQueue.once(token: "com.hostname.project") {
setupUI()
}
I suppose you could get a collision if you have the same file in two modules. Too bad there isn't #module
Edit
#Frizlab's answer - this solution is not guaranteed to be thread-safe. An alternative should be used if this is crucial
Simple solution is
lazy var dispatchOnce : Void = { // or anyName I choose
self.title = "Hello Lazy Guy"
return
}()
used like
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
_ = dispatchOnce
}
You can declare a top-level variable function like this:
private var doOnce: ()->() = {
/* do some work only once per instance */
return {}
}()
then call this anywhere:
doOnce()
You can still use it if you add a bridging header:
typedef dispatch_once_t mxcl_dispatch_once_t;
void mxcl_dispatch_once(mxcl_dispatch_once_t *predicate, dispatch_block_t block);
Then in a .m somewhere:
void mxcl_dispatch_once(mxcl_dispatch_once_t *predicate, dispatch_block_t block) {
dispatch_once(predicate, block);
}
You should now be able to use mxcl_dispatch_once from Swift.
Mostly you should use what Apple suggest instead, but I had some legitimate uses where I needed to dispatch_once with a single token in two functions and there is not covered by what Apple provide instead.
Swift 3: For those who likes reusable classes (or structures):
public final class /* struct */ DispatchOnce {
private var lock: OSSpinLock = OS_SPINLOCK_INIT
private var isInitialized = false
public /* mutating */ func perform(block: (Void) -> Void) {
OSSpinLockLock(&lock)
if !isInitialized {
block()
isInitialized = true
}
OSSpinLockUnlock(&lock)
}
}
Usage:
class MyViewController: UIViewController {
private let /* var */ setUpOnce = DispatchOnce()
override func viewWillAppear() {
super.viewWillAppear()
setUpOnce.perform {
// Do some work here
// ...
}
}
}
Update (28 April 2017): OSSpinLock replaced with os_unfair_lock due deprecation warnings in macOS SDK 10.12.
public final class /* struct */ DispatchOnce {
private var lock = os_unfair_lock()
private var isInitialized = false
public /* mutating */ func perform(block: (Void) -> Void) {
os_unfair_lock_lock(&lock)
if !isInitialized {
block()
isInitialized = true
}
os_unfair_lock_unlock(&lock)
}
}
I improve above answers get result:
import Foundation
extension DispatchQueue {
private static var _onceTracker = [AnyHashable]()
///only excute once in same file&&func&&line
public class func onceInLocation(file: String = #file,
function: String = #function,
line: Int = #line,
block: () -> Void) {
let token = "\(file):\(function):\(line)"
once(token: token, block: block)
}
///only excute once in same Variable
public class func onceInVariable(variable:NSObject, block: () -> Void){
once(token: variable.rawPointer, block: block)
}
/**
Executes a block of code, associated with a unique token, only once. The code is thread safe and will
only execute the code once even in the presence of multithreaded calls.
- parameter token: A unique reverse DNS style name such as com.vectorform.<name> or a GUID
- parameter block: Block to execute once
*/
public class func once(token: AnyHashable,block: () -> Void) {
objc_sync_enter(self)
defer { objc_sync_exit(self) }
guard !_onceTracker.contains(token) else { return }
_onceTracker.append(token)
block()
}
}
extension NSObject {
public var rawPointer:UnsafeMutableRawPointer? {
get {
Unmanaged.passUnretained(self).toOpaque()
}
}
}
import UIKit
// dispatch once
class StaticOnceTest {
static let test2 = {
print("Test " + $0 + " \($1)")
}("mediaHSL", 5)
lazy var closure: () = {
test(entryPoint: $0, videos: $1)
}("see all" , 4)
private func test(entryPoint: String, videos: Int) {
print("Test " + entryPoint + " \(videos)")
}
}
print("Test-1")
let a = StaticOnceTest()
a.closure
a.closure
a.closure
a.closure
StaticOnceTest.test2
StaticOnceTest.test2
StaticOnceTest.test2
StaticOnceTest.test2
OUTPUT:
Test-1
Test see all 4
Test mediaHSL 5
You can use a lazy var closure and execute it immediately with (#arguments_if_needed) so that it will call only one time. You can call any instance function inside of the closure [advantage].
You can pass multiple arguments based on need. You can capture those arguments when the class has been initialised and use them.
Another option: You can use a static let closure and it will execute only one time but you cannot call any instance func inside that static let clsoure. [disadvantage]
thanks!
Swift 5
dispatch_once is still available in libswiftFoundation.dylib standard library which is embedded to any swift app so you can access to exported symbols dynamically, get the function's symbol pointer, cast and call:
import Darwin
typealias DispatchOnce = #convention(c) (
_ predicate: UnsafePointer<UInt>?,
_ block: () -> Void
) -> Void
func dispatchOnce(_ predicate: UnsafePointer<UInt>?, _ block: () -> Void) {
let RTLD_DEFAULT = UnsafeMutableRawPointer(bitPattern: -2)
if let sym = dlsym(RTLD_DEFAULT, "dispatch_once") {
let f = unsafeBitCast(sym, to: DispatchOnce.self)
f(predicate, block)
}
else {
fatalError("Symbol not found")
}
}
Example:
var token: UInt = 0
for i in 0...10 {
print("iteration: \(i)")
dispatchOnce(&token) {
print("This is printed only on the first call")
}
}
Outputs:
iteration: 0
This is printed only on the first call
iteration: 1
iteration: 2
iteration: 3
iteration: 4
iteration: 5
iteration: 6
iteration: 7
iteration: 8
iteration: 9
iteration: 10
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.
An exploration of the Singleton pattern in Swift. All approaches below support lazy initialization and thread safety.
dispatch_once approach is not worked in Swift 3.0
Approach A: Class constant
class SingletonA {
static let sharedInstance = SingletonA()
init() {
println("AAA");
}
}
Approach B: Nested struct
class SingletonB {
class var sharedInstance: SingletonB {
struct Static {
static let instance: SingletonB = SingletonB()
}
return Static.instance
}
}
Approach C: dispatch_once
class SingletonC {
class var sharedInstance: SingletonC {
struct Static {
static var onceToken: dispatch_once_t = 0
static var instance: SingletonC? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = SingletonC()
}
return Static.instance!
}
}
I have a simple tree structure in memory based on an XML document and I am trying to write a recursive generator to support SequenceType, but I am stuck on how to actually do this.
Here was my first attempt:
#objc public class XMLNode: NSObject, SequenceType {
public weak var parentNode: XMLNode?
public var nodeName: String
public var attributes: [String: String]
public var childNodes = [XMLNode]()
public func generate() -> AnyGenerator<XMLNode> {
var childGenerator = childNodes.generate()
var returnedSelf = false
return anyGenerator {
let child = childGenerator.next()
if child != nil {
// I need to somehow recurse on child here
return child
} else if !returnedSelf {
returnedSelf = true
return self
} else {
return nil
}
}
}
}
Since childNodes is an array, I'm calling its own built-in generate() function to create a generator on the child nodes and iterating it, and then returning self at the end. The problem is it's not recursing on each child, so it only ever goes one level deep. I can't figure out how to combine two generators in that way.
I'm having a hard time wrapping my head around how to do this! What do I need to do to make a recursive generator?
I don't know if a generator itself can be recursive.
Will M proved me wrong!
Here is a possible implementation for a pre-order traversal, using a stack for the child nodes which still have to be enumerated:
extension XMLNode : SequenceType {
public func generate() -> AnyGenerator<XMLNode> {
var stack : [XMLNode] = [self]
return anyGenerator {
if let next = stack.first {
stack.removeAtIndex(0)
stack.insertContentsOf(next.childNodes, at: 0)
return next
}
return nil
}
}
}
For a level-order traversal, replace
stack.insertContentsOf(next.childNodes, at: 0)
by
stack.appendContentsOf(next.childNodes)
Here is a recursive post-order generator. Can't say I'd recommend actually using it though.
#MartinR's answer seems a bit more practical
public func generate() -> AnyGenerator<XMLNode> {
var childGenerator:AnyGenerator<XMLNode>?
var childArrayGenerator:IndexingGenerator<[XMLNode]>? = self.childNodes.generate()
var returnedSelf = false
return anyGenerator {
if let next = childGenerator?.next() {
return next
}
if let child = childArrayGenerator?.next() {
childGenerator = child.generate()
return childGenerator?.next()
} else if !returnedSelf {
returnedSelf = true
return self
} else {
return nil
}
}
}
While Martin's answer is certainly more concise, it has the downside of making a lot of using a lot of array/insert operations and is not particularly usable in lazy sequence operations. This alternative should work in those environments, I've used something similar for UIView hierarchies.
public typealias Generator = AnyGenerator<XMLNode>
public func generate() -> AnyGenerator<XMLNode> {
var childGenerator = childNodes.generate()
var subGenerator : AnyGenerator<XMLNode>?
var returnedSelf = false
return anyGenerator {
if !returnedSelf {
returnedSelf = true
return self
}
if let subGenerator = subGenerator,
let next = subGenerator.next() {
return next
}
if let child = childGenerator.next() {
subGenerator = child.generate()
return subGenerator!.next()
}
return nil
}
}
Note that this is preorder iteration, you can move the if !returnedSelf block around for post order.
This is a bit of a head banger (for me). Basically I want to have 2 different singletons that inherit from the same class. In either I want to use a certain class which itself is derived. So I have Utility and both AUtil:Utility and BUtil:Utility. And Singleton that is used as ASingleton using AUtility in its stomach and B respectively. I failed on all frontiers. The last attempt was a factory pattern which simply got Swift 1.2 to Segfault:
protocol Initializable { init() }
class A:Initializable {
var x = "A"
required init() {}
}
class B:Initializable {
var x = "B"
required init() {}
}
class C {
let t:Initializable
init(t:Initializable) {
self.t = t
println(t)
}
func factory() {
println(t.dynamicType())
}
}
As said I also tried to make the following pattern generic:
private let _SingletonSharedInstance = StaticClass()
class StaticClass {
class var sharedInstance : StaticClass {
return _SingletonSharedInstance
}
}
let s = StaticClass.sharedInstance
(This one isn't generic as you see. But all my attempts failed and so I show my starting point.)
Anyway I seem to be lost between doom and death.
Do you mean something like this?
protocol Initializable: class { init() }
private var instances = [String: Initializable]()
func singletonInstance<T: Initializable>(_ ty: T.Type = T.self) -> T {
let name = NSStringFromClass(ty)
if let o = (instances[name] as? T) {
return o
}
let o = ty()
instances[name] = o
return o
}
An use-side of it, for instance.
class Foo: Initializable { required init() {} }
class Bar: Initializable { required init() {} }
let foo1 = singletonInstance() as Foo // or `singletonInstance(Foo.self)`
let foo2 = singletonInstance() as Foo
assert(foo1 === foo2)
let bar1 = singletonInstance() as Bar
let bar2 = singletonInstance() as Bar
assert(bar1 === bar2)
(I've tested the code above and got it to work in Swift 1.2.)
Inspired by findalls implementation, I build my own singleton generator, which is a little more powerful.
You can create a singleton of any Class or Structure type in Swift. The only thing you have to do is to implement one of two different protocols to your type and use Swift 2.0 or newer.
public protocol SingletonType { init() }
private var singletonInstances = [String: SingletonType]()
extension SingletonType {
// this will crash Xcode atm. it's a Swift 2.0 beta bug. Bug-ID: 21850697
public static var singleton: Self { return singleton { $0 } }
public static func singleton(setter: (_: Self) -> Self) -> Self {
guard let instance = singletonInstances["\(self)"] as? Self else {
return setInstance(self.init(), withSetter: setter, overridable: true)
}
return setInstance(instance, withSetter: setter, overridable: false)
}
private static func setInstance(var instance: Self, withSetter setter: (_: Self) -> Self, overridable: Bool) -> Self {
instance = restoreInstanceIfNeeded(instance1: instance, instance2: setter(instance), overridable: overridable)
singletonInstances["\(self)"] = instance
return instance
}
private static func restoreInstanceIfNeeded(instance1 i1: Self, instance2 i2: Self, overridable: Bool) -> Self {
// will work if the bug in Swift 2.0 beta is fixed !!! Bug-ID: 21850627
guard i1.dynamicType is AnyClass else { return i2 }
return ((i1 as! AnyObject) !== (i2 as! AnyObject)) && !overridable ? i1 : i2
}
}
This may look a little scary, but don't be afraid of this code. The public function inside the protocol extension will create two access points for you.
For example you will be able to write code like this now:
// extend your type: as an example I will extend 'Int' here
extension Int : SingletonType {} // nothing else to do, because Int already has an 'init()' initializer by default
// let the magic happen
Int.singleton // this will generate a singleton Int with 0 as default value
Int.singleton { (_) -> Int in 100 } // should set your Int singleton to 100
Int.singleton { $0 - 55 } // your singleton should be 45 now
// I need to mention that Xcode will produce the setter like this and trow an error
Int.singleton { (yourCustomInstanceName) -> Self in // replace 'Self' with 'Int' and you should be fine
return yourCustomInstanceName
}
// btw. we just ignored the return value everywhere
print(Int.singleton) // will print 45 here
var singleton2 = Int.singleton { $0 + 5 }
singleton2 += 10
print(Int.singleton) // should print 50, because 'singleton2' is just a copy of an Int value type
class A : SingletonType {
var name = "no name"
required init() {}
}
A.singleton { $0; let i = A(); i.name = "hello world"; return i } // custom init on first singleton call for type A
print(A.singleton.name)
print(A.singleton { $0.name = "A"; return $0 }.name)
print(A.singleton.name)
// should print "hello world" and twice the string "A"
If you have any idea how to enhance this code and make it even safer, please let me know. I will push this code on GitHub (MIT License) soon, so everyone can benefit from it.
UPDATE: I modified the code a little so you can now pass a custom initialized instance of a class with the setter function when its called the first time.
UPDATE 2: I removed ClassInstance protocol and modified the private restore function. The Instance protocol is now called SingletonType. The setter function is not optional anymore. Right now Xcode 7 beta 3 will crash and provide an illegal instruction: 4 error when you will call the getter. But this is a confirmed beta bug.