Learn

Classes, structs, and enums can also be generic, which means they can work with many different types. Here’s a simple example:

struct InformationWrapper<T> { var information: T }

When creating instances of generic types, the instance is locked into the type it used. It can’t be assigned to an instance of the same struct with a different underlying type.

var stringWrapper = InformationWrapper(information: “Hello!”) var intWrapper = InformationWrapper(information: 5) stringWrapper = InformationWrapper(information: 4.0) // ERROR: Cannot convert value of type 'Double' to expected argument type 'String'

Just like for generic functions, you can also specify that the type must conform to one or more protocols:

struct HashableInformationWrapper<T: Hashable> { var information: T }

Many structs in the Swift standard library are generic! Arrays are one major example. The syntax below isn’t as common, but is a valid way to define arrays:

let strArr: Array<String> = Array() let intArr: Array<Int> = Array()

Both strArr and intArr of of type Array. The type specified in angle braces states what kind of array it is. Just like for our custom struct InformationWrapper, once strArr is defined as an array of Strings, it can’t be assigned to an array of any other underlying type.

Instructions

1.

In the code editor is a definition for a GameResult struct that takes in two players and their scores, then has a printWinner() method that prints the winner. Press run to see what the code does now, then move onto the next step.

2.

This implementation only supports Ints, but some games, like chess, need to have scores of type Double. Genericize GameResult such that playerOneScore and ``playerTwoScorecan be of any type that conforms toComparable. UseScore` as the generic placeholder name.

3.

Create a contstant chessResult of type GameResult<Double> using type annotation. playerOne should be “Boris Spassky”, playerTwo should be “Bobby Fischer”, playerOneScore should be 8.5, and playerTwoScore should be 12.5.

4.

Call chessResult.printWinner() to see the victor!

Take this course for free

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?