My path to learning Swift

Other Swift Idiosyncrasies encountered in Noughts and Crosses

The first version of Noughts and Crosses can be found here.

In the function computerMoves we have:

for view in self.view.subviews as! [UIView] {     // 1
    if let btn = view as? UIButton {              // 2
        if btn.currentTitle == "+" {              // 3
            btn.setTitle("O", forState: .Normal)  // 4
            let x:Int = btn.tag / 3
            let y:Int = btn.tag % 3
            OandX.makeMove(x, y: y, player: false)
            break
        }
    }
}

Peculiar to Swift/IOS are ‘as!‘, ‘as?‘, UIViewUIButton and subviews. For an understanding of how IOS handles it’s display, I read Apple’s documentation on the UIView class and an overview of Windows and Views. For an explanation of why ‘as!‘ is used, I read Apple’s documentation on Type Casting, and a helpful discussion, also by Apple. I also checked up on Optionals at  Apple, and by Andrew Wagner.

Referring to the code above:

  1. Each button, slider, label, etc is referred to as a view. All of these controls on the main view (superview) are known as the subviews. Hence, line 1 loops through all of the controls on the superview. Also, since we know that there are subviews, I have used the explicitly unwrap version of as, i.e. as! [Note that UIView is an optional type.]
  2. UIButton is an optional. Therefore, the ‘as‘ must be an ‘as!‘ or an ‘as?‘. I used ‘as?‘ just to be in the safe side, and the compiler recommended it.
  3. The currentTitle property returns the title that is displayed on the UIButton. See the Apple documentation for other title properties.
  4. The setTitle method takes the following forState parameters: .Normal, .Highlighted, .Disabled, .Selected, .Application, and .Reserved.

One thought on “My path to learning Swift”

Leave a Reply

Your email address will not be published. Required fields are marked *