class func invite(_cntrl : UIViewController)
{
// code to open mail composer sheet
}
this method needs to accept controllers which conforms to MFMailComposeViewControllerDelegate
.
currently it gives error :
Type 'UIViewController' does not conform to protocol
'MFMailComposeViewControllerDelegate'
how to pass uiviewconroller conforms MFMailComposeViewControllerDelegate
?
something like :
class func invite(_cntrl : UIViewController<MFMailComposeViewControllerDelegate>)
{
// code to open mail composer sheet
}
I believe if you set the parameter type to MFMailComposeViewControllerDelegate it accepts that.
so your function would be:
class func invite(_cntrl : MFMailComposeViewControllerDelegate)
As found in the Protocols as Types in the Swift Language Guide
EDIT:
Upon further clarification, as you want to be able to pass through a subclass of UIViewController that also conforms to the MFMailComposeViewControllerDelegate, it appears that extending the UIViewController class is the best way to go. (These are like ObjC categories.
eg
extension UIViewController : MFMailComposeViewControllerDelegate
{
optional func mailComposeController(_ controller: MFMailComposeViewController!,
didFinishWithResult result: MFMailComposeResult,
error error: NSError!)
{
self.dismissViewControllerAnimated(flag:true, completion:nil);
}
}
I don't know an exact solution. But as an alternative if you want to check whether an object conforms to that particular protocol or not using the is
keyword (also can use as
) In this case it'll look like:
class func invite(_cntrl : UIViewController)
{
if _cntrl is MFMailComposeViewControllerDelegate
{
println("Confirms to protocol")
}
else
{
println("Not confirm")
}
}
This approach is mentioned in Checking for Protocol Conformance
You can use the
is
andas
operators described in Type Casting to check for protocol conformance, and to cast to a specific protocol. Checking for and casting to a protocol follows exactly the same syntax as checking for and casting to a type:The
is
operator returnstrue
if an instance conforms to a protocol and returnsfalse
if it does not.The
as?
version of the downcast operator returns an optional value of the protocol's type, and this value isnil
if the instance does not conform to that protocol.The as version of the downcast operator forces the downcast to the protocol type and triggers a runtime error if the downcast does not succeed.
In Swift 3 you can do this
class func invite(_cntrl : MFMailComposeViewControllerDelegate)
{
// code to open mail composer sheet
// You can cast it to a UIViewController subclass if you need it
}
You can do something like,
func setDelegate<T : UIViewController>(controller: T) where T: YourDelegateName{
delegate = controller
}
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.