To create a generic struct in Swift, you need to use type parameters. Type parameters are placeholders for types that will be specified when the struct is used. Here's an example of a simple generic struct that uses a type parameter:
main.swift215 chars12 lines
In this example, the MyStack
struct has a type parameter T
. This means that when you use MyStack
, you can specify what type to use for T
. For example, you could create a stack of strings like this:
main.swift107 chars5 lines
The MyStack
struct also demonstrates type constraints. In this case, the push
method of the struct requires that the element being pushed is of type T
by specifying the type parameter T
after the function name. Similarly, the pop
method returns an optional value of type T
.
You can use type constraints to specify that the type parameter should conform to certain protocols. For example, if you only want to allow types that can be added together, you can add the Numeric
protocol as a type constraint:
main.swift97 chars6 lines
Now you can use the MyAddition
struct to add together any types that conform to Numeric
, such as integers or floating-point numbers:
main.swift67 chars3 lines
gistlibby LogSnag