2017-02-17 112 views
0

我試圖以允許用戶在我的應用程序發送電子郵件,但我得到一個:它的聲明之前局部變量聲明迅速

使用局部變量「configureMailComposeViewController」的

這是代碼。

func item(_ item: Int, selectedAtContactIndex index: Int) { 
    var mailComposeViewController = configuredMailComposeViewController() 
    if MFMailComposeViewController.canSendMail() { 
     self.presentViewController(mailComposeViewController, animated: true, completion: nil) 
    } else { 

    } 
} 

func configuredMailComposeViewController() -> MFMailComposeViewController{ 
    let mailComposerVC = MFMailComposeViewController() 
    mailComposerVC.mailComposeDelegate = self 

    mailComposerVC.setToRecipients([EmailAddressArray[index]]) 
    mailComposerVC.setSubject("I need your help") 

    return mailComposerVC 
} 

Image of the Error

+1

無關的,爲什麼你叫'configuredMailComposeViewController'之前你叫'如果MFMailComposeViewController.canSendMail()'? – rmaddy

+0

@john,你認爲這是什麼意思? 'MFMailComposeViewController()' – aircraft

回答

1
func configuredMailComposeViewController() -> MFMailComposeViewController 

這裏這個權利是你的函數具有返回類型MFMailComposeViewController,你會得到你什麼時候會調用這個方法。它會給你返回一些結果

現在您的上述方法func configuredMailComposeViewController() -> MFMailComposeViewControllercall的結果需要保存在一個變量中,您不能讓它在空中飛行。爲了保存或獲取此方法,您需要執行以下操作 - :

var mailComposeViewController = configuredMailComposeViewController() 

所以這清楚你不必在你的回報功能後,調用此mailComposeViewController = configuredMailComposeViewController()

正是這個 - :

func configuredMailComposeViewController() -> MFMailComposeViewController{ 
     let mailComposerVC = MFMailComposeViewController() 
     mailComposerVC.mailComposeDelegate = self 

     mailComposerVC.setToRecipients([EmailAddressArray[index]]) 
     mailComposerVC.setSubject("I need your help") 

     return mailComposerVC 
    } 





     func item(_ item: Int, selectedAtContactIndex index: Int) { 

     if MFMailComposeViewController.canSendMail() { 
var mailComposeViewController = configuredMailComposeViewController() 
      self.presentViewController(mailComposeViewController, animated: true, completion: nil) 
     } else { 

     } 
    } 
+1

你真的應該招行'VAR mailComposeViewController = configuredMailComposeViewController()'裏面的'if'語句。如果您無法發送電子郵件,則創建郵件編輯器是沒有意義的。 – rmaddy

0

切換的功能的順序,把configuredMailComposeViewController功能之上

func configuredMailComposeViewController() -> MFMailComposeViewController{ 
    let mailComposerVC = MFMailComposeViewController() 
    mailComposerVC.mailComposeDelegate = self 

    mailComposerVC.setToRecipients([EmailAddressArray[index]]) 
    mailComposerVC.setSubject("I need your help") 

    return mailComposerVC 
} 





    func item(_ item: Int, selectedAtContactIndex index: Int) { 
    var mailComposeViewController = configuredMailComposeViewController() 
    if MFMailComposeViewController.canSendMail() { 
     self.presentViewController(mailComposeViewController, animated: true, completion: nil) 
    } else { 

    } 
} 
+0

我很困惑,你可以讓編輯告訴我你談論 – john

+0

我已經編輯我的回答顯示瞭如何 – inzo