“Cannot assign to property: ”any“ is immutable” error

给你一囗甜甜゛ 提交于 2019-12-11 01:45:04

问题


tiledViewsStack contains UIImageViews. I'm trying to give each UIImageView in the array a new center coordinate. Not sure why I'm getting this error for the last line in the for loop...

    var tiledViewsStack = [AnyObject]()

    var randLocInt = Int()
    var randLoc = CGPoint()

    for var any in tiledViewsStack
    {
        randLocInt = Int((arc4random()*10) % 9) // 0, --- 8
        randLoc = allCenters[randLocInt].CGPointValue()
        any.center = randLoc
    }

回答1:


Needed to make tiledViewsStack a stack of UIImages, not AnyObjects. Changed var tiledViewsStack = [AnyObject]() to var tiledViewsStack = [UIImageView]().




回答2:


When you use Anyobject, you are using a protocol.

It can be an istance of any type. So AnyObject can represent an Int, a Float, a String, a UIView, anything.

The array [AnyObject] is a nonspecific type to represent any type of class. In you code you initialize an always immutable array, and when you try to modify each element you get the error..

The correct way to declare and initialize a type of this array is:

var genericTypeArray : [AnyObject] = [1, true, 1.2, "hello"]

For you code, you must change :

var tiledViewsStack = [AnyObject]()

with a code like my example up, or you modify AnyObject class with a specified class like UIImageView as recommended in comments.



来源:https://stackoverflow.com/questions/36525393/cannot-assign-to-property-any-is-immutable-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!