简体   繁体   中英

Swift Complex type in parameter

In order to be a bit more clear I am looking for a solution for the user to pass a class with a specific subclass and protocol, ie a class that inherits a viewController and delegate protocol. I know its possible to create a protocol list but cannot find a solution that works correctly. Currently I use a initializer and use the viewcontroller as a parameter and check for delegate inside the function but I would rather if I can have these types in the parameter instead.

EDIT: Looking to do something similar to this

Protocol prot:Delegate{}

class cla:ViewController{}

class impl{
      init(mainUI: cla, prot){
         do things
       }
}

That way back in the main view controller I can do something like this

class viewController: cla, prot{

     var view:impl  

     override func loadView() {
        //Attach to Screen
        view = impl(mainUI: self);
    }

}

Their is a bit more happening but that's the only part thats really relevant. Currently I use a initializer to just fail if the class doesn't inherit the correct protocols

You could create a dummy type that represents your requirements. A typealias doesn't work in this case, but this might:

class DummyClass: MyViewController, MyDelegateProtocol {}

func needsRequiredClass(input: DummyClass) {...}

With MyViewController and MyDelegateProtocol being the superclass and delegate you mentioned. The DummyClass would have an empty implementation.

Then, make your specific classes sub classes of DummyClass :

class TestClass: DummyClass {...}

And you can pass in that new class:

let test = TestClass()
self.needsRequiredClass(test)

You're asking the wrong question. In other words trying to shoe-horn in a serious design mistake.

A view should not know that its delegate is a UIViewController or a subclass.

A delegate should be any class that obeys (adopts) a specific delegate protocol.

A view should only delegate specific responsibilities. Each of those responsibilities must be described by a protocol method or property.

If you explain what your issue is in more detail (why you think you need direct access to the entire definition of a UIViewController within a UIView ), we can help you avoid this mistake.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM