Swift let computed property to Objective C syntax - objective-c

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

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

How to declare a C function with an undetermined return type?

Can I declare a C function with an undetermined return type (without C compiler warning)? The return type could be int, float, double, void *, etc.
undetermined_return_type miscellaneousFunction(undetermined_return_type inputValue);
And you can use this function in other functions to return a value (although that could be a run time error):
BOOL isHappy(int feel){
return miscellaneousFunction(feel);
};
float percentage(float sales){
return miscellaneousFunction(sales);
};
What I'm looking for:
To declare and to implement a C function (or Obj-C method) with an undefined-return-type could be useful for aspect-oriented programming.
If I could intercept Obj-C messages in another function in run time, I might return the value of that message to the original receiver or not with doing something else action. For example:
- (unknown_return_type) interceptMessage:(unknown_return_type retValOfMessage){
// I may print the value here
// No idea how to print the retValOfMessage (I mark the code with %???)
print ("The message has been intercepted, and the return value of the message is %???", retValOfMessage);
// Or do something you want (e.g. lock/unlock, database open/close, and so on).
// And you might modify the retValOfMessage before returning.
return retValOfMessage;
}
So I can intercept the original message with a little addition:
// Original Method
- (int) isHappy{
return [self calculateHowHappyNow];
}
// With Interception
- (int) isHappy{
// This would print the information on the console.
return [self interceptMessage:[self calculateHowHappyNow]];
}
You can use a void * type.
Then for example:
float percentage(float sales){
return *(float *) miscellaneousFunction(sales);
}
Be sure not to return a pointer to a object with automatic storage duration.
You may use the preprocessor.
#include <stdio.h>
#define FUNC(return_type, name, arg) \
return_type name(return_type arg) \
{ \
return miscellaneousFunction(arg); \
}
FUNC(float, undefined_return_func, arg)
int main(int argc, char *argv[])
{
printf("\n %f \n", undefined_return_func(3.14159));
return 0;
}
May be a union as suggested by thejh
typedef struct
{
enum {
INT,
FLOAT,
DOUBLE
} ret_type;
union
{
double d;
float f;
int i;
} ret_val;
} any_type;
any_type miscellaneousFunction(any_type inputValue) {/*return inputValue;*/}
any_type isHappy(any_type feel){
return miscellaneousFunction(feel);
}
any_type percentage(any_type sales){
return miscellaneousFunction(sales);
}
Here with ret_type you can know data type of return value and ret_type. i,f,d can give you corresponding value.
All elements will use same memory space and only one should be accessed.
Straight C doesn't support dynamically-typed variables (variants) since it is statically typed, but there might be some libraries that do what you want.

Why can't you assign and call a block at the same time?

The following code compiles:
^{}();
And this compiles:
void (^x)();
(x = ^{})();
But this doesn't:
(void (^x)() = ^{})();
The error I get is Expected ')'. Is this a bug with llvm or something? It's totally holding me back from pretending Objective-C is JavaScript.
This wouldn't make sense in a C-like language. To see why, let's build the statement from the ground up.
First, we'll use your working declaration for x:
void (^x)();
Now let's initialize it in the same statement:
void (^x)() = ^{};
So far so good - x has been initialized with the correct block. So let's invoke x now. But where will the () go? Naturally, we need to place the () immediately after a block-valued expression. However, in C, declarations are statements, not expressions so
(void (^x)() = ^{})();
doesn't make sense. The only place the () can go is after the ^{}:
void (^x)() = ^{}();
But ^{}() has type void, not type void (^)().
To sum up: you can't declare a block variable and invoke it at the same time. you'll have to either declare and initialize the variable, and then call it
void (^x)() = ^{};
x();
or declare it and then assign and call it
void (^x)();
(x = ^{})();
or just separate all three:
void (^x)();
x = ^{};
x();
As a concluding thought, let's say it was desirable to declare and invoke blocks at the same time. If we decided to allow code like (void (^x)() = ^{})();, then for the sake of consistency, we would have to also allow code such as ++(void x = 4); or (void x = 1) + (void y = 2);. I hope you'll agree that these just look strange in C.
As an analogy, consider:
This compiles:
if (42) { }
And this compiles:
int x;
if (x = 42) { }
But this doesn't:
if (int x = 42) { }

Objective C equivalent of C method signature

