Swift - 类Func实例成员'x'不能用于'y'类型

时间:2018-04-13 06:35:22

标签: ios swift

警报提示错误“实例成员'警报'不能用于'SendPhoto'类型”。我看了一些答案,但CustomAlertView Non-Void功能。所以我没弄明白。

class SendPhoto {
    var alert:CustomAlertView?
    class func sendPhotoToAssistant(){
        self.alert = CustomAlertView(title: "Title")
    }
}

2 个答案:

答案 0 :(得分:2)

原因是因为var alert只能在实例函数中访问,而您尝试在类函数中设置它。 如果您想设置var alert,则需要将代码更改为以下内容(还将函数名称更改为遵循Swift约定):

class SendPhoto {
    var alert: CustomAlertView?

    func sendPhoto() { // notice the lack of `class` in the declaration
        self.alert = CustomAlertView(title: "Title")

    }
}

答案 1 :(得分:1)

如果您想以类func的身份获取警报,可以这样做:

class SendPhoto {

    class func sendPhotoToAssistantAlert() -> CustomAlertView {
        return CustomAlertView(title: "Title")
    }
}

修改

如果您想要处理Alamofire上传过程,我建议您以这种方式更改您的方法:

//create a protocol
protocol SendPhoto {
    func sendPhotoToAssistant()
}

//add an extension of your protocol where Self is your UIViewController
extension SendPhoto where Self: UIViewController {
    func sendPhotoToAssistant() {
        //implement here your upload process
        //You now can present here your custom alert view
    }
}

然后为您的控制器采用SendPhoto协议,您可以在需要的地方调用该功能,例如:

class YourViewController: SendPhoto {

   override func viewDidLoad() {
       super.viewDidLoad()
       //this is an example call it where you need
       self.sendPhotoToAssistant()
   }
}