如果我将参数设置为nil,则会出现错误。像这样的代码:
func addChild(childToAdd: UIViewController, childToRemove: UIViewController) {
if (childToRemove != nil) {
childToRemove.view.removeFromSuperview()
}
var frame = childToAdd.view.frame as CGRect
frame.size.width = view.frame.size.width;
frame.size.height = view.frame.size.height;
childToAdd.view.frame = frame
view.addSubview(childToAdd.view)
}
override func viewDidLoad() {
super.viewDidLoad()
addChild(firstViewController, childToRemove: nil) //could not find an overload for conversion that accepts supplied argument
}
正如你所看到的,我不应该把nil放在那里,但我应该把它放进去。它在Objective-c中工作。
答案 0 :(得分:7)
您的childToRemove
参数定义为UIViewController
,不是可选的所以不能为
尝试:
func addChild(childToAdd: UIViewController, childToRemove: UIViewController?) {
允许第二个参数的nil值,并且不要忘记在使用它之前需要打开可选项(使用如果让这是一个很好的方法):
if let childController = childToRemove {
childController.view.removeFromSuperview()
}
答案 1 :(得分:1)
简要地说,如果你想发送nil
:
func addChild(childToAdd: UIViewController, childToRemove: UIViewController?) {
if childToRemove != nil {
childToRemove!.view.removeFromSuperview()
}
// the rest is the same...
}