繁体   English   中英

Swift:无法在Protocol Extension中使用变异方法

[英]Swift: Can't use mutating method in Protocol Extension

我有4个视图控制器,需要根据用户屏幕宽度使用不同的图像。 我正在尝试保持代码DRY并使用协议扩展。

以下是我的协议:

import UIKit

enum ScreenWidths: CGFloat {
        case iPhone455s = 320.0
        case iPhone6 = 375.0
        case iPhone6Plus = 414.0
}

protocol ScreenSizeProtocolExt {
    mutating func setupBG() -> String    
}


extension ScreenSizeProtocolExt {
    mutating func setupBG() -> String {
        let imageName: String
        let userScreenWidth = UIScreen.mainScreen().bounds.width

        switch userScreenWidth {
        case ScreenSizeWidth.iPhone455s.rawValue:
            imageName = "imageA"
        case ScreenSizeWidth.iPhone6.rawValue:
            imageName = "imageB"
        case ScreenSizeWidth.iPhone6Plus.rawValue:
            imageName = "imageC"
        default:
            imageName = "imageAll"
        }

        return imageName
    }
}

现在,我正在尝试使用它:

extension myViewController: ScreenSizeProtocolExt {

let imageToUse = setupBG()
// Here is get an error: 'Use of instance member 'setupBG' on type 'inout Self'; did you mean to use a value of type 'inout self' instead?
let image = UIImage(named: imageToUse)
imageView.image = image

}

如何使用协议扩展来检测屏幕宽度并为我提供正确的imageName以便使用。

这段代码:

extension myViewController: ScreenSizeProtocolExt {    
let imageToUse = setupBG()
// Here is get an error: 'Use of instance member 'setupBG' on type 'inout Self'; did you mean to use a value of type 'inout self' instead?
let image = UIImage(named: imageToUse)
imageView.image = image    
}

不合法 最主要的是扩展不能添加新的存储属性-因此您不能这样做:

let imageToUse = setupBG()

在扩展中。

另外,这一行:

imageView.image = image 

func之外是非法的。

至于您在这里需要什么,这一切似乎都不过分。 为什么要使用协议将其扩展到viewControllers? 您有一个返回imageName的函数-可以在任何地方(只是免费的func,不在类中)。

然后,在viewControllers中,只需将图像视图的图像设置为此函数返回的名称即可。

扩展是为类提供更多接口的一种方法-您不能使类仅通过扩展自动调用方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM