'任何'是不可转换为' UIView'

时间:2017-04-29 10:56:15

标签: ios swift xcode swift3

创建一个函数来随机化网格中的图像。以下是导致问题的快速代码的一部分。任何帮助表示赞赏。

    class ViewController: UIViewController {
    var allImgViews = [Any]()
    var allCenters = [Any]()

    override func viewDidLoad() {
    //code
    random()
    }

    func random() {
    var centesCopy: [Any] = allCenters
    var randLocInt: Int
    var randLoc: CGPoint
    for any: UIView in allImgViews {
        randLocInt = arc4random() % centersCopy.count
        randLoc = allCenters[randLocInt].cgPoint()
        any.center = randLoc
    }
}
   }

3 个答案:

答案 0 :(得分:1)

您是否有任何特殊原因需要' 任何'你的代码?

因为在我的代码中我可以看到 allImgViews 似乎是 UIImageView allCenters 的数组是的数组CGPoints

尝试尽可能使用特定数据类型。仅当您计划使用 Any 的不同类别子对象时,才使用 Any

答案 1 :(得分:1)

您正在寻找的代码是

for view in allImgViews as! [UIView] {
        // add your logic here
        // 'view' here is a UIView object
    }

建议:如果您已经知道该数组仅包含UIView对象,那么最好将其声明为如下所示

var allImgViews = [UIView]()

for view in allImgViews {
    // here the compiler already knows 'view' is a UIView object
    // no need for type casting. 
    //add your logic. 
}

答案 2 :(得分:1)

如果您真的不想将 allCenter 声明为 CGPoint 而将 allImgViews 声明为 UIImageView ,你可以试试这个。 。

func random() {

        var centesCopy: [Any] = allCenters
        var randLocInt: Int
        var randLoc: CGPoint
        for index in stride(from: 0, to: allImgViews.count, by: 1)  {
            randLocInt = Int (arc4random()) % centesCopy.count
            randLoc = self.allCenters[randLocInt] as! CGPoint
            var any = UIView()
            any.center = randLoc
            allImgViews[index] = any
        }