Unknown reference

This is just more like an open question if such feature in swift would make any sense.
Sometimes I feel like it would be useful to not force the implementation to decide how the memory reference ownership should be handled. The "caller" could pass this information. Example:

class Presenter {
	unknown var view: View!
	init(view: View) {
		self.view = view
	}
}

class View: UIViewController {
	var presenter: Presenter
}

class Factory {
	func makeModule() -> View {
		let view = View() 
		let presenter = Presenter(view: weak view)
		view.presenter = presenter
		return view
	}
}

Currently we are forced to introduce this implementation detail even there is no explicit need beside ARC.

You can already do this with Unmanaged. Instead of Presenter taking a real View, it could take an Unmanaged<View>. This would leave it up to someone else to manage the life of the view.

You could also make the storage unowned(unsafe), which is exactly what Unmanaged does internally.

But if I get this correctly I could even use unowned and still manage the lifetime somewhere else. But I would like to decide if the Presenter would strongly or weakly handle the lifetime not that someone else always needs to manage the lifetime.

Another example:

class A {
	unknown var referenceB: B!
}

class B {
	unknown var referenceA: A!
}

func makeAB_v1() -> (A, B) {
	let a = A()
	let b = B()
	a.referenceB = strong b
	b.referenceA = weak a
}

func makeAB_v2() -> (A, B) {
	let a = A()
	let b = B()
	a.referenceB = weak b
	b.referenceA = strong a
}

This really wouldn't work in Swift. It would require, among other things, that everything about the class (including method implementations) having an unknown property be exposed in the module interface. Since the complier would have to perform different ARC operations based on the type of reference passed.

Another thing that really wouldn't make this valuable is that within the containing type, you would have to effectively treat every access to the unknown as possibly being nil, since it's unknown to the author what kind of reference would be passed. And at that point, you're back to the behavior of weak var t: SomeType!, where every access to t would need nil checking.

Terms of Service

Privacy Policy

Cookie Policy