Calling function in swift - swift

I am having problems with calling the function in Swift, when building an iOS app.
#IBOutlet weak var vyseHypoteky: UITextField!
#IBOutlet weak var dobaSplaceni: UITextField!
#IBOutlet weak var urokovaSazba: UITextField!
#IBOutlet weak var mesicniSplatka: UITextField!
#IBAction func zmenaVyseHypoteky(sender: UISlider) {
var currentValue = Int(sender.value)
vyseHypoteky.text = "\(currentValue)"
vypoctiSplatku()
}
#IBAction func zmenaDobySplaceni(sender: UISlider) {
var currentValue = Int(sender.value)
dobaSplaceni.text = "\(currentValue)"
}
#IBAction func zmenaUrokoveSazby(sender: UISlider) {
var currentValue = Int(sender.value)
urokovaSazba.text = "\(currentValue)"
}
func vypoctiSplatku () {
let HU:Int? = vyseHypoteky.text.toInt()
let ipa:Int? = urokovaSazba.text.toInt()
let n:Int? = dobaSplaceni.text.toInt()
var ipm = ipa! / 12
var zavorka = 1+ipm
var vypoctenaZavorka = mocnina(mocnenec: zavorka, mocnitel: n)
var citatel = HU! * ipm * vypoctenaZavorka
var jmenovatel = vypoctenaZavorka - 1
var splatka = citatel / jmenovatel
mesicniSplatka.text = ("\splatka")
}
func mocnina (mocnenec: Int, mocnitel: Int) -> Int {
var mocnina = 1
for _ in 1...mocnitel {
mocnina *= mocnenec
}
return mocnina
}
The app is calculating a number by my formula. I want to use my function to calculate the x^y, this the "mocnina" function where I want to use two int, the x is "mocnenec" and the y is "mocnitel".
And finally I want to send the final int from variable "splatka" to text inout filed "mesicniSplatka".
But I am getting errors in calling the function "mocnina" --> var vypoctenaZavorka = mocnina(mocnenec: zavorka, mocnitel: n)
Extraneous argument label 'mocnenec:' in call
Value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'?
and in the end with mesicniSplatka.text = ("\splatka")
Invalid escape sequence in literal
How to fix it? Thx for helping a total newbie :)

The problem is that n is a wrapped:
var n:Int?
So you have a few options, you can either change your code to unwrap it when you use it (probably a good idea to check for nil before doing this as this will cause an exception if n is nil):
var vypoctenaZavorka = mocnina(mocnenec: zavorka, mocnitel: n!)
Or you can unwrap it when you create it:
let n:Int = dobaSplaceni.text.toInt()!
If you'd like to better understand "when to use optionals", I've written a very long explanation to this question on the subject: UIViewController variables initialization

In your code, n is declared of type Int?, it means "Optional Int". This is normal because the toInt() function is not guaranteed to succeed, and might return nil if the text is not convertible to an integer. So, you need to unwrap it first, like this: var vypoctenaZavorka = mocnina(mocnenec: zavorka, mocnitel: n!). Or, if you're not sure the conversion from string succeeded, do something like this:
let HU:Int? = vyseHypoteky.text.toInt()
let ipa:Int? = urokovaSazba.text.toInt()
let n:Int? = dobaSplaceni.text.toInt()
if ipa != nil {
var ipm = ipa! / 12
var zavorka = 1+ipm
if n != nil {
var vypoctenaZavorka = mocnina(mocnenec: zavorka, mocnitel: n)
// etc...
}
}

Related

Accept user input Range

