This question already has answers here:
Converting String to Int with Swift
(31 answers)
Closed 5 years ago.
I'm having some difficulty getting one of my view controllers to recognize a text input. I'm getting the "Cannot convert value of type 'String' to expected argument type 'Int'" error. I've seen some questions on stack overflow regarding the String/Int conversion but none that seemed to fix this specific situation.
The user is expected to input a number into the text field to set the value of pointsNeededText. The parameters of class Goal, however, state that the variable is an Int. How can I have the user type in a number into the text field and have it recognized as an Int? I set the keyboard type for that specific text field to be the number pad. Is this even the best way to do this? Should it be set up as something other than a text field? I'm a rookie at this, so any and all help would be greatly appreciated! Thank you!
import UIKit
class AddGoalsTableViewController: UITableViewController {
var goal:Goal?
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "SaveGoal" {
goal = Goal(goalText: nameOfRewardText.text!, pointsToCompleteGoal: pointsNeededText.text!, pointsEarnedTowardsGoal: goalProgressText.text!)
}
}
#IBOutlet var goalTableTitleText : UILabel!
#IBOutlet weak var goalProgressText: UILabel!
#IBOutlet weak var nameOfRewardText: UITextField!
#IBOutlet weak var pointsNeededText: UITextField!
#IBOutlet weak var repeatSwitch: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
If the initializer for the Goal class needs the values as Int, you need to explicitly cast it from String to Int for it to work.
let integerValue = Int(stringValue)
Note that this generates an optional value, and thus, has to be unwrapped if your Goal init doesn't accept optionals.
Related
I apologize if this has been asked before but I couldn't find what I was looking for online over the last few hours. I'm still functional a noob with swift.
I am trying to store the stringValue of a TextField when I click a NSButton. If I click anywhere and then click on the NSButton the code works perfect but if I don't click the stringValue is still reporting the previous value.
#IBOutlet weak var NameText: NSTextField!
#IBOutlet weak var SaveChangesAccountButton: NSButton!
var selectedAccountItemNumber = NSInteger()
#IBAction func SaveAccountChanges(_ sender: Any)
{
let AccountName = NameText.stringValue
AccountingData.instance.book.account[selectedAccountItemNumber].name = AccountName
}
You have to call validateEditing() on the text field.
And please conform to the naming convention that variable and function names start with a lowercase letter and don't use NSInteger in Swift.
#IBOutlet weak var nameText: NSTextField!
#IBOutlet weak var saveChangesAccountButton: NSButton!
var selectedAccountItemNumber = 0
#IBAction func saveAccountChanges(_ sender: Any)
{
nameText.validateEditing()
let accountName = nameText.stringValue
AccountingData.instance.book.account[selectedAccountItemNumber].name = accountName
}
I would like to have a user input numbers and then have a calculation as the result. I have succeeded with this but I would like the user to be able to input doubles if they want too and also have the result be a double. This is my issue. I have an input TextField box and a Label result. So two Outlets. So the code I have pasted below works but only for whole numbers (ints) Hope this makes sense. Any ideas? Keep in mind I am a newbie to Swift Programming. cheers
using Xcode:
#IBOutlet weak var userInput: NSTextField!
#IBOutlet weak var result: NSTextField!
var value = 100
#IBAction func pushButtonforResult(_ sender: Any) {
result.integerValue = value / userInput.integerValue
}
I am currently making a calculator, and I am using Swift, with XCode 8. I have already defined a variable, but when I want to connect it to my button and text field, it says use of unresolved identifier. Can anyone help me?
Screenshot:
Your sum variable is defined inside the Solve function scope, so it can only be used inside that scope. You have to make your variable global (i.e. inside the UIViewController scope) for it to be visible inside all the functions.
Define var sum outside the function, under Oranges.
class ViewController : UIViewController {
#IBOutlet weak var Apples :UITextField!
#IBOutlet weak var Oranges :UITextField!
var sum : String!
#IBAction func Solve(_ sender: AnyObject)
{
var apples = Int(Apples.text!)
var oranges = Int(Oranges.text!)
sum = String(oranges! + apples!)
}
}
This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 6 years ago.
Firstly, I'm very new to Swift, so keep that in mind before you berate my question for being an easy problem to solve.
I'm trying to use a button to send the contents of text field to a table. This bit of code defines the variable and you can see the sender:
import UIKit
var bookTitle:String!
class secondViewController: UIViewController {
#IBOutlet weak var titleField: UITextField!
#IBAction func addBook(sender: AnyObject) {
bookTitle = (titleField.text)!
}
This is the code where I'm receiving the error message:
import UIKit
var cellContent = ["Book 1", "Book 2", "Book 3", "Book 4"]
class firstViewController: UIViewController, UITableViewDelegate {
#IBOutlet weak var table: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
cellContent.insert(bookTitle, atIndex: 0)
//THIS IS THE ERROR: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellContent.count
}
From searching online, I think the problem is that the variable "bookTitle" is nil, but I'm not sure how to fix that.
It's because of your
var bookTitle:String!
Because you are accessing it before it was set. You can check that using the didSet.
var bookTitle: String! {
didSet {
print("did set called")
}
}
You should use this declaration instead:
var bookTitle: String?
It's much safer because you have to unwrap your variable when accessing it. You should read the Swift documentation chapter about optional and explicit types.
For reference:
Because the value of an implicitly unwrapped optional is automatically unwrapped when you use it, there’s no need to use the ! operator to unwrap it. That said, if you try to use an implicitly unwrapped optional that has a value of nil, you’ll get a runtime error.
See: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Types.html#//apple_ref/doc/uid/TP40014097-CH31-ID445
Chapter: Implicitly Unwrapped Optional Type
XCODE: Swift
Full Error:
Could not find initializer for type TableCell that accepts an argument list of type caseImage: (UIImge, caseName: String, caseDate: String)
var patientCaseArray = [TableCell]()
func loadSampleData() {
let Photo1 = UIImage(named: "retino1")!
let case1 = TableCell(caseImage: Photo1, caseName: "John Smith", caseDate: "2015-10-18" )
//error
patientCaseArray = [case1]
}
Working on a table cell class defined elsewhere, with this set of IBOutlets:
#IBOutlet weak var caseImage: UIImageView!
#IBOutlet weak var caseName: UILabel!
#IBOutlet weak var caseDate: UILabel!
I haven't done anything to the class except add the outlets.
I'm very new to swift and I'm going through a tutorial which says this is supposed to compile fine. It isn't supposed to input to the table yet. What am I missing?
Thanks in advance.
You have a discrepancy in types:
Could not find initializer for type 'TableCell' that accepts an
argument list of type caseImage: '(UIImge, caseName: String,
caseDate: String)'
and
#IBOutlet weak var caseImage: UIImageView!
UIImageView is not the same as UIImage, you will need to decide which one you want to use.