'UInt32' is not convertible to 'MirrorDisposition' - ios

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))

Related

Swift get value data from protocol

i need help with my code for swift 5,
so i make a struct and protocol to store list from uitextfield and now i wanna show that data in a UiTextView in another view controller
struct PatientNote {
var note : String
init(note :String) {
self.note = note
}
}
protocol AddNotesDelegate {
func AddNotes(controller : UIViewController, notes: PatientNote)
}
class AddNotesController: UIViewController {
var delegate : AddNotesDelegate!
#IBOutlet weak var Notes: UITextView!
#IBAction func addNotes(_ sender: Any) {
if let notes = self.Notes.text {
let patientNote = PatientNote(note: notes)
self.delegate.AddNotes(controller: self, notes: patientNote)
print(patientNote.note)
}
}
}
and now i wanna show in my view controller but i get this error of "Cannot convert value of type 'PatientNote' to expected argument type 'String'" in this viewController
class NotePatientController: UIViewController, AddNotesDelegate{
func AddNotes(controller: UIViewController, notes: PatientNote) {
let NotesPatient = PatientNote(note: notes) *this is where i get the error
}
var delegate : AddNotesDelegate!
var pasien : PatientNote!
override func viewDidLoad() {
super.viewDidLoad()
PatientTextView.text = pasien.note
}
#IBOutlet weak var PatientTextView: UITextView!
//in this ibaction i edit the notes that i get from the first Vc which is AddNotesController
#IBAction func Save(_ sender: UIButton) {
if let notes = self.PatientTextView.text {
let pasienNotes = PatientNote(note: notes)
self.delegate.AddNotes(controller: self, notes: pasienNotes)
}
}
}
i try to show the note from the AddNotesController to the NotePatientController, and in the NotePatientController i can edit and save the notes in UiTextView.
so i know i must be using the protocol in a wrong way, can someone help me how should i use it? im still kinda new in swift so could probably use any help i can get, Cheer!
Change let notesPatient = PatientNote(note: notes) to let notesPatient = PatientNote(note: notes.note)
It appears PatientNote takes a String as an argument but you passed an already created PatientNote to it instead. The below syntax, using notes.note would be a cleaner solution without involving initialising a new PatientNote.
func AddNotes(controller: UIViewController, notes: PatientNote) {
print(notes.note) // access the note String like this
}

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.

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

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.

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.

Resources