How to solve Swift warning: "Constant 'value' inferred to have type 'AnyClass?' (aka 'Optional<AnyObject.Type>'), which may be unexpected"?

Viewed 144

Can't figure out why the compiler throws this warning

enter image description here

Any idea how to solve it?

func configure(with classesReuseRegistry: [String: AnyClass?]) {
    var collectionView = UICollectionView() // Temp collection var for testing purposes
    
    for (key, value) in classesReuseRegistry {
        collectionView.register(value, forCellWithReuseIdentifier: key)
    }
}

I also want to clarify, this warning was not present before. I had similar code on this library and it was never a problem.

1 Answers

You can silence the warning by modifying your code to:

func configure(with classesReuseRegistry: [String: AnyClass?]) {
    var collectionView = UICollectionView() // Temp collection var for testing purposes
    
    for classDict in classesReuseRegistry {
        collectionView.register(classDict.value, forCellWithReuseIdentifier: classDict.key)
    }
}

I think that the warning is caused by having AnyClass, which is a type alias, as dictionary value, and not a value type like Int, String, ...

Related