如何在Swift中执行委派的基本实现?

时间:2016-02-13 23:38:04

标签: ios swift delegates swift2

我正试图了解代表团并将其剥离到基本实施。我已经想出了这个,但委托函数永远不会被调用。任何人都可以解释一下吗?

template<typename T>
void myFunction()
{
    ...
}

template<typename T, typename std::enable_if<T::MyTypedef>::type* = nullptr>
typename myFunction()
{
    ...
}

7 个答案:

答案 0 :(得分:7)

callDelegate()

点在您拨打delegate之前需要指定DelegatorClass。要检查您的代表团是否正常工作,您可以使用委托初始化class DelegatorClass { var delegate: MyDelegate? = DelegateClass() func callDelegate() { delegate?.delegatedFunction("hello") } }

 public void SendConfirmationAfterRegister(String EmailID, String UserName)
    {
        MailMessage mailMsg = new MailMessage();

        String BodyMsg = UserName + ", \r\n\nWe have recieved your request to become a user of our site.  Upon review, we will send you verification for site access.\r\n\n" +
            "Thank you, \r\n\nMuda Admin";
        try
        {
            var client = new SmtpClient("smtp.gmail.com", 587)
            {
                Credentials = new NetworkCredential(ConfigurationManager.AppSettings["AdminEmail"].ToString(), ConfigurationManager.AppSettings["Pwd"].ToString()),
                EnableSsl = true
            };

            mailMsg.IsBodyHtml = true;
            client.Send(ConfigurationManager.AppSettings["AdminEmail"].ToString(), EmailID, "Received Your Request", BodyMsg);

            client.Send(ConfigurationManager.AppSettings["AdminEmail"].ToString(), "mymailId", "User Needs Access", EmailID + " looking for access the xyz Network Site.");
        }
        catch (Exception ex) { throw new Exception(ex.Message); }
    }

答案 1 :(得分:4)

使用您的代码,这是正确使用委托的方法。 当您致电callDelegate()时,会引用DelegateClass,然后执行delegatedFunction()

protocol MyDelegate{
    func delegatedFunction (a:String)
}
class DelegatorClass {
    var delegate: MyDelegate?
    func callDelegate() {
        delegate?.delegatedFunction("hello")
    }
}
class DelegateClass: MyDelegate {
    let my_class= DelegatorClass()
    my_class.delegate = self

    func delegatedFunction (a:String){
        print(a)
    }
}

查看苹果协议文档以获取更多信息。 https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html

答案 2 :(得分:4)

protocol MyDelegate{
    func delegatedFunction (a:String)
}

class DelegatorClass {
    var delegate: MyDelegate?
    func callDelegate() {
        delegate?.delegatedFunction("hello")
    }
}

class DelegateClass: MyDelegate {
    func delegatedFunction (a:String){
        print(a)
    }
}
let delegator = DelegatorClass()
delegator.callDelegate() // print nothing, because delegate is nil by default

// set your delegate !!!!!!!
delegator.delegate = DelegateClass()
delegator.callDelegate() // print "hello"

你的方法没有错,只要以正确的方式使用它。该点是将委托变量设置为符合协议MyDelegate的类型T的某个实例。在您的情况下,这是DelegateClass实例。 通常,T几乎可以是符合MyDelegate协议的所有内容。

struct S:MyDelegate {
    func delegatedFunction(a: String) {
        print("Hello from struct conforming to MyDelegate protocol")
    }
}

delegator.delegate = S()
delegator.callDelegate() // print "Hello from struct conforming to MyDelegate protocol"

delegator.delegate = nil
delegator.callDelegate() // print nothing again :-)

答案 3 :(得分:3)

在示例操场上测试并工作。

import UIKit

protocol MyDelegate {
    func delegatedFunction(a: String)
}

class DelegatorClass {

    var delegate: MyDelegate?

    func callDelegate() {
        delegate?.delegatedFunction("Hello World!")
    }
}

class DelegateClass: MyDelegate {

    let my_class = DelegatorClass()

    init () {
        my_class.delegate = self
    }

    // MyDelegate Protocol implementation
    func delegatedFunction(a: String) {
       print(a)
    }

}

要测试它,请在下面添加以下行。

let c = DelegateClass()
c.my_class.callDelegate()

解释,

当您创建DelegateClass c的实例并初始化它时,将执行init方法。 DelegatorClass实例my_class成员delegate现在拥有对self的引用,这是DelegateClass。

现在执行callDelegate()方法时,由于可选变量delegate现在包含对DelegateClass实例的引用,因此它基本上要求在其中执行delegatedFunction(a: String)方法。因此,字符串a被打印出来。

另请注意,我必须将my_class.delegate = self放在init()中的原因是因为您只能在类的方法之外进行实例属性声明。所有功能都应该放在方法内。

希望解释清楚! :)

答案 4 :(得分:2)

你几乎已经拥有它,你只是忘了将class DelegateClass分配给class DelegatorClass delegate属性,并进行其他一些调整。

基本上,您告诉class DelegateClass符合protocol MyDelegate,这意味着它必须实施delegatedFunction(a:String)。在class DelegatorClass上,delegate属性期望被分配一个类型为protocol MyDelegate的对象,以便它可以针对它调用协议函数,因此分配{{1}的重要性{}} {/ 1>中的self属性

delegate

答案 5 :(得分:1)

DelegateClass的实例需要将自己设置为DelegatorClass

实例的委托

所以,你会有类似的东西:

class DelegateClass: MyDelegate {
    func delegatedFunction (a:String){
        print(a)
    }

    func testFunction() {
       var delegator=DelegatorClass()
       delegator.delegate=self
       delegator.callDelegate()
    }
}

答案 6 :(得分:-1)

protocol Delegate{

    func callMe()
    func textMe()
}

@objc protocol DelegateWithOptional: class{

    optional func callMe()
    func textMe()
}

class SomeClass{

    var delegate: Delegate?

   func call(){
      delegate?.callMe()
   }

   func text(){
      delegate?.textMe()
   }

}

class SomeClass2{

    var delegateWithOptional: DelegateWithOptional?

    func call(){
       delegateWithOptional?.callMe()
    }

    func text(){
       delegateWithOptional?.textMe()
    }
}

class ClassConfirmingToProtocol: SuperClass, Delegate{

    var someClass = SomeClass()
    override func viewDidLoad(){
        someclass.delegate = self
    }

    //must implement this method
    func textMe(){ 
        //do something
    }

    //must implement this method
    func callMe(){  
        //do something
    }

}

class ClassConfirmingToProtocolWithOptional: SuperClass, DelegateWithOptional{

    var someClass2 = SomeClass2()
    override func viewDidLoad(){
        someclass2.delegate = self
    }

    //must implement this method
    func textMe(){ 
        //do something
    }

    //optional to implement this method, i.e. even without this method, its not gonna throw any error
    func callMe(){
        //do something
    }

}