How does filter method work? - ios

-(instancetype)filter:(BOOL (^)(id value))block {
NSCParameterAssert(block != nil);
Class class = self.class;
return [[self flattenMap:^ id (id value) {
if (block(value)) {
return [class return:value];
} else {
return class.empty;
}
}] setNameWithFormat:#"[%#] -filter:", self.name];
}
This is the implementation of filter of ReactiveCocoa.I don't know what this code means.Also I can't get any reference to the second return method.
return [class return:value];
Also, what does this instancetype mean? Suppose the value is a string and I check whether its length is greater than 2. What will be returned by using filter method?

The filter method invokes the class method of the current class to get a RACStream subclass using that method. Using return: will give a signal that sends the value passed and then completes. Using empty gives a signal that immediately sends completed without sending a next value, which removes the value filtered value from the stream thanks to flattenMap: switching out the signal with the one being created.

Related

Why is the keyword "is" not functioning as expected when comparing classes?

I am using a redux pattern in my dart application. Inside the reducer the if statement that has the "is" keyword to figure out which action(in the form of a class) is being passed is not working at all.
DictionaryState dictionaryReducer(DictionaryState state, dynamic action){
if(action is RequestingDictionaryEntryAction){
// This if statement should be executed but it is not.
return _requestingDictionaryEntry(state);
}
if(action is ReceivedDictionaryEntryAction){
return _receivedDictionaryEntry(state, action);
}
return state;
}
When calling dictionaryReducer I am passing an action called RequestingDictionaryEntryAction and it is not being recognized as RequestingDictionaryEntryAction, instead the code continues to execute and the function does not return as it is supposed to.
Just off the top of my head, so don't put in too much faith, but your problem might lie in the "dynamic" type of the parameter causing the is operator to fail at compile-time. I would think it could be solved using:
DictionaryState dictionaryReducer(DictionaryState state, dynamic action){
if(action.runtimeType == RequestingDictionaryEntryAction){
return _requestingDictionaryEntry(state);
}
if(action.runtimeType == ReceivedDictionaryEntryAction){
return _receivedDictionaryEntry(state, action);
}
return state;
}
The problem was in the argument I was passing as action. I was not instantiating the class properly. I was passing the class declaration itself instead of an instant of it.
final action = RequestingDictionaryEntryAction instead of
final action = RequestingDictionaryEntryAction();
:D :D

Swift computed property return value

I have a computed property that is expected to return an object or nil if it fails.
var findRequest: Book {
get {
var foundRequest: Book!
API.requestBook(book: bookRequest) { book in
if book != nil {
foundRequest = book!
} else {
print("Could not find book")
foundRequest = nil
}
}
return foundRequest
}
}
When I run the code I get an unexpectedly found nil while unwrapping an Optional value error on the return foundRequest line. It looks like the code skips my closure function and goes straight to the return.
Thanks
There are several issues with your implementation. First of all, you shouldn't define foundRequest as an implicitly unwrapped optional if there is a possibility that its value will be nil. Second of all, you are returning the value outside the completion handler of the asynchronous function API.requestBook, so you are returning before foundRequest could get a value and hence you are returning the default value of nil, which will be force unwrapped due to the implicitly unwrapped optional declaration, hence the error.
Moreover, you shouldn't make an asynchronous request inside the getter of a computed property, since computed properties are supposed to return a value right away.
You should completely change your implementation to make findRequest a function returning a value of type Book inside a completion handler.
func findRequest(bookRequest: URLRequest, completion: #escaping (Book?->Void)){
API.requestBook(book: bookRequest) { book in
if let book = book {
completion(book)
} else {
print("Could not find book")
completion(nil)
}
}
}
You can call the function like this:
findRequest(bookRequest: yourRequest, completion: { book in
if let book = book {
//use the returned value
} else {
print("Book not found")
}
})
You might have to change the type of bookRequest from URLRequest depending on what the type of the input parameter book needs to be.
I have a computed property that is expected to return an object or nil if it fails.
Then you should probably define it as:
var findRequest: Book? {
// ...
(note the "?" after Book)
Also, like Martin mentioned in the comments, your computed property's getter is supposed to return a value right away, but you are making what looks like an asynchronous call to retrieve the value. The getter itself returns right away, before the completion handler is called. There is no way the side accessing the property will get the actual value returned by the API.

iOS. Passing block to block as parameter

I am going around blocks and try to discover the ways that they can be used.
So I am wondering is it possible to pass block to block like parameter?
Here is some sample code:
//declaration
static id (^someBlock)(id) = ^(id someClass) {
// do some stuff to obtain class some class instance
// check if class instance respond to #selector
// if yes - perform selector
}
//usage
+ (instancetype)someMethod {
someBlock(SomeClass.class);
// do additional work and return some instance type
}
This works fine, but is not good enough, because we obligate caller to respond to selector if caller want to do some additional stuff when someBlock is completed.
So my question is how I can invoke someBlock block with parameter block which I want to be executed when someBlock is completed.
Some like:
//declaration
static id (^someBlock)(id, <b>^otherBlock</b>) = ^(id someClass, <b>????</b>) {
// do some stuff to obtain class some class instance
otherBlock();
}
Any advice?
PS: Please note that the question is not about passing block to method as parameter.
Thanks,
Venelin
Is this what you are looking for?
static id (^someBlock)(id, void (^otherBlock)()) = ^id (id someClass, void (^otherBlock)()) {
otherBlock();
return nil; // just because you declares a `id` return type
};
And call it like
someBlock(someClass, ^() {
NSLog(#"other stuff");
});

Returning NULL Structure

I am calling a function which returns a structure of the type CvBox2D, however I want to check for an error in the function and return NULL if there is an error.
CvBox2D function()
{
...
if(ERROR)
return NULL;
...
}
I am getting an error : cannot convert from 'int' to 'CvBox2D'
Your function return type is CvBox2D, so you can't convert a (NULL) pointer to it.
If you really need to return "nothing" if the check inside the function fails, you can change the return type to a pointer to CvBox2D:
CvBox2D* function()
{
...
}
You will also have to change the way the returned object is created inside your function.
Note that using raw pointers in C++ usually isn't a good idea.
Take a look at std::shared_ptr (available in C++11) if you think you really have to use pointers.
If you want to return some error code, you can do the following:
int function(CvBox2D* output) {
// code...
// Assign to struct.
output->center = ...;
if (error) {
return RC_ERROR_FOO;
}
return RC_OK;
}
Then you call this function using a struct you've already allocated (for example, on the stack):
{
CvBox2D myBox;
int retval = function(&myBox);
if (RC_OK == retval) {
printf("Good! Angle of box: %g", myBox.angle);
} else {
printf("Error: %d", retval);
}
}
Where RC_OK, RC_ERROR_FOO are defined as constant integers, or better, as an enum (if you're using C++).
The other answers solve your problem, but if you want to keep the signature of your function, instead of returning an error code, you should throw an exception.

Overriding Doctrine enum default getter

In base class:
#method enum getWeightType() Returns the current record's
"weight_type" value
Subclass:
class Exercise extends BaseExercise
{
public function getWeightType()
{
$type = parent::getWeightType();
if ($type == 'free') {
return 'Wolny';
} else {
return 'Stacjonarny';
}
}
}
so basically I want to ouput values other than stores in database.
In indexSuccess:
echo $exercise->getWeightType()
I am getting error:
Fatal error: Maximum function nesting level of '100' reached, aborting
Could somebody give me any advice?
You need to use the protected method when overriding:
$type = $this->_get('weight_type');
Otherwise youre jsut going to run yourself in circles because its going to keep trying to call accessor method youre overriding never getting to a method that actually gets the internal value.

Resources