How To Fix: "Expression is Ambiguous". - ios

I am trying to create an app that can help you calculate sales tax on an item. Of course the app requires multiplication But I keep encountering the error:
"Type of expression is ambiguous without more context"
Can you help me? I'm new to swift so also try to explain why I am incorrect. This is my code so far:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var Item: UITextField!
#IBOutlet weak var Tax: UITextField!
#IBOutlet weak var Answer: UITextField!
#IBAction func Calculate(_ sender: Any) {
let a = Item.text
let conversionRate = Tax
let b = Int(a!)! * conversionRate
Answer.text = ("\(b)")
}
}
Thanks!!

Your primary issue is your attempt to multiply an Int and a UITextField.
You attempt to create an Int from Item.text but you make no similar attempt to convert Tax.text to a number.
There are also many other issues with your code. You are using the ! operator too much and your app will crash as a result.
And your naming conventions need to be improved. Variables and methods should start with lowercase letters.
Here's your code as it should be written:
class ViewController: UIViewController {
#IBOutlet weak var item: UITextField!
#IBOutlet weak var tax: UITextField!
#IBOutlet weak var answer: UITextField!
#IBAction func calculate(_ sender: Any) {
if let itemStr = item.text, let taxStr = tax.text, let itemVal = Int(itemStr), let taxVal = Int(taxStr) {
let result = itemVal * texVal
answer.text = "\(result)"
} else {
answer.text = "Invalid values"
}
}
}

You're trying to multiply a variable of UITextField type with a variable of Int. Try this:
class ViewController: UIViewController {
#IBOutlet weak var Item: UITextField!
#IBOutlet weak var Tax: UITextField!
#IBOutlet weak var Answer: UITextField!
#IBAction func Calculate(_ sender: Any) {
guard let a = Int(Item.text ?? "0") else { return }
guard let conversionRate = Int(Tax.text ?? "0") else { return }
let b = a * conversionRate
Answer.text = ("\(b)")
}
}

Related

How can I get values of response variable in other view in swift ...when I try to access this variable it returns nil...need to solve this

I just want to get all the values of response variable in (Agent view controller class) when I try to get using object it returns nil I have tried in many ways but still getting nil....in agent view controller I'm assigning all those runtime values to uitextview
import UIKit
class LoginViewController: UIViewController {
weak var delegateL:AgentprofileViewController!
var user : [UserModel] = []
let mm = Usersmanager()
//MARK:-- Outlets
#IBOutlet public weak var txtPhoneNumber: UITextField!
#IBOutlet public weak var txtPassword: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
//Functions
#IBAction func btnLogin(_ sender: Any) {
//below is the response variable which I want in other (Agent view controller class)
let response = mm.alluser(phoneNo: txtPhoneNumber.text!, Password: txtPassword.text!)
if response.count ?? 0 > 0
{
//uncom
delegateL.runtimeid? = response[0].u_id
delegateL.runtimename? = response[0].u_name!
delegateL.runtimephone? = response[0].phoneNumber!
delegateL.runtimepassword? = response[0].password!
delegateL.runtimeaddress? = response[0].address!
delegateL.runtimerid? = response[0].r_id!
delegateL.runtimername? = response[0].r_name!
print(response[0].u_id)
print(response[0].u_name)
print(response[0].password)
print(response[0].phoneNumber)
print(response[0].address)
print(response[0].r_id)
print(response[0].r_name)
if response[0].r_name=="Agent"
{
let next : tabViewController = self.storyboard?.instantiateViewController(withIdentifier: "tabViewController") as! tabViewController
self.navigationController?.pushViewController(next, animated: true)
showalertforloginsuccess()
print("Login Successfull")
//Passing view to the next view if login is succesfull
// let next : HomeViewController = self.storyboard?.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
// self.navigationController?.pushViewController(next, animated: true)
}
else{
print("Login Succesfull but login person is not agent")
}
}
else
{
showalertforloginfail()
print("Not Login")
}
}
This one is Agent Controller class where I want to access response variable values
import UIKit
class AgentprofileViewController: UIViewController {
#IBOutlet weak var txtid: UITextView!
#IBOutlet weak var txtname: UITextView!
#IBOutlet weak var txtphone: UITextView!
#IBOutlet weak var txtrid: UITextView!
#IBOutlet weak var txtpass: UITextView!
#IBOutlet weak var txtrname: UITextView!
#IBOutlet weak var txtaddress: UITextView!
var runtimeid:Int? = 0
var runtimename:String?=""
var runtimepassword:String?=""
var runtimeaddress:String?=""
var runtimephone:String?=""
var runtimerid:Int? = 0
var runtimername:String?=""
override func viewDidLoad() {
super.viewDidLoad()
//below all runtime variables contain nil
print(runtimeid)
print(runtimename)
print(runtimeaddress)
print(runtimepassword)
print(runtimephone)
print(runtimerid)
print(runtimername)
result()
}
override func viewWillAppear(_ animated: Bool) {
self.tabBarController?.navigationItem.title = "Profile"
}
func result() {
//uncom
//below is the error(txtid...contain nill while wrapping)
txtid.text = "\(String(describing: runtimeid))"
txtname.text = runtimename
txtpass.text = runtimepassword
txtphone.text = runtimephone
txtaddress.text = runtimeaddress
txtrid.text = "\(String(describing: runtimerid))"
txtrname.text = runtimername
}
}

