Swift let computed property to Objective C syntax

Viewed 331

I have this code in a Swift application and was curious of what its equivalent syntax would be in Objective C

typealias Signal = (Float) -> (Float)

static let sine: Signal = { (time: Float) -> Float in
    return amplitude * sin(2.0 * Float.pi * frequency * time)
}

I believe I would declare Signal as follows:

typedef float (^Signal)(float);

but I am not sure how I would setup a similar way of setting up the syntax to retrieve the value. I thought about a class method but the didn't quite work out.

Thank you

1 Answers

This is not a computed property. This is a “closure”.

So this defines a type alias for a closure that takes a Float as a parameter and returns a Float:

typealias Signal = (Float) -> (Float)

You can create an instance of this Signal closure like so:

let doubler: Signal = { $0 * 2 }

And you can call that closure like so:

print(doubler(21))     // 42

The equivalent Objective-C syntax to define the type for a “block”:

typedef float (^Signal)(float);

To create an instance of a Signal block:

Signal doubler = ^(float input) {
    return input * 2;
};

And to call it:

NSLog(@"%f", doubler(21));   // 42
Related