Decimals after multiplying values in Swift 3 - ios

I'm trying to make an app that multiplies a number for a price that can be decimal or not. For example 3 * 3.50.
I'm using Swift 3. I searched for several topics here but could not add this feature to my app.
My code looks like this:
#IBOutlet weak var valueBreja1: UITextField!
#IBOutlet weak var quantityBreja1: UITextField!
#IBOutlet weak var totalBreja1: UILabel!
#IBAction func calcBreja1(_ sender: Any) {
let a = Int(valueBreja1.text!)
let b = Int(quantityBreja1.text!)
let Answer = a! + b!
totalBreja1.text = "R$\(Answer)"
}
I wanted to show the value with decimal number after multiplication.

Use Double instead of Int:
#IBAction func calcBreja1(_ sender: Any) {
let a = Double(valueBreja1.text!)
let b = Double(quantityBreja1.text!)
let Answer = a! + b!
totalBreja1.text = "R$\(Answer)"
}

You have two problems.
First, you're creating Int values from the field strings. Int values can only hold integer values, so any fractional portion will be discarded. You need to create Double values (or some other form of floating or fractional value).
To format the output use a formatter.
//: Playground - noun: a place where people can play
import Cocoa
var str1 = "3.50"
var str2 = "3"
if let value = Double(str1) {
if let multiplier = Int(str2) {
let formattedResult = String(format: "%.02f", value*Double(multiplier))
}
}

Related

How do I find the Max from a group of user inputed Ints using Xcode 11 and swift

Here's what I have so far:
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) {
let game1Results = Int(game1.text!)
let game2Results = Int(game2.text!)
let game3Results = Int(game3.text!)
let gameResultsArray = [game1Results, game2Results, game3Results]
high.text = "\(gameResultsArray.max())"
}
}
I've been trying to use the .max function but I'm getting errors stating I need to refer to conform to "Comparable". I'm pretty new to swift, any help will be much appreciated.
It happens because you try to compare values of optional Int (Int?)
First of all, you should know that not each String can be converted to an Int
E.g. '42' will be converted correctly, but 'ie42zx' can't be converted to and Int - that's why Int(String) function returns optional Int (Int?)
'Optional' property says like 'i can have a value, but I can also be nil'. That's why you should unwrap optionals in your code
First, I suggest to avoid force unwraping here.
let game1Results = Int(game1.text!)
It can be done like that:
guard
let text1 = game1.text,
let text2 = game2.text,
let text3 = game3.text
else { return }
You should do that because not every text field contains text, so textField.text property returns an optional String?
Then you can convert your String results to an Int and unwrap these results before compare:
guard
let game1Results = Int(text1),
let game2Results = Int(text2),
let game3Results = Int(text3)
else { return }
I would suggest to read more about optionals in swift and unwrapping (see Optionals paragraph)
I believe your issue is that the Int constructor with a string returns an optional integer value. You're trying to take the max of a bunch of optionals, so it cant figure it out.
You can use the compactMap function on your array before calling max() to filter out the nil values.
gameResultsArray.compactMap{ $0 }.max()

I am running into an Index out of Range Error in Swift 5

I am new to swift programming and I am running into an error on the bolded piece of code below, this is my first post ever on Stack Overflow and am trying to figure out how to fix this Index out of Range Error. Any help would be greatly awesome!
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var questionLabel: UILabel!
#IBOutlet weak var progressBar: UIProgressView!
#IBOutlet weak var trueButton: UIButton!
#IBOutlet weak var falseButton: UIButton!
let quiz = [
["Four + Two is equal to Six.", "True"],
["Five - Three is greater than One", "True"],
["Three + Eight is less than Ten, False"]
]
var questionNumber = 0
override func viewDidLoad() {
super.viewDidLoad()
updateUI()
}
#IBAction func answeredButtonPressed(_ sender: UIButton) {
let userAnswer = sender.currentTitle // True, False
**let actualAnswer = quiz[questionNumber][1]**
if userAnswer == actualAnswer {
print("Right!")
} else {
print("Wrong")
}
if questionNumber + 1 < quiz.count {
questionNumber += 1
} else {
questionNumber = 0
}
updateUI()
}
func updateUI() {
questionLabel.text = quiz[questionNumber][0]
}
}
Welcome to Stackoverflow! The reason you get the crash error index out of range when you attempt to extract the boolean string is because the element of your index 2 has a single string.
["Three + Eight is less than Ten, False"]
Simply put the " in there.
["Three + Eight is less than Ten", "False"]
One more approach you can consider is to use Tuple or Dictionary.
If you use Tuple, and you commit the same mistake, it will give you a compile-time error, like:
Heterogeneous collection literal could only be inferred to '[Any]';
add explicit type annotation if this is intentional
Tuple example:
let quiz = [
("Four + Two is equal to Six.", "True"),
("Five - Three is greater than One", "True"),
("Three + Eight is less than Ten", "False")
]
let answer = quiz[2].1
As suggested by Paulw, a better way would be making a model. Like:
Quiz.swift
struct Quiz {
/// Contains the question string.
var question: String
/// Consider changing this to `Bool`.
var answer: String
}
Usage:
let quiz = [
Quiz(question: "Four + Two is equal to Six.", answer: "True"),
Quiz(question: "Five - Three is greater than One", answer: "True"),
Quiz(question: "Three + Eight is less than Ten", answer: "False")
]
let answer = quiz[2].answer

