How to write getter and setter for HasDelegate protocol in RxSwift? - rx-swift

I am implementing HasDelegate protocol to the IWDeviceManager.
In all the posts which I have read, no one has wrote getter & setter for this public var delegate property.
The compiler is explicitly asking me to write getter & setter for public var delegate. Why it's required in my case?
I tried writing but my code crashes when I try to get or set the delegate.
How do I solve this issue?
I have shared the code below
extension IWDeviceManager: HasDelegate {
public typealias Delegate = IWDeviceManagerDelegate
// Compiler explicitly asks to write getter and setter for this.
public var delegate: IWDeviceManagerDelegate? {
get { // Crashes here
return IWDeviceManager.shared()?.delegate
}
set(newValue) { // crashes here
IWDeviceManager.shared()?.delegate = newValue
}
}
}
Below is interface for IWDeviceManager
open class IWDeviceManager : NSObject {
weak open var delegate: IWDeviceManagerDelegate!
open class func shared() -> Self!
open func initMgr()
open func initMgr(with config: IWDeviceManagerConfig!)
}

Instead of using HasDelegate try this:
class IWDeviceManagerDelegateProxy
: DelegateProxy<IWDeviceManager, IWDeviceManagerDelegate>
, DelegateProxyType
, IWDeviceManagerDelegate {
init(parentObject: IWDeviceManager) {
super.init(parentObject: parentObject, delegateProxy: IWDeviceManagerDelegateProxy.self)
}
static func currentDelegate(for object: IWDeviceManager) -> Delegate? {
return object.delegate
}
static func setCurrentDelegate(_ delegate: IWDeviceManagerDelegate?, to object: IWDeviceManager) {
object.delegate = delegate
}
static func registerKnownImplementations() {
self.register { IWDeviceManagerDelegateProxy(parentObject: $0) }
}
}

Related

RxSwift Delegate Binding isn't Generated?

