Limiting User to One Decimal Point UILabel Swift2 - ios

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 + "."
}
}

Related

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

Decimals after multiplying values in Swift 3

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

Working on a calculator in swift and I'm stuck

I'm new to coding and just learning now. swift code and I'm running into a snag and can't seem to figure it out, so I've been flowing along with the Stanford YouTube channel on swift coding and they are doing a calculator. Currently we are trying to get double value.
#IBOutlet weak var display: UILabel!
var userIsInTheMiddleOfTypingANumber = false
#IBAction func appendDigit(sender: UIButton) {
let digit = sender.currentTitle!
if userIsInTheMiddleOfTypingANumber {
display.text = display.text! + digit
} else {
display.text = digit
userIsInTheMiddleOfTypingANumber = true
}
}
var operandStack: Array<Double> = Array<Double>()
#IBAction func enter() {
userIsInTheMiddleOfTypingANumber = false
operandStack.append(displayValue)
print("operandStack = \(operandStack)")
}
var displayValue: Double {
get {
return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
// This is my problem and comes back with exc_bad_instruction (code=exc_i387_invop any help would be greatly appreciated on this! thank you for your time!
}
set {
display.text = "\(newValue)"
userIsInTheMiddleOfTypingANumber = false
}
}
In addition to Martin R: Actually you have two big problems and both are related to your unwrapping of optionals.
First is this line:
#IBOutlet weak var display: UILabel!
The problem is the !. An #IBOutlet links to a view in a storyboard. But depending on the stage the GUI is at it may be that this displaywon`t exist yet. So this should be a optional marked with ? not !. Then your compiler would complain about this line:
return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
He would complain that display probably does not exist and that you can`t just do that. You would probably "solve" the problem like this:
return NSNumberFormatter().numberFromString(display!.text!)!.doubleValue
But this will either fail if displayist not ready or of the NSNumberFormatter can`t convert the string to a number. And you will never know why. So stop using forced unwrapping. You have different tools to solve your problem though. But at first you should think about your problem. Your problem is in the end that not every string can be converted to a double. So you have to deal with this at some point. There are countless possibilities to do so. But as a starter, if you have code that will crash if an optional (can be nil value) is actually nil then you can use this pattern:
if let thisValueIsNotNil = dontKnowIfItIsNil {
// Do something with thisValueIsNotNil - it is save
}
Edit: The core problem an mechanism are pretty well explained IMO in this blog post:
http://appventure.me/2014/06/13/swift-optionals-made-simple/

Why does this swift code work when newValue has nothing assigned to it?

import UIKit
class ViewController: UIViewController {
#IBOutlet weak var display: UILabel!
var inMid = false
#IBAction func appendDigit(sender: UIButton) {
let digit = sender.currentTitle!
if inMid{
display.text = display.text! + digit
}else{
display.text = digit
inMid = true
}
}
var operandStack = Array<Double>()
#IBAction func enter() {
inMid = false
operandStack.append(displayValue)
println("operandStack = \(operandStack)")
}
var displayValue:Double{
get {
return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
}
set{
display.text = "\(newValue)"
}
}
}
This is the part of code used in the latest Standford IOS 8 course using swift to build a calculator(Youtube address: https://www.youtube.com/watch?v=QLJtT7eSykg)
Every time I call enter() (press enter), a new number is supposed to be saved in a stack. For example: "8, enter()" --> {8}, "16, enter()" --> {8,16}.
I got confused about the computed property "displayValue" here. There is nothing assigned to the "newValue". If there is something like "displayValue = 8", then I know "newValue" is 8, and it all makes sense. But there is not such thing.
How come it still works?
(What I mean is not the name "newValue" itself,I know it is a default setting by Swift, instead, the missing of assigned value is the one that confuses me)
"newValue" is an implicitly defined variable in swift.
What he does is a very neat way of letting the label show the values of the double "displayValue" Every time displayValue is changed, the label is automatically updated with the newest (double) value.
Or when you write: displayValue = 45.0, the label will also show this value. Very handy when you constantly need to update textfield or labels with data you get from databases, rest interfaces, etc. What "newValue" does is taking the last "setter" value holding that.

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