Limiting User to One Decimal Point UILabel Swift2

So, if you read the question then you know the problem. I have read over a load of other articles about one decimal but all of them use this textfield thingy. I'm using a UILabel and have no idea how to only make one decimal point appear. Here is some of my code.
#IBOutlet weak var Screen: UILabel!
var firstNumber = Float()
var secondNumber = Float()
var result = Float()
var operation = ""
var isTypingNumber = false
var dotString = "."
#IBAction func Dot(sender: AnyObject) {
let dot = sender.currentTitle
Screen.text = Screen.text! + dot!!
}
I think I have provided enough code to fix the problem. The problem is I can enter 8.22.197.161... or as many decimals as the label can fit. I want it to stop putting more decimals after validating that there is only 1. I'm a pretty beginner noob at this stuff so any help will be appreciated as I have been breaking my head over this for the last couple days.
So, if there is no dot in the string, then you want to append a dot. Swift has something called an “if statement” that helps a lot:
if let text = Screen.text {
if !text.containsString(".") {
Screen.text = text + "."
}
}

When trying to convert a UITextField text to Int Xcode 7 gives me an error

I'm new to programming and after doing some tutorials online I decided to make my own app with Xcode 7 to be able to run my app on my iPhone. But when I try to get input data from a text field and put it into a var it gives me an error. I have tried to use the following:
var initialChips = 0
var initialBlind = 0
#IBOutlet weak var txtBlind: UITextField!
#IBOutlet weak var txtChips: UITextField!
#IBOutlet weak var doneBtn: UIBarButtonItem!
#IBAction func doneBtn(sender: AnyObject) {
let initialChips:Int? = Int(txtChips.text)
let initialBlind:Int? = Int(txtBlind.text)
}
Xcode will ask to put a "!" after ".text" but after doing that it gives me a warning: "Initialization of immutable value 'initialChips' (or 'initialBlind' was never used: consider replacing with assignment to '_'or removing it".
What can I do to set a value to my var?
The thing is that the let initialChips:Int? = Int(txtChips.text) generates a new variable called initialChips (different from the variable from the class). The difference between let and var is that let is inmutable and var is not. You should do:
initialChips = Int(txtChips.text)
To assign the integer from the UITextField to your class variable rather than declaring a new inmutable variable (with the same name) and do nothing with it.
Of course, the same happens with initialBlind
EDIT:
Try the following:
#IBAction func doneBtn(sender: AnyObject) {
if let initialChips = Int(txtChips.text!) {
self.initialChips = initialChips
}else {
self.initialChips = 0
}
if let initialBind = Int(txtBind.text!) {
self.initialBind = initialBind
}else {
self.initialBind = 0
}
}
You should add the ! after the closing parenthesis, not after .text, like so:
let initialChips:Int? = Int(txtChips.text)!

Swift how to output int value in a textfield?

Alright, so I'm building an app that takes in a sequence of int values using a text field and encrypts it depending upon the initialized cipher. Originally I use the .toInt() function to covert my numerical string values into an array of integer. Then I add the cipher to each value in the array of integers however I'm having difficulty outputting the int array back to the text-field with the encrypted sequence. I have already thoroughly researched this and I can't seem to find an adequate function to convert my int array (named: code) back into a string which I can initialize as message1.text = the string numerical sequence.
Here is my code so far:
class ViewController: UIViewController {
#IBOutlet var text: UITextField!
#IBOutlet var Lable: UILabel!
#IBOutlet var Button: UIButton!
#IBOutlet var message1: UITextField!
#IBOutlet var Button2: UIButton!
var name = 0
#IBAction func Button(sender: UIButton) {
name = text.text.toInt()!
}
#IBAction func Button2(sender: UIButton) {
var code = Array (message1.text).map{String($0).toInt()! }
for var n = 0 ; n < code.count; n++
{
code[n] = code[n] + name
}
var StringArray = (code : String()) // This is the mistake, I want to convert the code array into a joint string,
message1.text = StringArray
}
I already know that what I attempted to do doesn't work cause when I run the app and press Button2 I'am left with no text at all in the text-field thus it is a legitimate statement that String array is not being initialized as expected.
Any help is much appreciated, Thank you for your time I'm starting off in app programming and I'm still struggling at relatively simple stuff so I understand if the answer might seem overly palpable.
All you need to do is remap the values back to strings and join them:
var stringOfCodes = "".join( code.map { "\($0)" } )
This gives you a single string from the code values. I feel like there is a more elegant way to accomplish this, but this is what immediately came to mind.
If you want to create a string out of an array:
var spaceSeparatedString = " ".join(StringArray)
This will create a string out of the array using a space as the separator. Eg: "string1 string2 string3".

Resources