I am getting errors such as " braced block of statements is an unused closure" and expected expression - ios

This is my first time doing a simple project in swift and these errors are bugging me for last couple of hours. I have this code below and even though i have curly braces around and statements inside the if/else i still get that errors. Any help would be greatly appreciated guys.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var `switch`: UISwitch!
#IBOutlet var Answer: UILabel!
#IBOutlet var tempInput: UITextField!
//aqnswer value
#IBAction func switchPressed(sender: AnyObject)
{
if switch.on {
self.Answer.text = "cel to fah"
}
else {
self.Answer.text = "fah to cel"
}
}
//textfield value
#IBAction func calculate(sender: AnyObject)
{
//get user input
// value = celcius
var Value:Int = tempInput.text.toInt()!
var toFah :Int = ( 32 + Value * 9 ) / 5
//to celcius
var toCel: Int = (Value-32) * 5 / 9
if switch.on {
self.Answer.text = toFah.description
}
else {
self.Answer.text = toCel.description
}
// println(fah)
// Answer.text = fah.description
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

The Swift Language Guide says:
If you need to give a constant or variable the same name as a reserved
Swift keyword, surround the keyword with back ticks (`) when using it
as a name. However, avoid using keywords as names unless you have
absolutely no choice.
In your example you have indeed a choice…
But if you really really really want to use switch as a variable name you have to wrap all occurrences of switch in back ticks.

Related

Cannot find the error in this sequence. Thread 1: signal SIGABRT

I have just started to code, but I have already encountered some error which I cannot figure out. Would you please help me?
class ViewController: UIViewController {
#IBOutlet var getNumber: UITextField!
#IBAction func computePrime(_ sender: AnyObject) {
if let userString = getNumber.text { // Convert input to Int
let userNumber = Int(userString)
if let number = userNumber {
var i = 2 // Variable declaration
var prime = true
while i < number { // Prime calculation
if number & i == 0 {
prime = false
i = number
} else {
i += 1
}
}
if prime == false { // Output result
displayResult.text = "It is not prime"
} else {
displayResult.text = "It is prime"
}
} else {
displayResult.text = "Please enter a positive whole number" // Error message in case value entered is not good
}
}
}
#IBOutlet var displayResult: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
When I try to run it, the app crashes and it gives me this error:
"Thread 1: signal SIGABRT"
highlighting this line:
"class AppDelegate: UIResponder, UIApplicationDelegate {"
from the AppDelegate.swift file, which I have not modified.
How can I fix it?
Thank you!
Probably you don't have connected in Storyboard the getNumber and displayResult (IBOutlet) object.
Check that answer:
IBOutlet not connecting in SWIFT
The highlighted line is at the application delegate because the system regressed all the way back to the top trying to find a layer with an exception handler for the exception that was thrown. Check the last few lines of the Xcode console for a description of the exception which may tell you where it was caused.
You can add an "Exception Breakpoint" to stop execution at the moment of the exception to see the point of origin. Many articles exist on how to do this.

Use of unresolved identifier when creating a string

I am very new to swift, but i can work with javascript and php so thought this would make sense to me. I have read so many posts on this topic but non really explain mine. I have the following code which is pretty straight forward. I have several text fields with login information to pass on to php. But when i try to use the var from a function it is not possible. So i figured that out but when i try to redefine the vars outside of the function with different var i am still keep getting the error. This is the code so far
import UIKit
class RegisterPage: UIViewController, UITextFieldDelegate{
#IBOutlet weak var userEmailTextField: UITextField!
#IBOutlet weak var userPasswordTextField: UITextField!
#IBOutlet weak var userPasswordConfirmTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func registerTapped(sender: AnyObject) {
let userEmail = userEmailTextField.text
let userPassword = userPasswordTextField.text
let userConfirmPassword = userPasswordConfirmTextField.text
// check for empty fields
if(userEmail.isEmpty || userPassword.isEmpty || userConfirmPassword.isEmpty)
{
// Display alert message
displayMyAlertMessage("Alle velden gelieve invullen");
return;
}
//Check if passwords match
if(userPassword != userConfirmPassword){
// Display alert message
displayMyAlertMessage("Wachtwoorden komen niet overeen");
return;
}
}// end of registerTapped button
// send data to server side
static var urlConn: NSURL = NSURL(string: "http://xxxxxxxxx")!
var request: NSMutableURLRequest = NSMutableURLRequest(URL:urlConn);
var credLogin = "email=\(userEmail)&password=\(userPassword)"
the following line is giving the unresolved identifier error
var credLogin = "email=\(userEmail)&password=\(userPassword)"
i have tried so many different things, but i can't move the var in the function outside of it, and i have had also in other code blocks errors like this, i really would like to know how this works in swift.
Thanks
The variables userEmail and userPassword are declared within the scope of the registerTapped method. They are not visible outside this method.
Either put the line
var credLogin = "email=\(userEmail)&password=\(userPassword)"
in the method or declare the variables as instance variables right after IBOutlet declarations.
The code to send data to server side must be also executed within a method.

Xcode 7 beta 2 and swift not getting along

I have an error when I typed in some code, it gave me an error. It looks perfect, but here is the code:
import UIKit
class SecondViewController: UIViewController {
#IBOutlet weak var resultLabel: UILabel!
#IBOutlet weak var tempText1: UITextField!
#IBAction func convertTemp1(sender: AnyObject) {
#let fahrenheit = (tempText1.text as NSString).doubleValue
let celsius = (fahrenheit - 32 )/1.8
let resultText = "Celsius \(celsius)"
resultLabel.text = resultText
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
It give me the following error: 'String?' is not convertable to 'NSString' On the line I put a # on. The # is not in the real code.
Note: I do not understand much computer talk so please try to speak very simply. :)
The text property of UITextField returns an optional string but your code doesn't handle optionals. Casting to NSString isn't allowed there (also not necessary to get to the doubleValue).
You need to handle the optional. For this you could force-unwrap it using !. But that can lead to crashes. It would be better to use the if let or guard let statements:
guard let fahrenheit = tempText1.text?.doubleValue else { return }
For conciseness we use optional chaining (the ?here). We could also keep this in two steps:
guard let fahrenheitString = tempText1.text else { return }
let fahrenheit = fahrenheitString.doubleValue
Both are basically equivalent.

'UInt32' is not convertible to 'MirrorDisposition'

EDIT:
Ok. I just changed my code as: var randomX = Int(arc4random()%6) Wish i could think of it before posting here :|
I took accepted answer of this topic as reference: Swift convert UInt to Int
I've been trying to make a simple ios guessing app with swift. I'm generating a random number and getting another number from user and comparing both. But i'm stuck with this error: 'UInt32' is not convertible to 'MirrorDisposition' while comparing two integers (one of them converted from string to integer by toInt() method)
Below you can see my ui, my code, two stackoverflow topics i read and how i changed my code after reading those topics.
UI: (i couldn't resize the image)
my code:
import UIKit
class ViewController: UIViewController {
#IBOutlet var myImageView: UIImageView!
#IBOutlet var inputField: UITextField!
#IBAction func clickedGuessButtonAction(sender: AnyObject) {
println("Guess button clicked")
var randomX = arc4random()%6
println("randomX = \(randomX)")
var guess = inputField.text.toInt()
if((inputField.text) != nil){
if(guess == randomX){
println("correct")
var image = UIImage(named: "images/tick.png");
myImageView.image=image;
self.view.addSubview(myImageView); // what is this?
inputField.resignFirstResponder();// hides keyboard
}
else
{
println("wrong")
var image = UIImage(named: "images/cross.png")
myImageView.image=image;
self.view.addSubview(myImageView);
inputField.resignFirstResponder();//hides keyboard
}
}
else{
println("invalid input. requires integer only")
inputField.resignFirstResponder();// hides keyboard
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I found these topics on stackoverflow:
float is not convertible to 'MirrorDisposition' Swift What is mirrordisposition?
iOS Swift Error: 'T' is not convertible to 'MirrorDisposition'
First one especially has an extended answer finally suggesting if intValue == Int(floatValue)
Than i changed var guess = inputField.text.toInt()
to var guess = Int(inputField.text);
But this time i'm getting an error message like this: Cannot invoke 'init' with an argument of type '#lvalue String!'
This time, i searched this error message but couldn't find anything helpful. It shouldn't be this difficult to compare 2 integers. I'm definitely missing something easy. Any ideas?
Try changing:
var randomX = arc4random()%6
to
var randomX = Int(arc4random()%6)
this should do it
let sizeX = UInt32(6)
let randomX = CGFloat(arc4random_uniform(sizeX))

How to call a function from a different function?

I'm trying to make a simple app that counts the characters of a textfield, but when the user inputs the text, the function that converts the user-inputed string into a var and the function that counts the characters are executed at once. Here's the code:
import UIKit
class ViewController: UIViewController {
#IBOutlet var myTextField : UITextField
#IBOutlet var userTextField : UITextField
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
myTextField.text = fullConstant
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func modifyMyVariable(sender : AnyObject) {
myVariable = userTextField.text
}
#IBAction func clickMe(sender : AnyObject) {
countCharacters(&fullConstant)
println(fullConstant)
myTextField.text = fullConstant
}
}
And here's the "OtherFile.swift" where the functions are located:
import Foundation
var fullConstant = "Type something!"
var myVariable = ""
func modifyMyVariable() {
println()
}
func countCharacters(inout fullConstant: String) {
let FirstPart = "There are "
let LastPart = " characters"
var numberOfCharacters = countElements(myVariable)
switch numberOfCharacters {
case 0 :
fullConstant = "There isn't any character yet"
case 1 :
fullConstant = "There is just one character"
default :
fullConstant = FirstPart + String(numberOfCharacters) + LastPart
}
}
Both functions execute as soon the userTextField is edited, but if the user inputs one character, the countCharacters function takes the var myVariable before it's modified by the function modifyMyvariable, so it doesn't count the last character added.
To solve this, I've thought that I could call the function countCharacters from the function modifyMyVariable, so the variable myVariable has already changed when it counts the characters.
Change the following and see if it's then easier to fix your problem.
You should always only link each event to one IBAction. Your IBActions shouldn't be named after what you're trying to do in them; they should be named after the event that triggers them. For example, "modifyMyVariable" should be called "textEdited" or similar.
In that "textEdited" method, do all the work you need to do. If you need to call another function, call it from there instead of linking to two IBActions.
Put code in your "OtherFile" inside a
class OtherFile {
}
block, and hold an instance to that class as a variable in your view controller. You want to avoid declaring global functions outside of classes.
Not related, but name your constants using camelCase with first letter lower case, just like your variables. So FirstPart should be firstPart.
Avoid using 'inout' as much as possible. Each language has it's conventions; in ObjC and Swift, pass in values needed to do work, and return values that result from that work. So:
func countCharacters(text: String) -> (String)
Putting it all together, your 'modifyMyVariable' function (which should really be called 'textEdited') will look something like this:
myVariable = userTextField.text
let characterCount = self.myOtherFileInstance.countCharacters(myVariable)
myTextField.text = characterCount
and the other function (clickMe) should be deleted.

Resources