Initialization of immutable value error on Swift? - swift

I am trying to create an app where you can chose the type of chemistry you are interested in and it will give you information on that type. The only problem is that I am getting a error message stating the following:
Initialization of immature value 'chemistry' was never used.
On this block of code:
override func viewDidLoad() {
super.viewDidLoad()
chemistryArray = [chemistryLabel0, chemistryLabel1, chemistryLabel2, chemistryLabel3, chemistryLabel4]
for index in 0..<chemistryArray.count {
let chemistry = chemistryArray[index]
}
}
On this line:
let chemistry = chemistryArray[index]
I was wondering what this error message means and how to fix it.
Any suggestions or input is grealty appreciated
Thanks in advance

I think every other loop you declare chemistry again and never use it inside the loop. And as I was corrected this variable is not seen outside the scope of the for-loop.
So the purpose of the for-loop is ambiguous.
Sorry, I would rather comment but I cannot yet.

As Martin R already explained, you are declaring and populating the constant chemistry but you are not using it.
Since chemistry is declared within the { } of the for loop, it does exist only inside that scope.
So the compiler, looking at your code, cannot figure out (me neither :) the meaning of your code and it is producing a warning to grab your attention.
In other words the compiler is telling you something like:
Dear coder,
I will compile this code but are you sure it is correct? Because this instruction does not make sense to me.
Regards
The compiler
The fixing
To fix the warning you just need to use the constant or remove it.
Now my question
Why are you declaring and populating a constant and you are not using it?

Related

Does #discardableResult actually lead to compiler optimizations?

I have an assignment operation that I want to also return the new value my object is assigned, but only optionally. So of course I would add the #discardableResult attribute. However, does this actually tell the compiler to ignore the return statement inside my function definition if it is not actually being passed anywhere? What optimization does this attribute actually do? All the documentation says is that it "suppresses the warning," although I only want to use it if it can be easily optimized.
Any help is appreciated!

fatal error: unexpectedly found nil while unwrapping an Optional value with toInt()

I am getting the error that is in the title, when I run my code. The main problem occurs in the code below. I don't really understand what is going on. I started (and completed) this project to make a bingo tracker in swift during the beta, but apparently the syntax changed or something. I would prefer an easy fix with an explanation of why my solution does not work any more. I provided all of my code and would appreciate if no one reused it, but I can not really stop you. Thank for the help.
if ((newCardB1?.text.toInt()) != nil) // this is not nil
{
println(newCardB1?.text); // this prints out "Optional("1") when i run it but i only want the 1
}
else
{
println("error" );
}
let B1: Int = "\(newCardB1?.text)".toInt()!; //this is where the problem starts
let B2: Int = "\(newCardB2?.text)".toInt()!;
PS: I have limited programming experience with swift, but a lot with Java. Any tips on the switching back and forth would also be appreciated and feel free to state any other problems or bad coding techniques so that I am able to fix them.
Change all the statements of the type let B1: Int = "(newCardB1?.text)".toInt()!; to this template: let B1: Int = (newCardB1?.text)!.toInt()!. The reason is: newCardB1?.text is already a string. If you interpolate it using "()", I am not sure where it ends up. Also note the ! in (newCardB1?.text)!. The code will not compile without it.
With regard to your style, it is clear you are from Java. Semicolons are rarely needed in Swift. Other than that the style is fine. Perhaps a little verbose.

Using LuaJ with Scala

