This is my code I don't know what I did wrong. All of the problems are in function steve. LebelText is a timer timer label that is segued from another view controller. So i want to take lebetText convert it to a int to subtract 1 from it then reconvert it back to a string to display the number.
This is view Controller a. The texted being segued is lebelText.
import UIKit
class testViewController: UIViewController {
#IBOutlet var lazel: UILabel!
#IBOutlet var plax: UIButton!
#IBOutlet var stopx: UIButton!
var timer = Timer()
var counter = 0.0
var isRunning = false
override func viewDidLoad() {
super.viewDidLoad()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let DestViewController : restultViewController = segue.destination as! restultViewController
DestViewController.LebelText = lazel.text!
}
#IBAction func play(_ sender: Any) {
if !isRunning{
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(testViewController.update), userInfo: nil, repeats: true)
}
plax.isEnabled = false
stopx.isEnabled = true
}
#IBAction func stop(_ sender: Any) {
plax.isEnabled = true
stopx.isEnabled = false
timer.invalidate()
isRunning = false
}
func update(){
counter += 0.1
lazel.text = String(format: "1%f", counter)
lazel.text = "\(counter)"
}}
this is view controller b. The goal is to go to take lebelText convert it to a int to subtracted 1 from it. Then convert it back to a string so it can be displayed.
import UIKit
class restultViewController: UIViewController {
#IBOutlet var dxe: UILabel!
var LebelText = String()
let myInt = Int()
override func viewDidLoad() {
super.viewDidLoad()
steve()
}
func steve(){
var eq = LebelText
var intValue = Int(eq)
let vx = intValue! - 1
let ramit = String(vx)
dxe.text = ramit
}
ok so to get rid of the optional and to be sure it all works you should do like
if let intValue = Int(eq) {
vx = intValue - 1
dxe.text = String(vx)
} else {
//do some stuff if you cannot convert eq to Int
}
but I would recommend you to start with some easier tasks, it looks like you did not completely learn basics.
import UIKit
class restultViewController: UIViewController {
#IBOutlet var someLabel: UILabel!
public var myText: String?
override func viewDidLoad() {
super.viewDidLoad()
self.parseData()
}
private func parseData(){
guard let unwrapedText = self.myText else {
//you didn't pass string
return
}
if let myInt = Int(unwrapedText) {
myInt = myInt - 1
self.someLabel.text = String(myInt)
} else {
//you string is not convertable to int
}
}
}
You Can just do this.
import UIKit
class restultViewController: UIViewController {
#IBOutlet var dxe: UILabel!
var LebelText = String()
let myInt = Int()
override func viewDidLoad() {
super.viewDidLoad()
steve()
}
func steve(){
var eq = Int(LebelText.text)
eq = eq - 1
dxe.text = String(eq)
}
Related
I am new to programming & trying to apply filters using UISwitches
Currently I have:
A realm database returning all the objects
A UI that uses Switches to send filters
Things Attempted:
Subqueries, however I don't know the proper format to write it for realm
Goal: Apply multiple filters to realm database results
User Interface:
Realm Database:
class Question: Object {
#objc dynamic var neverAttempted: Bool = true
#objc dynamic var correct: Int = 0
#objc dynamic var flagged: Bool = false
#objc dynamic var subject: String = ""
}
correct = 1;
neverAttempted = true;
flagged = false;
subject = Law;
View Controller:
import UIKit
import RealmSwift
class OptionsViewController: UIViewController {
#IBOutlet weak var totalQuestionsLabel: UILabel!
#IBOutlet weak var totalQuestionSlider: UISlider!
var neverAttempted = ""
var correct = ""
var flagged = false
var subject = ""
let realmOne = try! Realm()
var questionBank: Results<Question>! {
get {
return realmOne.objects(Question.self)
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
func updateQuestionBank() {
let updatedQuestionBank = realmOne.objects(Question.self)
.filter(//Apply filter//)
totalQuestionsLabel.text = String(updatedQuestionBank.count)
print (updatedQuestionBank)
}
#IBAction func subjectSwitch(_ sender: UISwitch) {
if sender.isOn == true {
subject =
updateQuestionBank()
}
}
#IBAction func flaggedSwitch(_ sender: UISwitch) {
if sender.isOn == true {
flagged =
updateQuestionBank()
}
}
#IBAction func neverAttemptedSwitch(_ sender: UISwitch) {
if sender.isOn == true {
neverAttempted =
}
}
#IBAction func correctOnlyOnceSwitch(_ sender: UISwitch) {
if sender.isOn == true {
correct =
updateQuestionBank()
}
}
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
I have two Random numbers generating in ViewDidLoad. I Want to plus these two numbers and the result should be checked in a button with data of a input field. my problem is that I do not know how to transfer result to the function CheckResultBtn . now it does not recognise result.
here is My codes and I really appreciate any kinds of help
class ViewController: UIViewController {
#IBOutlet weak var lblRandomNumOne: UILabel!
#IBOutlet weak var lblRandomNumTwo: UILabel!
#IBOutlet weak var KidsField: UITextField!
#IBOutlet weak var Showresult: UILabel!
#IBOutlet weak var CheckResult: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let x = Int.random(in: 0 ..< 10)
lblRandomNumOne.text = String(x);
let y = Int.random(in: 0 ..< 10)
lblRandomNumTwo.text = String(y);
let result = x + y;
CheckResultBtn(result) //not sure about this
}
#IBAction func CheckResultBtn(_ sender: Any)
{
if (KidsField != nil)
{
let kidsresult = Int(KidsField.text!) ;
if (result == kidsresult)
{
Showresult.text = "Bravo";
}
else
{
Showresult.text = "Try Again!"
}
}
}
}
declare the variable "result" before the viewDidload function
var result : Int!
then proceed to perform the operation on the variable in your viewDidload and you can get rid of this line
CheckResultBtn(result)
and you should be able to access the result variable in your IBAction function
You can try
#IBAction func checkResultBtn(_ sender: Any) {
displayRes(Int(kidsField.text!)!)
}
func displayRes(_ result:Int) {
showresult.text = result == kidsresult ? "Bravo" : "Try Again!"
}
Then inside viewDidLoad
displayRes(x+y)
create a new function instead of using action Method
like this :
func CheckResultBtn(_ result : Int) {
if (KidsField != nil)
{
let kidsresult = Int(KidsField.text!) ;
if (result == kidsresult)
{
Showresult.text = "Bravo";
}
else
{
Showresult.text = "Try Again!"
}
}
}
or create a variable
var result : Int?
assign a value
result = x + y;
and use inside the action Method
var result : Int?
override func viewDidLoad() {
super.viewDidLoad()
let x = Int.random(in: 0 ..< 10)
lblRandomNumOne.text = String(x);
let y = Int.random(in: 0 ..< 10)
lblRandomNumTwo.text = String(y);
result = x + y;
}
#IBAction func CheckResultBtn(_ sender: Any) {
if (KidsField != nil)
{
let kidsresult = Int(KidsField.text!) ;
if (result == kidsresult)
{
Showresult.text = "Bravo";
}
else
{
Showresult.text = "Try Again!"
}
}
}
Sorry if this is a newbie question, I am very new to iOS & Swift. I have seen already on the internet how to use User Default, but I don't know how to insert it in my project:
#IBOutlet weak var labelScore: UILabel!
var score = 0
let scoreUserDefault = UserDefaults.standard
#IBAction func button(_ sender: Any) {
score += 1
labelScore.text = String(score)
print(score)
}
override func viewDidLoad() {
super.viewDidLoad()
if let score = scoreUserDefault.value(forKey: "best") as? Int {
self.score = score
}
}
My project did not store the score, which I expected it to do.
Welcome to swift
// you should store value at first
// here also is good lesson for that part
https://www.hackingwithswift.com/example-code/system/how-to-save-user-settings-using-userdefaults
#IBOutlet weak var labelScore: UILabel!
var score = 0
let scoreUserDefault = UserDefaults.standard
#IBAction func button(_ sender: Any) {
score += 1
labelScore.text = String(score)
// you should store value sta key
scoreUserDefault.set(score, forKey: "best")
print(score)
}
override func viewDidLoad() {
super.viewDidLoad()
if let score = scoreUserDefault.integer(forKey: "best"){
self.score = score
}
}
This is the code I have. Basically when the user first chooses the quality of the dinning whether it is fine (20%), casual (15%), or a bar (11%). From there the user will then be asked on a 1-5 scale about the food quality, service, etc. Depending what number they choose, for example if the fine dinning was a 5/5 then it will ad 4% to the already 20 percent (each number will have a selected value to add to the tip). Can anyone figure out what's going on? Or if there is a better way about doing it.
import UIKit
#IBDesignable
class ViewController: UIViewController {
#IBOutlet weak var billTotal: UITextField!
var diningValue: Double = 0.0
#IBAction func toggleFineDining(sender: UIButton) {
sender.highlighted = sender.selected
if sender.selected == true{
diningValue = 0.20
}
}
#IBAction func toggleCasualDining(sender: UIButton) {
sender.highlighted = sender.selected
if sender.selected == true{
diningValue = 0.15
}
}
#IBAction func toggleBartender(sender: UIButton) {
sender.highlighted = sender.selected
if sender.selected == true{
diningValue = 0.11
}
}
#IBOutlet weak var service: UITextField!
#IBOutlet weak var friendliness: UITextField!
#IBOutlet weak var foodQuality: UITextField!
#IBOutlet weak var atmosphere: UITextField!
#IBOutlet weak var overall: UITextField!
#IBOutlet weak var recommend: UISwitch!
#IBOutlet weak var total: UILabel!
func totalBill(inputArray: [Double], value: Double, recommend: Bool)->Double{
var array: [Double] = []
let total = inputArray[0]
for var i = 1; i < inputArray.count; ++i {
array.append(inputArray[i] * 0.01)
}
let sum = array.reduce(0, combine: +)
var totalTip = Double()
if recommend == true{
totalTip = sum + value
} else {
if sum < 0.15 {
totalTip = 0.15
} else {
totalTip = sum + value
}
}
let tipValue = totalTip * total
return total + tipValue
}
#IBAction func calcTotal(sender: AnyObject) {
var valueList = [String(service.text), String(friendliness.text), String(foodQuality.text), String(atmosphere.text), String(overall.text)]
let list = doubleArray(valueList)
print(list)
let initialTotal = Double(billTotal.text!)
let total_bill = totalBill(list, value: diningValue, recommend: recommend.selected)
print("Total: ", total_bill)
print(String(format: "%.3f", Double(total_bill)))
total.text = "$" + String(format: "%.2f", Double(total_bill))
//diningValue = diningValue
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
func doubleArray(list: [String])->[Double]{
var doubledList: [Double] = []
for element in 0...list.count{
let doubledElement = Double(list[element])
doubledList.append(doubledElement!)
}
return doubledList
}
Your issue is in the last function:
func doubleArray(list: [String])->[Double]{
var doubledList: [Double] = []
for element in 0...list.count{
let doubledElement = Double(list[element])
doubledList.append(doubledElement!)
}
return doubledList
}
Your loop is looping from 0 to list.count and it crashes at list[element] when element is list.count (Out of Index)
You need to change from 0...list.count to 0..<list.count:
func doubleArray(list: [String])->[Double]{
var doubledList: [Double] = []
for element in 0..<list.count{
let doubledElement = Double(list[element])
doubledList.append(doubledElement!)
}
return doubledList
}
I would recommend you to do it in swifty way:
func doubleArray(list: [String])->[Double]{
var doubledList: [Double] = []
for element in list {
doubledList.append(Double(element) ?? 0.0)
}
return doubledList
}
A shorter version using map function:
func doubleArray(list: [String])->[Double]{
return list.map( { Double($0) ?? 0.0 })
}