最近寫的項目是用的swift4.0來寫的,但是坑不是一般的多,但是相較于oc來說有好處也有不好之處,因為oc有runtime機制,下面我就說說swift的一個關于nil的坑,話不多說,上源代碼
//我在一個自定義的uiview里面創(chuàng)建一個初始化方法為
init(iconImage:String,message:String) {
super.init(frame:CGRect.zero)
self.frame = CGRect(x: 0, y: 0, width: windowW, height: windowH)
}
//在vc中初始化這個view
let alertView:CCarAlertView = CCarAlertView.init(iconImage:nil, message: "您還未登錄,請先登錄/注冊")
然后編譯的時候就出現(xiàn)下面這個錯誤
Nil is not compatible with expected argument type 'String'
解決辦法
//我在一個自定義的uiview里面創(chuàng)建一個初始化方法為
init(iconImage:String?,message:String) {
super.init(frame:CGRect.zero)
self.frame = CGRect(x: 0, y: 0, width: windowW, height: windowH)
}
//在vc中初始化這個view
let alertView:CCarAlertView = CCarAlertView.init(iconImage:nil, message: "您還未登錄,請先登錄/注冊")
然后判斷iconImage是否為空的時候需要這樣做
if (iconImage?.isEmpty) != nil{
print("iconImage不為空")
}else{
print("iconImage為空")
}
這個?和!我個人認為很煩人