Convert Objective C to Swift - objective-c

So i started learning swift directly and i'm trying to convert this objective C to swift but not sure exactly what it means, can someone explain it?
Side1 = ([[[ValueArray objectAtIndex:Counter-1] objectAtIndex:2] intValue] == 1)?-1:1;
where, Side = 0,ValueArray = [] and Counter = 0
Edit: Its in loop so counter++
Thanks

if ([[[ValueArray objectAtIndex:Counter-1] objectAtIndex:2] intValue] == 1) {
Side1 = -1
} else {
Side1 = 1
}
What is inside of ValueArray? Also, if Counter == 0 then getting objectAtIndex -1 will crash. But basically the swift version would be:
(ValueArray[Counter-1][2] as! NSString).intValue == 1
This makes a couple of assumptions, mainly that you're returning a String which we can force downcast to an NSString to take advantage of intValue.

This is shorthand for if-else. It can be used like so:
my_variable = (some_condition ? some_value : some_other_value)
This is equivalent to
if some_condition
my_variable = some_value
else
my_variable = some_other_value
It seems your code checks the integer value of an object in an array inside another array. It can be converted to Swift like so:
Side1 = (ValueArray[Counter - 1][2] as! Int == 1 ? -1 : 1)
As mentioned in a comment, this will crash if Counter is 0. I'm also assuming that ValueArray only contains objects that can be casted to Int. Swift is usually very picky about these things.
EDIT
If ValueArray contains strings, they can't be casted to Int. Cast to NSString first:
ValueArray[Counter - 1][2] as! NSString
and therefore the if shorthand becomes
Side1 = ((ValueArray[Counter - 1][2] as! NSString).intValue == 1 ? -1 : 1)

This does not always do the best job, but it can definitely help! It is a Objective-C to Swift converter.
Link https://objectivec2swift.com/#/converter/code

Related

Comparison between pointer and int (id to int) - Object wrapping still doesn't work [duplicate]

