1

In my app there are many classes for different ViewControllers. I am searching way to give class name as function parameter so i can use it in function.

Example

func myFunc (var1: String, var2 : Int, var3 : myClass) {
 var example = myClass();
 example.name = var1;
 example.age = var2;
}

i saw this thread Class conforming to protocol as function parameter in Swift but i didn't understand how can i solve my problem with it.

3
  • Why do you want to pass the class as the function parameter? Cannot you pass a class instance instead? Commented Aug 26, 2015 at 7:51
  • Agree with @MarioZannone , your problem should be solved using inheritance and passing the instance variable to the controller Commented Aug 26, 2015 at 8:23
  • can you show me example? Commented Aug 26, 2015 at 9:47

1 Answer 1

1

You can do this without the need to pass an instance of your view controller:

import Cocoa

protocol MyViewControllerType : class {
    var name : String { get set }
    var age : Int { get set }
}

class FirstViewController : NSViewController, MyViewControllerType {
    var name = ""
    var age = 0
}

class SecondViewController : NSViewController, MyViewControllerType {
    var name = ""
    var age = 0
}

func myFunc<VC : NSViewController where VC : MyViewControllerType>(viewControllerType: VC.Type, name: String, age: Int) -> VC {
    let viewController = VC()
    viewController.name = name
    viewController.age = age
    return viewController
}

let first = myFunc(FirstViewController.self, name: "Bob", age: 20)
let second = myFunc(SecondViewController.self, name: "Paul", age: 30)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.