I want to accept user input in a range, but keep on getting error:
Cannot convert value of type Range<Int32> to expected argument type Range<_>
I am learning Swift but I did not understand the different scenarios to convert UITextField to text and maybe integer.
class ViewController: UIViewController {
#IBOutlet weak var Range1: UITextField!
#IBOutlet weak var Range2: UITextField!
#IBOutlet weak var TheNUmber: UITextField!
#IBOutlet weak var OutletLabel: UILabel!
#IBAction func Guess(_ sender: UIButton) {
var R1 = (Range1.text! as NSString).intValue
var R2 = (Range2.text! as NSString).intValue
//print(R1, " ", R2)
var answer = Int.random(in: R1..<R2)
// I tried my best to use custom range from UItext field but did not work.
//I need more help.
print ("Random Number: \(answer)")
var turn = 0;
if(((R1>1)&&(R1<1000))&&((R2>1)&&(R2<1000))){
for i in 1...5{
let guess = (TheNUmber.text! as NSString).intValue
turn = i;
//let guess = (TheNUmber.text! as NSString).intValue
if(guess == answer){
OutletLabel.text = ("Yes, it is \(answer).")
OutletLabel.text = ("It took you \(turn) tries.")
break
}
else if(guess>answer){
OutletLabel.text = ("Lower!")
}
else if (guess<answer){
OutletLabel.text = ("Higher!")
}
else{
continue;
}
}
if (turn > 5){
OutletLabel.text = ("Sorry, it was \(answer).")
}
}
else{
OutletLabel.text = ("Keep the numbers between 1 and 100.")
}
}
#IBAction func Reset(_ sender: Any) {
self.Reset (sender)
}
I am not sure about this error. Please help me with the range.
The problem is that intValue returns an Int32, not an Int. So change
var R1 = (Range1.text! as NSString).intValue
var R2 = (Range2.text! as NSString).intValue
var answer = Int.random(in: R1..<R2)
To
let R1 = Int((Range1.text! as NSString).intValue)
let R2 = Int((Range2.text! as NSString).intValue)
let answer = Int.random(in: R1..<R2)
Even better, don't use NSString or intValue. Use Swift.
let R1 = Int(Range1.text!)!
let R2 = Int(Range1.text!)!
let answer = Int.random(in: R1..<R2)
Be aware that this code can crash — for example, if the user types "howdy" instead of an integer. But you need to deal with that.
Your code has other issues, but at least you will get past this one.

Mortgage Calculator Swift

I am a beginner with Xcode and Swift. Below is my formula for the mortgage calculator. It is working correct in Playground but when I transfer it to the ViewController tab that is when Xcode is giving me a bunch of errors. Can someone please help?
let r: Double = interestRate / 1200
let n: Double = years * 12
let p: Double = pow(1 + r, n)
let monthPay = loan * r * p / (p - 1)
print(monthPay)
So in my View Controller
valueA is Loan Amount
valueB is Number of Payments
valueC is Interest Rate
underneath that you will have a calculate button that will print the results underneath in a label currently named results. It may be that when i rename everything to the values is when the issues occur.
ViewController Code
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var valueA: UITextField!
#IBOutlet weak var valueB: UITextField!
#IBOutlet weak var valueC: UITextField!
#IBOutlet weak var results: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func button(_ sender: Any) {
let a = Int(valueA.text!)
let b = Int(valueB.text!)
let c = Int(valueC.text!)
let answer = a! * c! * pow(1 + c!, b!) / (pow(1 + c!, b!))
results.text = "$\(answer)"
}
}
Your issue is that you are converting your textfield values to integers and trying to multiply them by the result of pow's method which returns a Double. Note that if the user enters an invalid value your app will crash if you force unwrap the result. Yo can use nil coalescing operator ?? to provide a default value .zero in case of failure. Try like this:
class ViewController: UIViewController {
#IBOutlet weak var valueA: UITextField! // loan amount
#IBOutlet weak var valueB: UITextField! // Number of Payments
#IBOutlet weak var valueC: UITextField! // Interest Rate
#IBOutlet weak var results: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func button(_ sender: Any) {
let loanAmount = Double(valueA.text!) ?? .zero
let numberOfPayments = Double(valueB.text!) ?? .zero
let interestRate = Double(valueC.text!) ?? .zero
let rate = interestRate / 100 / 12
let answer = loanAmount * rate / (1 - pow(1 + rate, -numberOfPayments))
results.text = Formatter.currency.string(for: answer)
}
}
extension Formatter {
static let currency: NumberFormatter = {
let formatter = NumberFormatter()
formatter.locale = .init(identifier: "en_US_POSIX")
formatter.numberStyle = .currency
return formatter
}()
}