I am attempting to use LuaJ with Scala. Most things work (actually all things work if you do them correctly!) but the simple task of setting object values has become incredibly complicated thanks to Scala's setter implementation.
Scala:
class TestObject {
var x: Int = 0
}
Lua:
function myTestFunction(testObject)
testObject.x = 3
end
If I execute the script or line containing this Lua function and pass a coerced instance of TestObject to myTestFunction this causes an error in LuaJ. LuaJ is trying to direct-write the value, and Scala requires you to go through the implicitly-defined setter (with the horrible name x_=, which is not valid Lua so even attempting to call that as a function makes your Lua not parse).
As I said, there are workarounds for this, such as defining your own setter or using the #BeanProperty markup. They just make code that should be easy to write much more complicated:
Lua:
function myTestFunction(testObject)
testObject.setX(testObject, 3)
end
Does anybody know of a way to get luaj to implicitly call the setter for such assignments? Or where I might look in the luaj source code to perhaps implement such a thing?
Thanks!
I must admit that I'm not too familiar with LuaJ, but the first thing that comes to my mind regarding your issue is to wrap the objects within proxy tables to ease interaction with the API. Depending upon what sort of needs you have, this solution may or may not be the best, but it could be a good temporary fix.
local mt = {}
function mt:__index(k)
return self.o[k] -- Define how your getters work here.
end
function mt:__newindex(k, v)
return self.o[k .. '_='](v) -- "object.k_=(v)"
end
local function proxy(o)
return setmetatable({o = o}, mt)
end
-- ...
function myTestFunction(testObject)
testObject = proxy(testObject)
testObject.x = 3
end
I believe this may be the least invasive way to solve your problem. As for modifying LuaJ's source code to better suit your needs, I had a quick look through the documentation and source code and found this, this, and this. My best guess says that line 71 of JavaInstance.java is where you'll find what you need to change, if Scala requires a different way of setting values.
f.set(m_instance, CoerceLuaToJava.coerce(value, f.getType()));
Perhaps you should use the method syntax:
testObject:setX(3)
Note the colon ':' instead of the dot '.' which can be hard to distinguish in some editors.
This has the same effect as the function call:
testObject.setX(testObject, 3)
but is more readable.
It can also be used to call static methods on classes:
luajava.bindClass("java.net.InetAddress"):getLocalHost():getHostName()
The part to the left of the ':' is evaluated once, so a statement such as
x = abc[d+e+f]:foo()
will be evaluated as if it were
local tmp = abc[d+e+f]
x = tmp.foo(tmp)

Execute a "prepared" math operation in Objective-C

I want to to math operations with some kind of prepared formula that would look like tan(%f)*1000 or %f+%f where the %f has to be replaced by an argument.
Is there a function in Objective-C that I can pass the format of my formula and the required numbers to execute this prepared operation?
I hope the problem is described understandable, if not, leave a comment.
Thanks in advance.
Edit 1: Thanks for your answers so far, but I'm looking for something more dynamic. The block and inline function is great, but to static. I also understand that this may be something hard to achieve out of the box.
You may be interested in DDMathParser, found here. I believe it will do everything you're looking for.
There is nothing that would do it this way, however what you could do is rewrite your "format" into a function, and just pass the arguments it needs to have, much faster and much easier.
inline float add(float p_x,float p_y)
{ return p_x+p_y; }
inline is a compiler feature that you can use to speed things up. It will replace the function call with the code it executes when you compile. This will result in a lager binary though.
If I understand your question correctly, Objective-C Blocks are great for this.
typedef double (^CalcBlock)(double);
CalcBlock myBlock = ^(double input) {
return (tan(input) * 1000);
};
NSLog(#"Result: %f", myBlock(M_PI_2));
You can pass the block that contains your algorithm to other objects or methods.

iPhone SDK: Please explain why "nil ==" is different than "== nil"

I have been programming iPhone SDK for around 6 months but am a bit confused about a couple of things...one of which I am asking here:
Why are the following considered different?
if (varOrObject == nil)
{
}
vs
if (nil == varOrObject)
{
}
Coming from a perl background this is confusing to me...
Can someone please explain why one of the two (the second) would be true whereas the first would not if the two routines are placed one after the other within code. varOrObject would not have changed between the two if statements.
There is no specific code this is happening in, just that I have read in a lot of places that the two statements are different, but not why.
Thanks in advance.
They are the same. What you have read is probably talking about if you mistakenly write == as =, the former will assign the value to the variable and the if condition will be false, while the latter would be a compile time error:
if (variable = nil) // assigns nil to variable, not an error.
if (nil = variable) // compile time error
The latter gives you the chance to correct the mistake at compile time.
They might be different if you are using Objective-C++ and you were overriding the '==' operator for the object.
They are exactly the same, it is just a style difference. One would never be true if the other is false.
if it's a recommendation that you use the latter, it's because the second is easier to catch if you accidentally type =. otherwise, they are identical and your book is wrong.
They can only be different if the "==" - Operator is overloaded.
Let's say someone redefines "==" for a list, so that the content of two lists is checked rather than the memory adress (like "equals() in Java). Now the same person could theoretically define that "emptyList == NULL".
Now (emptyList==NULL) would be true but (NULL==emptyList) would still be false.