Swift If program - swift

Still a beginner with just playing around with some basic functions in swift.
Can someone tell me what is wrong with this code?
import UIKit
var guessInt: Int
var randomNum = arc4random_uniform(10)
if Int(randomNum) == guessInt {
println ("correct")
} else {
println; "no, the number is not. guess again"
}
So far the only error I'm getting is that
guessInt
is being used before being initialized!
I've tried to type everything again but still have the same error.
Thanks in advance.

In Swift you cannot read a value before it's set, which you're doing here:
if Int(randomNum) == guessInt
If you change your declaration from this:
var guessInt:Int
to this:
var guessInt = 6
then your code will work as expected (assuming you want the user's guess to be 6).

You've declared guessInt but now you need to initialize, or set it to some initial value.
For example:
let guessInt = 3

Another option is to declare guessInt as an "Optional", meaning that it can be nil, in fact it will be initialized to nil. This will print "no, ...." until you assign guessInit to a non nil value in the range of values produced by arc4random_uniform(10), but it will compile and run cleanly.
var guessInt:Int? // note the ? after Int this marks it as an Optional
var randomNum = arc4random_uniform(10)
if Int(randomNum) == guessInt {
println ("correct")
} else {
println; "no, the number is not. guess again"
}

Related

Swift3 optionals chaining in IF conditions bug?

This code worked just fine in Swift 2.3 and I don't understand why I have to unwrap TestClass to check if number is bigger than 4. This is whole point of chaining optionals, to save additional call.
Now to make this work, I have to check if testClass != nil (or use implicit unwrap with if let statement) and then check count.
Is this really the only way?
import UIKit
class testClass
{
var optionalInt:Int?
}
var test:testClass?
if test?.optionalInt > 4
{
}
It's not a bug. It is, alas, intentional. Implicit unwrapping of optionals in comparisons (>) has been removed from the language.
So, the problem now is that what's on the left side of the > is an Optional, and you can no longer compare that directly to 4. You have to unwrap it and get an Int, one way or another.
First of all, where are you initialising your test var? Of course it'll be nil if you don't give it a value!
And regarding optional chaining, what's the issue writing :
if let optionalInt = test?.optionalInt, optionalInt > 4
{
}
As always, safety > brevity.
Optional comparison operators are removed from Swift 3.
SE-0121
You need to write something like this:
if test?.optionalInt ?? 0 > 4
{
}
This could also happen on Guard statement.
Example:
var playerLevels = ["Harry": 25, "Steve": 28, "Bob": 0]
for (playerName, playerLevel) in playerLevels {
guard playerLevels > 0 else {//ERROR !!
print("Player \(playerName) you need to do the tutorial again !")
continue
}
print("Player \(playerName) is at Level \(playerLevels)")
}

Type 'Int' does not conform to protocol 'BooleanType'?

I know there is another thread with the same question, but it doesn't tell what is actually causing the problem
Im new to swift, so Im a bit confused on this.
I wrote a very simple program that is supposed to start with a default number of followers (0) and assign that to 'defaultfollowers' and once that becomes 1 its supposed become "followers", but I get the error "Type 'Int' does not conform to protocol 'BooleanType'". What is causing this and why
var followerdeafault = 0
var followers = 0
if (followerdeafault++){
var followers = followerdeafault
}
In Swift you can't implicitly substitute Int instead of Bool. This was done to prevent confusion and make code more readable.
So instead of this
let x = 10
if x { /* do something */ }
You have to write this:
let x = 10
if x != 0 { /* do something */ }
Also you can't pass an Optional instead of Bool to check if it's nil, as you would do in Objective-C. Use explicit comparison instead:
if myObject != nil { /* do something */ }
As the comments said, you're trying to use an Int in a Bool comparison statement. What you're looking for is probably something like this:
if followerdeafuaut++ == 1 { ... }
Also side note: the ++ operator is deprecated, moving towards using +=

What am I overlooking as I attempt to account for nil?

I've reread the Swift documentation a number of times, but I'm afraid I'm overlooking something simple here.
The function below processes just fine and properly calls the updateCalorieBalance method if there is value in the field caloriesConsumed.text. But, of course, crashes if caloriesConsumed.text is nil.
The error message I get is: fatal error: unexpectedly found nil while unwrapping an Optional value.
Your assistance is greatly appreciated.
#IBAction func buttonThree(sender: AnyObject) {
var calConsumed: String?
if let calConsumed = caloriesConsumed.text {
calorieCount.updateCalorieBalance(Double(calConsumed)!)
balanceLabel.text = "New Balance: \(Int((calorieCount.getCalorieBalance())))"
} else {
balanceLabel.text = "Please enter calories to add."
}
caloriesConsumed.resignFirstResponder()
}
calConsumed should not be an optional string. Actually, "if let" creates its own variable so you now have two variables with the same name...
Double (calConsumed) returns nil if calConsumed is an empty string or a string not containing a number. The ! that you use will make it crash.
if let calText = caloriesConsumed.text,
calNumber = Double (calText) {
...
}
(Not tested or even compiled).

Conditional instructions in swift

I am trying to write in swift something that should be very basic, but I can't seem to get a handle on it :
First, I create a global variable. For example:
var xx:Int
Then, I want to create a conditional instruction. Something like :
if (xx == 1){
//do something
}
else if (xx == 2) {
//do something else
}
I can do this very easily in Objective-C, but I can't seem to be able to do it in Swift. I have looked everywhere, and don't seem to find the answer.
With the code you provided you're probably getting the error: "Variable xx used before initialized". This is happening because the declaration of the variable is incomplete, you neither gave a value to the variable nor told the compiler it is an optional. You have three options:
Give a initial value to it; var xx: Int = //value here
Declare it as an optional (doing this you say that it may not have a value, if it does the code will be executed, if it doesn't it won't); var xx: Int?
Force unwrap the variable (it still an optional, but if you force-unwrap it you're assuring the compiler that the variable will have a value when needed, otherwise it'll crash); var xx: Int!
Or you can say var xx = Int() that way it's initialized and the default initialization is equal to 0. This is different than the other answers and allows you to have a value from the get go if you're not sure what value might be assigned during runtime.
In addition to the other poster's point that you must assign an initial value before you can use xx, you also need to lose the parentheses around the condition in your if statement:
var xx:Int
xx = 2
if xx == 1
{
//do something
}
else if xx == 2
{
//do something else
}

is the init method not working properly in swift

With the code below, the local songs variable is never able to be iterated despite all the checks to the contrary ( println shows the value stored ). The other thing is that the Xcode debugger seems to jump all over the place in the init method.
let gLibraryManager = LibraryManager()
class LibraryManager {
var Songs = Dictionary<String, String>()
init() {
println("struct being initialized from NSDefaults")
let userDefaults = NSUserDefaults.standardUserDefaults();
var result:AnyObject = userDefaults.objectForKey(LIKED_LIST)
println(result)
var local = result as? Dictionary<String,String>
if local != nil {
println("local not nil: \(local!)")
for (id,title) in local! {
Songs[id] = title
}
if Songs.count > 0 {
println("NSDefaults detected: \(Songs)")
} else {
println("no NSDefaults detected. Initializing empty")
}
}
}
ok. i figured out what is was.
I had set the Swift Compiler - Code Generation. Optimization level to -Fastest. This was to prevent the extremely slow creation of Dictionaries.
However, it appears this breaks the ability to iterate structures.
It also seems to resolve the weird bouncing around of breakpoints.
This was a needle in a haystack that tooks many hours. I guess the moral of the story is not to mess with compiler flags yet.