How to add two Ints in Swift 4? [duplicate]

This question already has answers here:
Swift: adding optionals Ints
(7 answers)
Closed 4 years ago.
I am trying to make an application that allows you to save a number in UserDefaults and then add onto that number later on. Right now, I keep getting the error:
'Binary operator '+' cannot be applied to two 'Int?' operands'
Can anyone point me in the right direction?
class FirstViewController: UIViewController {
var totalHoursInt = 0
var typeHoursInt = 0
var savedHours = 0
#IBOutlet weak var totalHours: UILabel!
#IBOutlet weak var typeHours: UITextField!
#IBAction func addButton(_ sender: Any) {
totalHours.text = typeHours.text!
UserDefaults.standard.set(typeHours.text, forKey: "savedHours")
typeHours.text = ""
var totalHoursInt = Int(totalHours.text!)
var typeHoursInt = Int(typeHours.text!)
print(totalHoursInt + typeHoursInt)
}
override func viewDidAppear(_ animated: Bool) {
if let x = UserDefaults.standard.object(forKey: "savedHours") as? String {
totalHours.text = x
}
}
}
Int() with a String argument doesn’t return an Int value but an Int Optional. This is because the String to Int conversion could fail in which case the conversion returns nil. And the + operator simply isn’t defined for optionals.
To solve your problem you will need to make sure the returned values aren in-nil, using a construct like this:
if let totalHours = totalHoursInt, let typeHours = typeHoursInt {
print(totalHours + typeHours)
}
if let ... assigns a value only if the right side is non-nil so the variables are converted from optionals to non-optionals. (You’re using that in viewDidAppear.) After that, the + operator will work.

Having Problems calculating the volume with 3 input values.

i'm a fairly new programmer and i've just started on Xcode. Atm i am trying to make a calculator that can calculate the total volume from 3 input values (Height, length & width) but i can't seem to make it calculate it. right now i am able to enter a value and click the button and then it crashes.
Thanks in advance!
here is my code:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
#IBOutlet weak var HeightInput: NSTextField!
#IBOutlet weak var LengthInput: NSTextField!
#IBOutlet weak var WidthInput: NSTextField!
#IBOutlet weak var Result: NSTextField!
#IBAction func Calculate(_ sender: Any) {
var height = Int(HeightInput.stringValue)
var width = Int(WidthInput.stringValue)
var length = Int(LengthInput.stringValue)
if height == 0
{
Result.stringValue = "Error"
}
else{
var result = width! * height! * length!
Result.stringValue = "the volume is: \(result)"
}
}
Try something like this.
#IBAction func Calculate(_ sender: Any) {
let height = Int(HeightInput.stringValue) ?? 0
let width = Int(WidthInput.stringValue) ?? 0
let length = Int(LengthInput.stringValue) ?? 0
let result = height * width * length
if result == 0 {
Result.stringValue = "Error"
else {
Result.stringValue = "The volume is: \(result)"
}
}
When converting your label value to an integer, it will return an optional (meaning it could be nil). When you are calculating your result, you are force-unwrapping these optionals with the !.
I recommend conditionally unwrapping these values. Using ?? meaning that if the value is nil, it will default to whatever you put after the ??.

Multiply a UI text field with number - Swift

Just starting learning swift but stuck when trying to multiply an input with another number and display on a label. I get the error that the number isn't a string and tried to cast but didn't work.
class ViewController: UIViewController {
#IBOutlet weak var entry: UITextField!
#IBOutlet weak var answer: UILabel!
#IBAction func button(_ sender: Any) {
answer.text = entry.text * 2
}
}
You should cast the text into a Double, an Int etc., then convert the calculation to a string.
if let entry = Double(entry.text) {
answer.text = "\(entry * 2)"
}
or
if let entry = Int(entry.text) {
answer.text = "\(entry * 2)"
}
If you know that the entry will hold a number
answer.text = String(Int(entry.text)! * 2)
Using optional unwrapping instead
if let num = Int(entry.text) {
answer.text = String(num * 2)
}