I am trying to bind a delegate this is what was done
/** Delegate Proxy **/
func castOrThrow<T>(_ resultType: T.Type, _ object:Any) throws -> T {
guard let returnValue = object as? T else {
throw RxCocoaError.castingError(object: object, targetType: resultType)
}
return returnValue
}
#objc
public protocol TestEventGeneratorDelegate:class {
#objc optional func asyncEventResult(int:Int)
}
open class TestEventGenerator {
public var delegate: TestEventGeneratorDelegate?
func asyncCall() {
DispatchQueue.global().asyncAfter(deadline: .now() + .seconds(1)) { [weak self] in
guard let self = self else { return }
self.delegate?.asyncEventResult!(int: 0)
}
}
}
extension TestEventGenerator: HasDelegate {
public typealias Delegate = TestEventGeneratorDelegate
}
open class RxTestDelegateProxy : DelegateProxy<TestEventGenerator,TestEventGeneratorDelegate>,
DelegateProxyType,
TestEventGeneratorDelegate {
public weak private(set) var testGenerator: TestEventGenerator?
public init(testEventGenerator: ParentObject) {
self.testGenerator = testEventGenerator
super.init(parentObject: testEventGenerator, delegateProxy: RxTestDelegateProxy.self)
}
public static func registerKnownImplementations() {
self.register { RxTestDelegateProxy(testEventGenerator: $0) }
}
}
extension Reactive where Base: TestEventGenerator {
public var delegate: DelegateProxy<TestEventGenerator, TestEventGeneratorDelegate> {
return RxTestDelegateProxy.proxy(for: base)
}
public var asyncEventResult: Observable<Int> {
let source = delegate.methodInvoked(#selector(TestEventGeneratorDelegate.asyncEventResult(int:)))
.map { (a) in
return try castOrThrow(Int.self,a[0])
}
return source
}
}
/** Delegate Proxy **/
Then when I use it
let testEventGenerator = TestEventGenerator()
textEventGenerator.rx.asyncEventResult.subscribe.... // subscribe here no rx found?
testEventGenerator.asyncCall() // call and wait for the observable to return to the delegate
It doesn't compile and says there is no such rx
I have to bind it because the person who wrote the API didn't use a callback to return the value but rather a delegate.
This is example of how he wrote the code and how I want to wrap it.
Is there a way to bind a delegate that requires a kick off from asyncCall()?
so I can chain it using flatmapLatest in a promiseLike way?
Thanks let me know!
I followed these tutorial:
How to convert Delegate to Observable RxSwift?
and
https://blog.ippon.fr/2018/11/13/rxswift-how-to-make-your-favorite-delegate-based-apis-reactive/
have conform to TestEventGenerator:ReactiveCompatible and that will fix it.

Swift - Pass a reference to a class

I have a class which will perform a search. Once complete I want the search class to pass back the results to which ever instance (of another class) started the search. My thinking was to pass a reference to the class which instantiates the search class and use that reference to call a function. Here's a basic example of what I'm trying to do. How can I get this to work, or is there another/better way?
Search Class (I've tried AnyObject and UITableViewContoller):
class SearchClass : NSObject, NSURLConnectionDelegate, NSURLConnectionDataDelegate {
var callingClass : AnyObject? = nil //To store reference to the "other" class
var searchResults : [[String : AnyObject]]? = nil
init(callingClass: AnyObject) { //I don't know the name of the ViewController class which will instantiates this as it will be called by several different classes
self.callingClass = callingClass
}
func startSearch(searchString: String) {
//NSURLConnection etc
}
func connectionDidFinishLoading(connection: NSURLConnection) {
//more code
searchResults = ...
callingClass!.searchCompleted(searchResults) //Pass the search results back to the class instance which started the search
}
}
Other Classes:
class RandomViewController : UITableViewController {
//The casting on the next line fails
let Searcher = SearchClass(callingClass: self as! UITableViewController) //OR AnyObject
func randomFunction() {
searcher.startSearch("search query")
}
func searchComplete(searchResults: [[String : AnyObject]]) {
self.searchResults = searchResults
tableView.reloadData()
}
}
You can add a closure parameter to your startSearch function in your search class:
typealias SearchResultHandler = (result: [String : AnyObject]) -> ()
func startSearch(query: String, resultHandler: SearchResultHandler) {
// send the search request and in the completion handler of the request call your result handler:
resultHandler(result: searchResult)
}
Which you would then call from any class:
let searcher = SearchClass()
searcher.startSearch("query") { (result) -> () in
self.searchResults = results
tableView.reloadData()
}
You can use generics when you don't know what the class is going to be:
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Generics.html
However....
This seems like something that you should use protocol / delegates for.
// NOTE: weak references must be class type
protocol SearchClassDelegate: class {
func searchComplete(results: [[String: AnyObject]?])
}
// This is where you define T as the generic class
class SearchClass {
weak var delegate: SearchClassDelegate? // This is your "callingClass"
// NOTE: make sure it's weak
// ...
func connectionDidFinishLoading() {
// ...
self.delegate?.searchComplete(results)
}
}
// Set to the delegate
class ViewController: UIViewController, SearchClassDelegate {
// ...
// Make sure you set the delegate
// Here is where you implement this function
func searchComplete(results: [[String : AnyObject]?]) {
// Do whatever
// ...reloadData() etc.
}
}

Type variable in protocol - Swift 2

So I have a protocol, and in it I want a variable that is a class type. That way I can init that class from the variable.
Keep in mind that there will be many different classes. I made a quick example.
I get the error "type 'CashRegister' does not conform to protocol 'RegisterProtocol'"
This example isn't exactly what I'm doing, but it gets the point across. Thanks for the help.
protocol RegisterProtocol {
var currentBill: DollarBillProtocol {get set}
func makeNewBill()->DollarBillProtocol
}
extension RegisterProtocol {
func printCurrentBill() {
Swift.print(currentBill)
}
}
class CashRegister: RegisterProtocol {
var currentBill = OneDollarBill.self
func makeNewBill() -> DollarBillProtocol {
return currentBill.init()
}
}
protocol DollarBillProtocol {
// protocol that all bills have in common
}
class OneDollarBill: DollarBillProtocol {
required init(){
}
}
class FiveDollarBill: DollarBillProtocol {
required init(){
}
}
The way you declare currentBill in CashRegister makes it a var of type class. But the protocol RegisterProtocol requires this variable to be of type DollarBillProtocol in any class that implements the protocol. The compile error is because of this mismatch.
To make this more clear, you could declare the var with the explicit type, as follows:
class CashRegister: RegisterProtocol {
var currentBill: DollarBillProtocol = OneDollarBill() // or other initial value
}

When to init a delegate in Swift

I have a basic question. I'm working on a project with many delegate patterns, and would like reference on the best way about initializing them..
Here's some ideas with a test delegate I made:
Option 1:
It fails because I'm initilizing the delegate to self before super.init()
protocol MyClassDelegate {
func doSomething()
}
class MyClass {
var delegate: MyClassDelegate!
init(delegate: MyClassDelegate){
self.delegate = delegate
}
func myClassFuction(){
self.delegate.doSomething()
}
}
class ClassConformingToDelegate: NSObject, MyClassDelegate {
let myClass: MyClass
override init(){
myClass = MyClass(delegate: self) // Error because it's called before super.init
super.init()
}
func doSomething(){
//called from the delegate
}
}
Option 2:
It works, but then I risk having the delegate be nil.. Would I have to run a 'if delegate != nil' check each time I want to call a method? Is there a way around that? Is it a good practice to init the delegate this way?
protocol MyClassDelegate {
func doSomething()
}
class MyClass {
var delegate: MyClassDelegate!
init(){
}
func myClassFuction(){
self.delegate.doSomething() // might fail if delegate is nil
}
}
class ClassConformingToDelegate: NSObject, MyClassDelegate {
let myClass: MyClass
override init(){
myClass = MyClass()
super.init()
myClass.delegate = self // works because called after super.init
}
func doSomething(){
//called from the delegate
}
}
Those were just a couple ideas. I'm just trying to learn the best way of doing it. I'm open to all suggestions.
Thanks!!
Option 2 looks better. However, in this case it would be advisable to use an optional as your delegate type. That way, you don't need to check "if delegate != nil" every time you want to perform a task with it. You can simply use optional chaining, which is designed specifically for such cases where you want to perform a task on an optional only if it contains a value.
protocol MyClassDelegate {
func doSomething()
}
class MyClass {
var delegate: MyClassDelegate?
init(){
}
func myClassFuction(){
self.delegate?.doSomething() // will do nothing if delegate is nil
}
}
class ClassConformingToDelegate: NSObject, MyClassDelegate {
let myClass: MyClass
override init(){
myClass = MyClass()
super.init()
myClass.delegate = self
}
func doSomething(){
//called from the delegate
}
}
Use lazy initialization to work around that issue.
protocol MyClassDelegate: class {
func doSomething()
}
class MyClass {
private(set) weak var delegate: MyClassDelegate?
func myClassFuction ( ) {
self.delegate?.doSomething()
}
init ( delegate: MyClassDelegate ) {
self.delegate = delegate
}
}
class ClassConformingToDelegate: NSObject, MyClassDelegate {
lazy private(set) var myClass: MyClass = {
return MyClass(delegate: self)
}()
func doSomething ( ) {
//called from the delegate
}
}
The variable myClass, which has no public setter, will be initialized the first time it is accessed by ClassConformingToDelegate itself or by some external code. If you want to make sure that it is always initialized when creating a new ClassConformingToDelegate object (as its sole creation may have side effects, like registration to notifications and so on), just access it from init:
override
init ( ) {
super.init()
_ = self.myClass
}

Class variables not yet supported

I begin my project with a split view controller as initial view controller and start it automatically from storyboard.
Generally, an app with this UI have one and only one split view controller as root, so I create a static variable in the subclass and set it when initialisation was done.
So I want try this behaviour with swift.
I read the Swift programming language guide book on iBook about Type properties (with static and class keyword) and trying a piece of code to the job:
import UIKit
class SplitViewController: UISplitViewController {
class func sharedInstance() -> SplitViewController {
return SplitViewController.instance
}
class let instance: SplitViewController = nil
init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.initialization()
}
init(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder);
self.initialization()
}
func initialization() {
SplitViewController.instance = self;
}
}
but I figured out when Xcode say the class keyword for type properties wasn't supported yet.
Did you have a solution to do this ?
Embedding a struct can work just fine as a workaround:
class SomeClass
{
// class var classVariable: Int = 0
// "Class variables not yet supported." Weird.
// Workaround:
private struct SubStruct { static var staticVariable: Int = 0 }
class var workaroundClassVariable: Int
{
get { return SubStruct.staticVariable }
set { SubStruct.staticVariable = newValue }
}
}
The SomeClass.workaroundClassVariable computed type property can then be used as if it were a stored type property.
Swift now has support for static variables in classes. This is not exactly the same as a class variable (because they aren't inherited by subclasses), but it gets you pretty close:
class X {
static let y: Int = 4
static var x: Int = 4
}
println(X.x)
println(X.y)
X.x = 5
println(X.x)
It seems to be possible to declare variables with static storage duration in file scope (as in C):
var sharedInstance: SplitViewController? = nil
class SplitViewController: UISplitViewController {
....
func initialization() {
sharedInstance = self
}
}
My preferred method is to just use a private file scope var outside of the class and then implement class/static getters and setters:
private var _classVar: Int = 0;
class SomeClass
{
public class var classVar: Int
{
get { return _classVar }
set { _classVar = newValue }
}
}
As of Swift 1.2 (available with Xcode 6.3b1 and onwards), static class properties and methods are supported.
class SomeClass
{
static var someVariable: Int = 0
}
Using a dispatch_once singleton model in Swift
Seems to be the best answer so far, avoiding the use of a global variable.
A solution enough similar than var in file scope but more customisable and near singleton is to use a struct which support static var as property of class
struct PersonSharedData {
static var backstore = ""
var data: String {
get { return PersonSharedData.backstore }
set { PersonSharedData.backstore = newValue }
}
}
class Person {
var shared=PersonSharedData() //<< pseudo class var
var family: String {
get { return shared.data }
set { shared.data=newValue }
}
var firstname = ""
var lastname = ""
var sexe: Sexe = .Unknown
}
Ok, with the solution of Nikolai that do the work. I post my changes in this thread for information
var instance: SplitViewController? = nil
class SplitViewController: UISplitViewController {
class func sharedInstance() -> SplitViewController? {
return instance;
}
init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.initialization()
}
init(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder);
self.initialization()
}
func initialization() {
instance = self
}
}
and for example, in my appDelegate, I can access this static method like this
SplitViewController.sharedInstance()!.presentsWithGesture = false
The wording in the error heavily implies this will be a language feature in the future.
You may want to resort temporarily to declaring a property variable in the Application Delegate and retrieve it from there. Not ideal, definitely an anti-pattern, but would give you a central place to retrieve the UISplitViewController when needed.
You have to wrap the class variables inside an inner struct variable
class Store{
var name:String
var address:String
var lat:Int
var long:Int
init(name:String, address:String, lat:Int, long:Int){
self.name = name
self.address = address
self.lat = lat
self.long=long
}
private struct FACTORY_INITIALIZED_FLAG { static var initialized: Bool = false
static var myStoreList:[Store]?
static func getMyStoreList()->[Store]{
if !initialized{
println("INITIALIZING")
myStoreList = [
Store(name: "Walmart", address: "abcd", lat: 10, long: 20),
Store(name: "JCPenny", address: "kjfnv", lat: 23, long: 34)
]
initialized = true
}
return myStoreList!
}
}
}
var a = Store.FACTORY_INITIALIZED_FLAG.getMyStoreList()
var b = Store.FACTORY_INITIALIZED_FLAG.getMyStoreList()
// only prints INITIALIZING once
Try this:
class var instance: SplitViewController {
return nil
}
It is called Type Property in Swift.
You define type properties with the static keyword. For computed type properties for class types, you can use the class keyword instead to allow subclasses to override the superclass’s implementation. The example below shows the syntax for stored and computed type properties:
struct SomeStructure {
static var storedTypeProperty = "Some value."
static var computedTypeProperty: Int {
return 1
}
}
enum SomeEnumeration {
static var storedTypeProperty = "Some value."
static var computedTypeProperty: Int {
return 6
}
}
class SomeClass {
static var storedTypeProperty = "Some value."
static var computedTypeProperty: Int {
return 27
}
class var overrideableComputedTypeProperty: Int {
return 107
}
}
Read more at link below,
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html#//apple_ref/doc/uid/TP40014097-CH14-ID254

Resources