Check if input countains numbers in 2 fields in xcode

So i recently tried to create a very simple calcylator in xcode, the problem i have is when i press the calculate button when there is no numbers there the app crashes, and when i put anything that isnt a number there and press the calculate button it also crash, and i know it crash cause it cant convert nothing/non numbers into a double, but how do i check if it is numbers in the textfields and if it is it will show the result off the
equation and if there is no number it will just set the textfeilds to nothing
(faktor1.text = "") (faktor2.text = "") ...
well it looks like this right now (ränka ut means calculate)
here is the code i used,
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var faktor1: UITextField!
#IBOutlet weak var faktor2: UITextField!
#IBOutlet weak var result: UILabel!
#IBOutlet weak var calculatebutton: UIButton!
#IBOutlet weak var clearui: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
result.text = ""
calculatebutton.layer.cornerRadius = 25.0
result.layer.cornerRadius = 25.0
clearui.layer.cornerRadius = 25.0
}
#IBAction func calculate( sender: Any) {
let input1 = Double(faktor1.text!)!
let input2 = Double(faktor2.text!)!
let calculation = input1 * input2
result.text = "(calculation)"
}
#IBAction func clearfnc( sender: Any) {
result.text = ""
faktor1.text = ""
faktor2.text = ""
}
}
You can simply unwrap your optionals the Swift way, instead of using ! (force unwrap)
This is an example using guard:
#IBAction func calculate(sender: Any) {
guard
let input1String = faktor1.text,
let input2String = faktor1.text,
let input1 = Double(input1String),
let input2 = Double(input2String)
else {
faktor1.text = ""
faktor1.text = ""
return
}
let calculation = input1 * input2
result.text = "\(calculation)"
}

How to check if a user inputed answer has letters, and if so, how would you just default that answer into a 0?

Heres the code I have so far, now when a user inputs any letter, my label display nothing, what I would like to figure out is how to turn that nothing "", into a 0. I tried doing an if statement on my "label.txt ="'s but that didn't pan out. What would be a better way of finding my desired results?
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var game1: UITextField!
#IBOutlet weak var game2: UITextField!
#IBOutlet weak var game3: UITextField!
#IBOutlet weak var series: UILabel!
#IBOutlet weak var average: UILabel!
#IBOutlet weak var high: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func calculate(_ sender: Any) {
self.view.endEditing(true)
guard
let text1 = game1.text,
let text2 = game2.text,
let text3 = game3.text
else { return }
guard
let game1Results = Int(text1),
let game2Results = Int(text2),
let game3Results = Int(text3)
else { return }
let gameResultsArray = [game1Results, game2Results, game3Results]
let sumArray = gameResultsArray.reduce(0, +)
let positiveArray = gameResultsArray.filter {
(item: Int) -> Bool in return item > 0
}
var avgArrayValue = 0
if positiveArray.count == 0
{
avgArrayValue = 0
}else {
avgArrayValue = sumArray / positiveArray.count
}
series.text = "\(sumArray)"
average.text = "\(avgArrayValue)"
if let maximumVal = gameResultsArray.max() {
high.text = String(maximumVal)
}
}
}
Here is what you need, convert String to Int and give the default 0. Instead of using the guard let return use this method:
Instead of this:
guard let game1Results = Int(text1) else { return }
Use this:
let game1Results = Int(text1) ?? 0

