Bonjour à tous, quelqu'un pourrait traduire et m'expliquer d'une façon la plus simple possible ce qui est écrit ici:
Initializers can have quite a few keywords associated with them. A designated initializer indicates that it’s one of the primary initializers for a class; any initializer within a class must ultimately call through to a designated initializer. A convenience initializer is a secondary initializer, which adds additional behavior or customization, but must eventually call through to a designated initializer. Designated and convenience initializers are indicated with the designated and convenience keywords, respectively.
A required keyword next to an initializer indicates that every subclass of the class that has that initializer must implement its own version of the initializer (if it implements any initializer).
Type casting is a way to check the type of an instance, and to treat that instance as if it’s a different superclass or subclass from somewhere else in its own class hierarchy.
A constant or variable of a certain class type may actually refer to an instance of a subclass behind the scenes. Where you believe this is the case, you can try to downcast to the subclass type using a type cast operator.
Because downcasting can fail, the type cast operator comes in two different forms. The optional form, as?, returns an optional value of the type you are trying to downcast to. The forced form, as!, attempts the downcast and force-unwraps the result as a single compound action.
Use the optional type cast operator (as?) when you’re not sure if the downcast will succeed. This form of the operator will always return an optional value, and the value will be nil if the downcast was not possible. This lets you check for a successful downcast.
Use the forced type cast operator (as!) only when you’re sure that the downcast will always succeed. This form of the operator will trigger a runtime error if you try to downcast to an incorrect class type.
This example shows the use of the optional type cast operator (as?) to check whether a shape in an array of shapes is a circle or a square. You increment the count of the squares and triangles variables by one each time the corresponding shape is found, printing the values at the end.
Voici le code associé:
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 class Triangle: NamedShape { init(sideLength: Double, name: String) { super.init(name: name) numberOfSides = 3 } } let shapesArray = [Triangle(sideLength: 1.5, name: "triangle1"), Triangle(sideLength: 4.2, name: "triangle2"), Square(sideLength: 3.2, name: "square1"), Square(sideLength: 2.7, name: "square2")] var squares = 0 var triangles = 0 for shape in shapesArray { if let square = shape as? Square { squares++ } else if let triangle = shape as? Triangle { triangles++ } } print("\(squares) squares and \(triangles) triangles.")
Partager