Search code examples
swiftobjectforeachpropertiestext-alignment

Do text alignment in a for each statement not compiling


In my swift code below it uses a forEach statement. The problem is some of the items in the the set can not do a text alightment. For example a text alignment is not possible in a uiimageview. So I tried to write a code of something that might possibly work but a compile error does occur. You can see what I tried to code in the comment block below.

override func viewDidLoad() {
        super.viewDidLoad()
        [player1Score,player2Score,clearBtn,player1UpBTN,player1DownBtn,player2UpBTN,player2DownBtn,play1Lbl, play2Lbl,play1text,play2text,resetBtn,resetBtn,GameLabel,GameText,gameIncrease,gameDecrease,submit].forEach{
        $0.translatesAutoresizingMaskIntoConstraints = false
        $0.layer.borderWidth = 1
        view.addSubview($0)
        $0.backgroundColor = UIColor(
            red: .random(in: 0.0...1),
            green: .random(in: 0.0...1),
            blue: .random(in: 0.0...1),
            alpha: 1
            

             //part of cocde I tried that does not work
            if $0 is = UITextField {
                $0.textalignment = .cent
            }
        )
     
    }

Solution

  • First off, you're missing a closing paren on your call to UIColor.

    Next, your if statement. Since your array of objects are of different types, the array is going to be of type Array<Any>. Your if $0 is UITextField means "only execute the body of this if statement if the current object being iterated is of type UITextField. The compiler won't then treat $0 as being of that type however.

    Instead of using if $0 is <type>, I would use if let optional binding to create a new local variable of type UITextField:

    override func viewDidLoad() {
        super.viewDidLoad()
        [player1Score,player2Score,clearBtn,player1UpBTN,player1DownBtn,player2UpBTN,player2DownBtn,play1Lbl, play2Lbl,play1text,play2text,resetBtn,resetBtn,GameLabel,GameText,gameIncrease,gameDecrease,submit].forEach{
            $0.translatesAutoresizingMaskIntoConstraints = false
            $0.layer.borderWidth = 1
            view.addSubview($0)
            $0.backgroundColor = UIColor(
                red: .random(in: 0.0...1),
                green: .random(in: 0.0...1),
                blue: .random(in: 0.0...1),
                alpha: 1
            )
            if let textfield = $0 as? UITextField {
                // if the if let succeeds, `textField` will be 
                // a var of the correct type
                textfield.textalignment = .cent
            }
        }