Checking if array contains two objects - ios

I'm attempting to implement the containsObject but with two parameters, is this possible?
Currently I've got:
if ([ myArray containsObject:#"Object1", #"Object2"]){
return result;
} else {
return NO;
}
and apparently there's too many arguments. I've delved through Apple's docs but I'm yet to find anything. Any suggestions?

Why not just do this?
if ([ myArray containsObject:#"Object1" ] && [ myArray containsObject:#"Object 2" ] ){
return result;
} else {
return NO;
}

There is too many arguments, containsObject is for a single object. (You can read its official documentation here) To fix your problem, use the && operator and call containsObject on each object individually.
if ([myArray containsObject:#"Object1"] && [myArray containsObject#"Object2"]){
return result;
} else {
return NO;
}

You will have to evaluate them individually. Example:
bool MONNSArrayContainsAllObjectsIn(NSArray* const pArray, NSArray* const pSought) {
assert(pArray);
assert(pSought);
assert(0 < pSought.count);
for (id at in pSought) {
if (false == [pArray containsObject:at]) {
return false;
}
}
return true;
}
Then your code above becomes:
return MONNSArrayContainsAllObjectsIn(myArray, #[#"Object1", #"Object2"]);
If you are working with a known number of elements (2 in this case), then you can avoid creating the temporary array -- if you prefer to make that optimization and write out all variants you need, including parameters. Other answers detail this approach.
If you have large arrays and many comparisons to perform, NSSet may be better suited for your task.

Related

Equivalent of tuples in Dart [duplicate]

Is there a way to return several values in a function return statement (other than returning an object) like we can do in Go (or some other languages)?
For example, in Go we can do:
func vals() (int, int) {
return 3, 7
}
Can this be done in Dart? Something like this:
int, String foo() {
return 42, "foobar";
}
Dart doesn't support multiple return values.
You can return an array,
List foo() {
return [42, "foobar"];
}
or if you want the values be typed use a Tuple class like the package https://pub.dartlang.org/packages/tuple provides.
See also either for a way to return a value or an error.
I'd like to add that one of the main use-cases for multiple return values in Go is error handling which Dart handle's in its own way with Exceptions and failed promises.
Of course this leaves a few other use-cases, so let's see how code looks when using explicit tuples:
import 'package:tuple/tuple.dart';
Tuple2<int, String> demo() {
return new Tuple2(42, "life is good");
}
void main() {
final result = demo();
if (result.item1 > 20) {
print(result.item2);
}
}
Not quite as concise, but it's clean and expressive code. What I like most about it is that it doesn't need to change much once your quick experimental project really takes off and you start adding features and need to add more structure to keep on top of things.
class FormatResult {
bool changed;
String result;
FormatResult(this.changed, this.result);
}
FormatResult powerFormatter(String text) {
bool changed = false;
String result = text;
// secret implementation magic
// ...
return new FormatResult(changed, result);
}
void main() {
String draftCode = "print('Hello World.');";
final reformatted = powerFormatter(draftCode);
if (reformatted.changed) {
// some expensive operation involving servers in the cloud.
}
}
So, yes, it's not much of an improvement over Java, but it works, it is clear, and reasonably efficient for building UIs. And I really like how I can quickly hack things together (sometimes starting on DartPad in a break at work) and then add structure later when I know that the project will live on and grow.
Create a class:
import 'dart:core';
class Tuple<T1, T2> {
final T1 item1;
final T2 item2;
Tuple({
this.item1,
this.item2,
});
factory Tuple.fromJson(Map<String, dynamic> json) {
return Tuple(
item1: json['item1'],
item2: json['item2'],
);
}
}
Call it however you want!
Tuple<double, double>(i1, i2);
or
Tuple<double, double>.fromJson(jsonData);
You can create a class to return multiple values
Ej:
class NewClass {
final int number;
final String text;
NewClass(this.number, this.text);
}
Function that generates the values:
NewClass buildValues() {
return NewClass(42, 'foobar');
}
Print:
void printValues() {
print('${this.buildValues().number} ${this.buildValues().text}');
// 42 foobar
}
The proper way to return multiple values would be to store those values in a class, whether your own custom class or a Tuple. However, defining a separate class for every function is very inconvenient, and using Tuples can be error-prone since the members won't have meaningful names.
Another (admittedly gross and not very Dart-istic) approach is try to mimic the output-parameter approach typically used by C and C++. For example:
class OutputParameter<T> {
T value;
OutputParameter(this.value);
}
void foo(
OutputParameter<int> intOut,
OutputParameter<String>? optionalStringOut,
) {
intOut.value = 42;
optionalStringOut?.value = 'foobar';
}
void main() {
var theInt = OutputParameter(0);
var theString = OutputParameter('');
foo(theInt, theString);
print(theInt.value); // Prints: 42
print(theString.value); // Prints: foobar
}
It certainly can be a bit inconvenient for callers to have to use variable.value everywhere, but in some cases it might be worth the trade-off.
you can use dartz package for Returning multiple data types
https://www.youtube.com/watch?v=8yMXUC4W1cc&t=110s
Dart is finalizing records, a fancier tuple essentially.
Should be in a stable release a month from the time of writing.
I'll try to update, it's already available with experiments flags.
you can use Set<Object> for returning multiple values,
Set<object> foo() {
return {'my string',0}
}
print(foo().first) //prints 'my string'
print(foo().last) //prints 0
In this type of situation in Dart, an easy solution could return a list then accessing the returned list as per your requirement. You can access the specific value by the index or the whole list by a simple for loop.
List func() {
return [false, 30, "Ashraful"];
}
void main() {
final list = func();
// to access specific list item
var item = list[2];
// to check runtime type
print(item.runtimeType);
// to access the whole list
for(int i=0; i<list.length; i++) {
print(list[i]);
}
}

forEach instead of for loop

I am dealing with this function to see whether a certain number is in an array of numbers. If it is it should return true otherwise false.
I have this piece of code, that is perfectly working below. However, could you simplify it even more(e.g. avoid using a for loop and instead use forEach?)
Thanks
function findNumber(number){
for (var i=0;i<array.length;i++){
if (array[i] === number){
return true }
}
return false
}
Something that semantically is similar to your code and "looks functional" could be:
const findNumber = number => array.includes(number);
There really is no reason to use Array.prototype.forEach. And to be honest, in a "truly functional style" the Array.prototype.forEach is almost never used (since its purpose is to make side effects, and that is what you try to avoid with choosing FP).
References:
Array.prototype.includes()
Arrow functions
function findNumber(arr, number){
var result = false;
arr.forEach(function(item, index){
if(item === number) result = true;
});
return result;
}
Btw. I think it would be easier and more simple to simply use Array.prototype.indexOf() or Array.prototype.includes() methods.
// I guess var array is already declared
function findNumber(number){
let test = false
array.forEach(function(nbr){
if(nbr ==(=) number ){
test = true
}
})
if(test == true) {
return true
} else {
return false
}
}

Chaining promises on PromiseKit

I'm trying to chain a number of promises that need to be resolved before returning.
In my case, for each element of databaseResult I need to fetch some data with a method that returns a promise.
Once I've fetched the data for every single element of the array I need to return to the calling method.
var toReturn = [MatchModel]()
//get my array of data
let databaseResults = MatchDatabaseManager.getMatchList();
//not sure what I'm doing
var promise = dispatch_promise{ 0 }
if(databaseResults.count > 0) {
return Promise { fulfill, reject in
for index in 0..<databaseResults.count {
print(index)
promise = promise.then { y -> Promise<Int> in
//Fetch the data I need ...
DataProvider.getUserProfileWithUserId(
(databaseResults[y].partnerUserProfile?.userId)!)
.then {(model) in {
//and use it to create the data I need to return
toReturn.append(MatchModel(realmModel:
databaseResults[y], partnerProfile: model))
}
}
return dispatch_promise { index }
}
}
//Once all the promises are fulfilled, toReturn contains the data I need and I can return it
promise.then{ x in {
fulfill(toReturn)
}
}
}
}
If I run this I get
PromiseKit: Pending Promise deallocated! This is usually a bug
I have very little experience with PromiseKit and documentation / exaples are scarce, so I have no idea what I'm missing here.
After asking the library developer for some help, I found out one must use "when" to wait for a series of promises to be completed.
The solution to the problem then becomes
return when(databaseResults.map{ (dbresult : MatchRealmModel) in
return DataProvider.getUserProfileWithUserId((dbresult.partnerUserProfile?.userId)!).then { model in
return MatchModel(realmModel: dbresult, partnerProfile: model)
}
})
I also found that a when() call with an empty array as the parameter can cause this issue.

Finding out whether ObjectAtIndex returns an object

Is there a way to write some sort of catch statement around ([MyArray ObjectAtIndex:myindexpath.row])so that I can run this without throwing an exception?
In other words, I want to write this sort of expression:
if ([MyArray ObjectAtIndex:myindexpath.row]) {
// do some stuff if the object is in the array
else {
// do some other stuff
}
Sure: use logic & maths.
if (index < myArray.count) {
// ...
}

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.

Resources