1. 声明
// this delegate needs a @objc, because @optional is only for objective-c, not for swift
@objc protocol DetailViewControllerDelegate : NSObjectProtocol {optional func changeItem(forUserModel userModel: UserModel?)
}2.代理的点击事件func onChangeButtonClick(sender: UIButton!) {if (userModel != nil) {userModel!.userName = "ChangeName"userModel!.email = "robinson_911@163.com"// changeItem needs to add a ? to the end, before (), because// this function is optional// delegate? 表示可能没有代理,而changeItem?表示方法可能没有实现,这样写就算没有实现也没有问题delegate?.changeItem?(forUserModel: userModel)self.navigationController!.popViewControllerAnimated(true)}}
3. 实现
class RootViewController:UITableViewController, DetailViewControllerDelegate{}func changeItem(forUserModel userModel: UserModel?) {var index = 0for index = 0; index < dataSource.count; index++ {let model = dataSource[index] as? UserModelif model!.userID == userModel!.userID {model!.phone = userModel!.phonemodel!.email = userModel!.emailtableView.reloadRowsAtIndexPaths([currentIndexPath!], withRowAnimation: UITableViewRowAnimation.Fade)break}}}