So my problem is this:
I am receiving a JSON string from across the network. When decoded (using SBJSON libraries), it becomes an NSDictionary that SHOULD contain a number of some sort for the key 'userid'. I say 'should' because when I compare the value to an int, or an NSINTEGER, or NSNumber, it never evaluates correctly.
Here is the comparison in code:
NSDictionary *userDictionary = [userInfo objectAtIndex:indexPath.row];
if ([userDictionary objectForKey:#"userid"] == -1) {
//Do stuff
}
The value inside the dictionary I am testing with is -1. When I print it out to console using NSLog it even shows it is -1. Yet when I compare it to -1 in the 'if' statement, it evaluates to false when it should be true. I've even tried comparing to [NSNumber numberWithInt: -1], and it still evaluates to false.
What am I doing wrong? Thanks in advance for your help!
You are comparing a pointer to an object, not an integer itself. You must first convert the object into an integer:
if ([[userDictionary objectForKey:#"userid"] integerValue] == -1)
{
//Do stuff
}

app crashes because of null values, swift 2

I'm trying to get data using JSON ad there is a null value causes crash.
let jsonData:NSDictionary = try NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers ) as! NSDictionary
let success:NSInteger = jsonData.valueForKey("success") as! NSInteger
//code error bad instruction
NSLog("Success: %ld", success);
how can I turn null to zero?
let success = (jsonData["success"] as? NSInteger) ?? 0
step by step:
get the value jsonData["success"] (please, don't use valueForKey, it does something completely different)
as? NSInteger - try to cast it to NSInteger or return nil if it's not a number (in this case, it's a NSNull instance)
?? 0 - if nil, use a default value of zero

Converting string to static constant

I have in my objective-c application a number of constants that I need to have inputted from an external source using strings. The reason of course, is that constants are better to work with, but can't be passed external.
I have made this objective-c code to convert, and it works 100%, but a) it is ugly, and b) quite obscure. I suppose I could have converted to NSNumber and made an array, but that seems like a lot of code/processing (though maybe the right solution)
Can anyone provide a better solution?
NSArray *types = #[#"text_input",#"textbox",#"select",#"yesno",#"date",#"signature",#"label",#"SectionHeading"];
int indexes[10];
indexes[0] = FieldTypeTextInput;
indexes[1] = FieldTypeTextBox;
indexes[2] = FieldTypeSelect;
indexes[3] = FieldTypeYesNo;
indexes[4] = FieldTypeDate;
indexes[5] = FieldTypeSignature;
indexes[6] = FieldTypeLabel;
indexes[7] = FieldTypeSectionHeading;
for (int i=0;i<[types count];i++)
{
NSString *string_i = [types objectAtIndex:i];
if ([type_string isEqualToString:string_i])
I suggest to use an NSDictionary.
enum YourNiceTypes : NSInteger {FieldNotFound, FieldTypeTextInput, FieldTypeTextBox, ...};
NSDictionary *types = #{"text_input" : #(FieldTypeTextInput), ... };
enum YourNiceType type = [types[textInput] integerValue];
You used the trick to define wrong input with zero, which will be handled automatically correctly, as calling integerValue on a nil object will return 0.

Comparing NSNumber to 0 not working?

I have a JSON parser in my app, and I load the value into a detailDataSourceDict variable. When I try to get the valueForKey of the array and try to compare it to 0, it never works...
Here's my code:
if (indexPath.row == 1) {
NSNumber *rating = [detailDataSourceDict valueForKey:#"rating"];
NSLog(#"Rating: %#",rating);
if (rating == 0) {
cell.detailTextLabel.text = #"This sheet has not yet been rated.";
}
else {
cell.detailTextLabel.text = [NSString stringWithFormat:#"This sheet has a %# star rating.",rating];
}
cell.textLabel.text = #"Rating";
}
I see in my JSON feed that "rating":"0", but when the rating is 0, it shows "This sheet has a 0 star rating.", instead of "This sheet has not yet been rated."
Any suggestions? Thanks.
NSNumber *rating is an object. 0 is a primitive type.
Primitive types can be compared with ==. Objects cannot; they need to be compared for equality using isEqual:.
Thus replace this:
rating == 0
with:
[rating isEqual:#0]
(#0 being a NSNumber literal)
or alternatively:
rating.integerValue == 0
The reason why your wrong code even compiles is that 0 is equal to 0x0 which in turn is equal to nil (kind of, sparing the details).
So, your current code would be equivalent to this:
rating == nil
rating is a pointer to an NSNumber object, if you compare with == 0, you'll be comparing the pointer only.
If you want to compare the value with 0, you'll have to get the actual value using intValue, try;
if ([rating intValue] == 0) {
NSNumber is an object and you have to access it's value with the value accessors.
[NSNumber intValue];
See "Accessing Numeric Values" #:
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNumber_Class/Reference/Reference.html
You want to change it from:
if (rating == 0) {
To
if ([rating intValue] == 0) {

How do i compare string and integer?

i have basicly no knowledge of objective c, but how do i make a if statement to see if SourceTypeString is equal to 1 or 2?
NSString* sourceTypeString = [arguments objectAtIndex:2];
UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera; // default
NSLog(#"my ns string = %#",sourceTypeString);
//NEWBIE PART
if ((sourceTypeString == 1))
{
NSLog(#"equals 1");
sourceType = (UIImagePickerControllerSourceType)[sourceTypeString intValue];
} else {
NSLog(#"equals 2");
sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
}
//NEWBIE PART
My code crashes and gives me
my ns string = 1
(lldb)
sourceTypeString __NSCFNumber * 0x0013bf80 (int)1
if ([sourceTypeString intValue] == 1)
You can call intValue on an NSString to get its value as an int, if it is possible to do so with the given string. Then you can compare those.
You can't directly compare ints to strings. However, you can use NSString's isEqualToString to check if the first strings value is equal to the string value of the number.
if ([sourceTypeString isEqualToString:#"1"]) {
//
}