I want make a function to include in my code to calculate percentages.
In Php, it's :
function percent(a,b){
return a/b*100;
}
In Objective C, I don't know. I tried:
-(void)percent(a,b){
return a/b*100;
}
But there are 2 errors. Could you me explain how to make it work?
Thank you for you help
A method is defined in a slightly different syntax than you're used to:
- (float)percentWithA:(float)a dividedByB:(float)b
{
return a / b * 100;
}
The parameters are "strewn" throughout the method call. For instance, this method's name would be percentWithA:dividedByB:. You don't need to be as explicit as this call, however. For example, you could do this:
- (float)percent:(float)a :(float)b { /* ... */ }
But it doesn't provide much context.
The more correct way to do this will be:
- (float)precentageByDevidingFloat:(float)a byFloat:(float)b {
float returnValue = 0;
if (b != 0)
returnValue = a / b * 100;
return returnValue;
}
This way you use a more correct naming convention , you actually return a float and your safe in case some one gave you the value 0 in B.
(which should be covered by documentation)
You could also do it like this, with a C function:
// in your .h
float percent(float a, float b);
// in your .m or .c
float percent(float a, float b)
{
return a / b * 100.0f;
}
Or, if you are into macros:
// remember to always enclose macros in parentheses
#define percent(a, b) (a / b * 100.0f)
And you would call it like this:
percent(50, 20);
Objective-C uses a strange convention of having parameter names as part of a method name and therefore parameter declarations are embedded in a method name.
-(float)percentOf:(float)a over:(float)b
{
return (a/b) * 100.0;
}
The first type in parentheses defines the return type, the parameters come after colons and also have their type in parentheses.

Convert methods from Java-actionscript to ObjectiveC

I'm tring to convert the following 3 methods from java-actionscript to Objective C.
Part of my confusion I think is not knowing what Number types, primitives I should be using. ie in actionscript you have only Number, int, and uint. These are the 3 functions I am trying to convert
public function normalize(value:Number, minimum:Number, maximum:Number):Number
{
return (value - minimum) / (maximum - minimum);
}
public function interpolate(normValue:Number, minimum:Number, maximum:Number):Number
{
return minimum + (maximum - minimum) * normValue;
}
public function map(value:Number, min1:Number, max1:Number, min2:Number, max2:Number):Number
{
return interpolate( normalize(value, min1, max1), min2, max2);
}
This is what I have so far
-(float) normalize:(float*)value
withMinimumValue:(float*)minimum
withMaximumValue:(float*)maximum
{
return (value - minimum) / (maximum - minimum);
}
-(float) interpolate:(float*)normValue
withMinimumValue:(float*)minimum
withMaximumValue:(float*)maximum
{
return minimum + (maximum - minimum) * normValue;
}
-(float) map:(float*)value
withMinimumValue1:(float*)min1
withMaximumValue1:(float*)max1
withMinimumValue2:(float*)min2
withMaximumValue2:(float*)max2
{
return interpolate( normalize(value, min1, max1), min2, max2);
}
If you're looking for a primitive type (not an object) that can handle non-integer values, float is probably fine (or CGFloat, as suggested by Chris)
unless your functions need to modify their arguments, you want the arguments to be just float not float *.
you are mixing up Objective-C message passing and plain C function invocation syntax: your example declares them as instance methods, but you're calling them like a function (won't work).
To match your declarations, the invocation would look something like:
return [self interpolate:
[self normalize:value withMinimumValue:min1 withMaximumValue:max1]
withMinimumValue:min2
withMaximumValue:max2];
Because your interpolate, normalize, and map methods do not rely on any variables from the current object instance, they might be better off as objective-C class methods (or even as plain C functions).
Given that none of your methods require any other state to work, all are basic math kinda stuff, and all are pretty straightforward, I would skip Objective-C entirely and just go with straight C. Something like:
static inline float normalize(float val, float min, float max) {
return (val - min) / (max - min);
}
Stick that in a header file somewhere in your project and be done with it. Do the same for interpolate and map.
Note: as others have mentioned, you might want to change the type to CGFloat, if needed.
Assuming you're using Apple's frameworks, these are the conversions you'll probably want to use:
Number =~ CGFloat
int =~ NSInteger
uint =~ NSUInteger

function with multiple arguments

how to pass multiple arguments in a single function in Objective-C? I want to pass 2 integer values and the return value is also integer. I want to use the new Objective-C syntax, not the old C/C++ syntax.
In objective-c it is really super easy. Here is the way you would do it in C:
int functName(int arg1, int arg2)
{
// Do something crazy!
return someInt;
}
This still works in objective-c because of it's compatibility with C, but the objective-c way to do it is:
// Somewhere in your method declarations:
- (int)methodName:(int)arg1 withArg2:(int)arg2
{
// Do something crazy!
return someInt;
}
// To pass those arguments to the method in your program somewhere:
[objectWithOurMethod methodName:int1 withArg2:int2];
Best of luck!
Since this is still google-able and there are better solutions than the accepted answer; there's no need for the hideous withArg2 – just use colons:
Declaration:
#interface
-(void) setValues: (int)v1 : (int)v2;
Definition:
#implementation
-(void) setValues: (int)v1 : (int)v2 {
//do something with v1 and v2
}
Like this:
int sum(int a, int b) {
return a + b;
}
Called like this:
int result;
result = sum(3, 5);
// result is now 8
More here
int add (int a, int b)
{
int c;
c = a + b;
return c;
}
link text