Thor
Thor

Reputation: 10038

When using typealias, I get the compiler error "use of undeclared type"

I'm new to Swift and is trying to learn the concept of Type Aliases. I tried to compile the code below:

var x = 23
typealias y = x // compiler output: use of undeclared type x
print(y)

However, the compiler tell me "use of undeclared type x".

I'm very confused by why this is happening. I thought Swift can implicitly infer to the variable type. Is there something I'm missing?

Upvotes: 1

Views: 910

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236340

You can use typealias to make it easier for you declaring more complex types for example:

typealias RGBA = (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat)

let redColor: RGBA = (1.0, 0.0, 0.0, 1.0)

redColor.red    // 1
redColor.green  // 0
redColor.blue   // 0
redColor.alpha  // 1

typealias CMYK =  (cyan: CGFloat, magenta: CGFloat, yellow: CGFloat, black: CGFloat)

let cyanColor: CMYK = (1.0, 0.0, 0.0, 0.0)

cyanColor.cyan     // 1
cyanColor.magenta  // 0
cyanColor.yellow   // 0
cyanColor.black    // 0

Upvotes: 3

Related Questions