在swift中运行此代码时出现类型不匹配错误

时间:2015-04-21 04:46:52

标签: swift casting ios8

我正在为其属性创建出口ImageView和一个自定义类“TTTImageView”。我想在所有ImageView上添加TapGestureRecognizer,但我发现了这个错误

“NSArray元素无法匹配Swift数组元素类型”

我的ViewController.swift类看起来像这样:

import UIKit

class ViewController: UIViewController {



@IBOutlet var fields: [TTTImageView]!

override func viewDidLoad() {
    super.viewDidLoad()
    self.setUpLogic()
            // Do any additional setup after loading the view, typically from a nib.
}

func setUpLogic(){
    for index in 0 ... fields.count-1{
        let gestureRecognizer = UITapGestureRecognizer(target: self, action: "fieldTapped")
        gestureRecognizer.numberOfTapsRequired = 1
        fields[index].addGestureRecognizer(gestureRecognizer)
    }
}

func fieldTapped(recognizer:UITapGestureRecognizer){

    var img = recognizer.view as TTTImageView
    img.setPlayer("x")


}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

和TTTImageView.swift是:

import UIKit

 class TTTImageView: UIImageView {
var player : String = String()

func setPlayer(player : String){
    self.player = player
    if(player == "x"){
        self.image = UIImage(named: "alphabet X")
    }
    else{
        self.image = UIImage(named: "alphabet O")
    }
}

}

我认为这是一个类型转换问题,但不知道如何解决。请让我摆脱这个问题。感谢

1 个答案:

答案 0 :(得分:0)

也许你想要的是这个

@IBOutlet var fields: [TTTImageView!]

而不是

@IBOutlet var fields: [TTTImageView]!

注意放置!字符。