Ios “Any”不能转换为“UIView”
创建一个函数,使网格中的图像随机化。以下是导致问题的swift代码的一部分。感谢您的帮助Ios “Any”不能转换为“UIView”,ios,swift,xcode,swift3,Ios,Swift,Xcode,Swift3,创建一个函数,使网格中的图像随机化。以下是导致问题的swift代码的一部分。感谢您的帮助 class ViewController: UIViewController { var allImgViews = [Any]() var allCenters = [Any]() override func viewDidLoad() { //code random() } func random() { var centesC
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
}
}
}
您在代码中选择“any”有什么具体原因吗 因为就我在代码中所见,AllimgView似乎是UIImageView的数组,allCenters是CGPoints的数组
尽可能使用特定的数据类型。仅当您计划使用任意子类的不同类型的对象时才使用Any。您要查找的代码是
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.
}
如果确实不想将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
}
你为什么用[任何]?如果数组包含UIView,则将其声明为[UIView]谢谢您的帮助谢谢您的帮助很高兴它帮助了您。