Converting string value from text field to integer

I'm really new to Swift and I am having problems with the conversion of a string (entered in a text field) to an integer.
I'm trying to create a small calculation app (I was following a tutorial on YouTube but it's old).
My app has 3 text fields, a label (that is meant to display the result), and a button to start the calculation.
Here's the code:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var valueA: UITextField!
#IBOutlet weak var valueB: UITextField!
#IBOutlet weak var valueC: UITextField!
#IBOutlet weak var result: UILabel!
#IBAction func calculateTotal(_ sender: Any) {
var a:Int? = Int(valueA.text)
var b:Int? = Int(valueB.text)
var c:Int? = Int(valueC.text)
var answer = a! * b! * c!
}
}
Try this (crash free code and you can add n number of textfield/string values as a number string):
var arrayOfTextFieldValues = [valueA.text, valueB.text, valueC.text]
#IBAction func calculateTotal(_ sender: Any) {
if let multiplication = multiplication(arrayString: arrayOfTextFieldValues) {
print("Answer = \(multiplication)")
result.text = "\(multiplication)"
}
}
// handle operations
func multiplication(arrayString: [String?]) -> Int? {
var answer:Int?
for arrayElement in arrayString {
if let stringValue = arrayElement, let intValue = Int(stringValue) {
answer = (answer ?? 1) * intValue
}
}
return answer
}

Stripe - Getting Error in Stripe Method

I am trying to integrate Stripe into my app and I followed a tutorial that seems to be out of date. This is how my code looks:
import Foundation
import UIKit
import Stripe
import AFNetworking
class PaymentViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
#IBOutlet weak var emailTextField: UITextField!
#IBOutlet weak var cardNumberTextField: UITextField!
#IBOutlet weak var expirationDateTextField: UITextField!
#IBOutlet weak var cvcTextField: UITextField!
#IBAction func payButton(_ sender: Any) {
// Initiate the card
let stripCard = STPCardParams()
// Split the expiration date to extract Month & Year
if self.expirationDateTextField.text?.isEmpty == false {
let expirationDate = self.expirationDateTextField.text?.components(separatedBy: "/")
let expMonth = UInt((expirationDate?[0])!)
let expYear = UInt((expirationDate?[1])!)
// Send the card info to Strip to get the token
stripCard.number = self.cardNumberTextField.text
stripCard.cvc = self.cvcTextField.text
stripCard.expMonth = expMonth!
stripCard.expYear = expYear!
}
var underlyingError: NSError?
stripCard.validateCardReturningError(&underlyingError)
if underlyingError != nil {
self.handleError(underlyingError!)
return
}
}
}
I am getting an error in this block of code:
var underlyingError: NSError?
stripCard.validateCardReturningError(&underlyingError)
if underlyingError != nil {
self.handleError(underlyingError!)
return
}
}
The error says that .validateCardReturningError(&underlyingError) is deprecated and that I should use STPCardValidator instead. I tried doing so but could not fix it. Help will be greatly appreciated.
according to #jflinter . you should flowing this way
let cardParams = STPCardParams()
cardParams.number = ...
cardParams.expMonth = ...
cardParams.expYear = ...
cardParams.cvc = ...
if STPCardValidator.validationStateForCard(cardParams) == .Valid {
// the card is valid.
}

Resources