How do I check if x is in a variable in classes within a list? - swift

I have a list called mainframe which holds classes. I want to check before adding a new username; if newusername is in mainframe.usernames perform adding the new username in.
pretty much something like this:
import UIKit
class addNewPassword: UIViewController {
var homeVC = Home()
#IBOutlet weak var createHolderItem: UITextField!
#IBOutlet weak var createHolderUsername: UITextField!
#IBOutlet weak var createHolderPassword: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func savePasswordButton(_ sender: Any) {
let holder = Holder()
holder.item = createHolderItem.text!
holder.username = createHolderUsername.text!
holder.password = createHolderPassword.text!
}
if mainframe.contains(where: { $0.username == holder.username }) {
print("test")
}
else {
homeVC.mainframe.append(holder)
homeVC.tableView.reloadData()
navigationController?.popViewController(animated: true)
}
}
I pretty much want to run a loop, within an if statement. Or am I approaching it the wrong way?
I'm new to programming, did online tutorials and trying to write my first iOS app for my aunt.

if mainframe.usernames.contains(holder.username) {
...

Use contains :
if mainframe.usernames.contains(holder.username) {
...
}

Related

How do I assign Y to X?

I couldn't figure out how to copy value of variable into another variable in Swift, an example code for this in python would be
def assignVariable():
x=1
y=x
return y
RESULT 1
When I did this it doesn't seem to work in Swift. Is there any solution to this or am I doing something wrong?
Edit: problem is at
var originalCount=countDown
it gave me Use of unresolved identifier 'countDown' but when I assign it literally it works. Here's my swift code
import Cocoa
class MainWindow: NSWindowController {
var hitCount = 0
var started:Bool = false
var timer = 10
var colorList: [NSColor] = [ NSColor.black,NSColor.blue,NSColor.brown,NSColor.cyan,NSColor.darkGray,NSColor.gray,NSColor.green,NSColor.lightGray,NSColor.magenta,NSColor.orange,NSColor.purple,NSColor.red,NSColor.white,NSColor.yellow]
#IBOutlet weak var button1: NSButton!
#IBOutlet weak var scrubber1: NSScrubber!
#IBOutlet weak var display: NSTextField!
override func windowDidLoad() {
super.windowDidLoad()
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}
var countdown=10
var originalCount=countDown
//(countdown,originalCount) = (10,10) //it works if i use this instead
func startGame(){
if(countDown>0 || started==true){
display.stringValue=String(countDown)
countDown-=1
let seconds = 1.0
DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
self.startGame()
}
}else{
display.stringValue="Done "+String(hitCount)+" Taps in " + String(originalCount) + "Tap to RESET"
started=false
countDown=10;
}
}
#IBAction func labelPress(_ sender: Any) {
display.stringValue="__RESET__"
hitCount=0
countDown=10
started=false
}
#IBAction func buttonPressed(_ sender: Any) {
if started==false{
startGame()
}
button1.bezelColor = colorList[Int.random(in: 0..<colorList.count)]
started=true
button1.title=String(hitCount)
hitCount+=1
}
}
You can't initialise one variable with another at the top level in your class. Looking at your code I don't think that originalCount needs to be a property, move it inside startGame() instead and make it a local variable and also use let since it isn't changing
var countdown=10
func startGame(){
let originalCount = countDown
if(countDown>0 || started==true){
...
}

Error: "Cannot capture 'word' before it is declared" iOS swift

I'm writing code for a dictionary app in splitviewcontroller. I set a "Word" class with various entries, which are now not being read by the computer when I try to label them.
import UIKit
class DetailViewController: UIViewController {
class Word {
let name: String
let meaning: String
let numberOfTimesTapped: String
init(name: String, meaning: String, numberOfTimesTapped: String) {
self.name = name
self.meaning = meaning
self.numberOfTimesTapped = numberOfTimesTapped
}
}
#IBOutlet weak var WordLabel: UILabel!
#IBOutlet weak var DescriptionLabel: UILabel!
#IBOutlet weak var NumberOfTimesTappedLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
func refreshUI() {
loadViewIfNeeded()
WordLabel.text = word?.name //[THIS IS WHERE I GET THE ERROR: "Cannot capture 'word' before it is declared" ALTHOUGH IT'S BEEN CLEARLY DECLARED BEFORE!!!]
DescriptionLabel.text = word?.meaning
NumberOfTimesTappedLabel.text = word?.numberOfTimesTapped
}
var word: Word? {
didSet {
refreshUI()
}
}
You'd see it much easier if you were using proper indentation, but you declare var word inside of refreshUI. You need to declare it outside of that so that the scope is accessible inside of refreshUI. Also you declare refreshUI inside of viewDidLoad, which is most likely not what you want. A fixed version of this code would be
var word: Word? {
didSet {
refreshUI()
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
func refreshUI() {
loadViewIfNeeded()
WordLabel.text = word?.name
DescriptionLabel.text = word?.meaning
NumberOfTimesTappedLabel.text = word?.numberOfTimesTapped
}

Secure text .echosbullets not working for password field

Here's what I've got:
#IBOutlet weak var password: NSSecureTextField!
#IBOutlet weak var shwpswd: NSButton! //Checkbox
#IBOutlet weak var pswdcell: NSSecureTextFieldCell! //Cell
#IBAction func shwpswd(_ sender: Any) {
if(shwpswd.state == 1) {
pswdcell.echosBullets = false // Turn the Secure text into regular text
}
else if(shwpswd.state == 0) {
pswdcell.echosBullets = true // Secure text
}
}
Everything seems to run fine, except the text in the password field doesn't change states between echoing bullets and echoing the real text. Everything is linked together properly too - Cell is within the text field, password button is in the view and the outlet works. I'm wondering if this is another one of the "Swift on mac < Swift on iOS cases".
EDIT: Here is the final solution, should anyone care to see it:
#IBOutlet weak var shwpswd: NSButton! //Checkbox
#IBOutlet weak var visPswd: NSTextfield! //hidden regular box to show chars
#IBOutlet weak var password: NSSecureTextField! //visible initial secure box
#IBAction func shwpswd(_ sender: Any) {
if(shwpswd.state == 1) {
self.visPswd.stringValue = self.password.stringValue //Sync both the text fields
self.password.isHidden = true //hide the secure field
self.visPswd.isHidden = false //show the real character echo field
}
else if(shwpswd.state == 0) {
self.password.stringValue = self.visPswd.stringValue //Sync the two
self.password.isHidden = false // Inverse of above
self.visPswd.isHidden = true
}
}
Note the text fields password and visPswd are the same size and position in the view - one remains hidden at all times to avoid overlapping. When the user enters values in either the password or visPswd field, it syncs with the other field when the checkbox state is changed.
You can accomplish what you want adding a second text field in top of your secure field. Add an IBAction to your check box to switch your fields isHidden property and copy the other textField stringValue and make it the first responder. Your implementation should look like something like this:
import Cocoa
class ViewController: NSViewController {
#IBOutlet weak var password: NSSecureTextField!
#IBOutlet weak var showPassword: NSTextField!
#IBOutlet weak var shwpswd: NSButton!
override func viewDidLoad() {
super.viewDidLoad()
shwpswd.state = .off
showPassword.isHidden = true
}
override func viewDidAppear() {
super.viewDidAppear()
password.window?.makeFirstResponder(password)
}
#IBAction func showHidePassword(_ sender: NSButton) {
showPassword.isHidden.toggle()
password.isHidden.toggle()
if !showPassword.isHidden {
showPassword.stringValue = password.stringValue
showPassword.becomeFirstResponder()
} else {
password.stringValue = showPassword.stringValue
password.becomeFirstResponder()
}
}
}
show/hide password sample

if statement returning a value not working for UiLabel

my fairly new to swift and programming, I'm trying to display a value from an if statement. Here is my func within my UiLabel. I've tried a few variations along the same lines but it only every returns "calculate.fuelTank" it never seems to trigger the second part to my IF statement?
#IBOutlet weak var startingFuelDisplay: UILabel! //not working yet
func refreshUiopeningFuel() {
if calculate.totalFuel <= Double(calculate.fuelTank) {
print (Double(calculate.fuelTank)) // FuelTank
} else {
print (calculate.totalFuel) // TotalFuel
}
Do I need to add a bool argument to trigger "else"? I have also tried using the "return" function with initialised string which included the value I was trying to extract, finally I need this to work for another display.
here is my full view controller code (i'm new I'm sure it could be cleaner)
import UIKit
class ViewController: UIViewController {
let calculate = Inputs ( raceLaps: 13, fuelRate: 3.7, fuelTank: 110, laptime: 85.456, tyreWear: 0.05 )
#IBOutlet weak var rate: UITextField!
#IBOutlet weak var laps: UITextField!
#IBOutlet weak var tank: UITextField!
#IBOutlet weak var tyreWear: UITextField!
#IBOutlet weak var laptime: UITextField!
#IBOutlet var cancelKeyboard: UITapGestureRecognizer!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Looks for single or multiple taps.
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
view.addGestureRecognizer(tap)
}
//Calls this function when the tap is recognized.
func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
refreshUiFuel()
refreshUiStops()
refreshUiTyreLife()
refreshUiTyreLifeLaps()
refreshUiopeningFuel()
refreshUiBoxOnLap ()
}
#IBAction func calculate(sender: UIButton) {
if let rateVal = Double(rate.text!),
tankVal = Int(tank.text!),
lapVal = Int(laps.text!),
wearVal = Double(tyreWear.text!),
laptimeVal: Float = 85.456 {
let fuelModel = Inputs(raceLaps: lapVal, fuelRate: rateVal, fuelTank: tankVal, laptime: laptimeVal, tyreWear: wearVal )
totalFuelDisplay.text = ("\(Double(fuelModel.totalFuel))")
totalStopsDisplay.text = ("\(Int(fuelModel.totalStops))")
tyreLifeDisplay.text = ("\(Int(fuelModel.tyreChangesRaceDistanceTotal))")
tyreLifeLapsDisplay.text = ("\(Int(fuelModel.tyreLife))")
startingFuelDisplay.text = ("\(refreshUiopeningFuel())")
}
else {
totalFuelDisplay.text = "missing value"
totalStopsDisplay.text = "missing value"
tyreLifeDisplay.text = "missing value"
tyreLifeLapsDisplay.text = "missing value"
startingFuelDisplay.text = "missing Value"
}
}
#IBOutlet weak var totalFuelDisplay: UILabel!
func refreshUiFuel()->String {
return totalFuelDisplay.text!
}
#IBOutlet weak var totalStopsDisplay: UILabel!
func refreshUiStops()->String {
return totalStopsDisplay.text!
}
#IBOutlet weak var tyreLifeDisplay: UILabel!
func refreshUiTyreLife()->String {
return tyreLifeDisplay.text!
}
#IBOutlet weak var tyreLifeLapsDisplay: UILabel!
func refreshUiTyreLifeLaps()->String {
return tyreLifeLapsDisplay.text!
}
#IBOutlet weak var pitOnLapDisplay: UILabel!
func refreshUiBoxOnLap () {
}
#IBOutlet weak var startingFuelDisplay: UILabel! //not working yet
func refreshUiopeningFuel() ->Double {
print(calculate.fuelTank)
print(calculate.totalFuel)
if calculate.totalFuel <= Double(calculate.fuelTank) {
return Double(calculate.fuelTank) // FuelTank
} else {
return calculate.totalFuel // TotalFuel
}
}
}
all helped welcomed
Judging from the natural real-world logic, it appears you've simply reversed the if/else logic. It would seem that if totalFuel is less than the tank's capacity (the if clause), you should return totalFuel in that case, and return the tank capacity in the else clause.

In Swift how do I convert int to string and reverse and display result?

The program is suppose to change F TO C and reverse. With the Switch it changes from on to off and on is suppose to be C to f and off is F to c and entering the # underneath in the text field.
When clicking the submit button it takes whats in the text field transfers it to an in preforms the algorithm and then displays it in the textfield.
I believe the conversion is going correctly but will not display the actual result. Or the way its being converted is wrong.
#IBOutlet weak var buttonClicked: UIButton!
#IBOutlet weak var mySwitch: UISwitch!
#IBOutlet weak var myTextField: UITextField!
#IBOutlet weak var User: UITextField!
func stateChanged(switchState: UISwitch) {
if switchState.on {
myTextField.text = "Convert to Celius"
} else {
myTextField.text = "Convert to Farheniet"
}
}
#IBAction func buttonClicked(sender: UIButton) {
if mySwitch.on {
var a:Double? = Double(User.text!)
a = a! * 9.5 + 32
User.text=String(a)
mySwitch.setOn(false, animated:true)
} else {
var a:Double? = Double(User.text!)
a = a! * 9.5 + 32
User.text=String(a)
mySwitch.setOn(true, animated:true)
}
}
I am using an older version of XCode(6.4) so my code will be a little bit different from yours. From what I understand your function buttonClicked should take the argument of AnyObject instend of UIButton. Also you do not call the function stateChanged in your code at all. The following code should help achieve what you trying to do.
#IBOutlet weak var mySwitch: UISwitch!
#IBOutlet weak var myTextField: UITextField!
#IBOutlet weak var User: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// sets the textfield to the intended conversion on load.
if mySwitch.on {
myTextField.text = "Convert to Celius"
}
else {
myTextField.text = "Convert to Farheniet"
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// changes the myTextFiled text to the intended conversion when the switch is manually switched on or off
#IBAction func switched(sender: AnyObject) {
if mySwitch.on {
myTextField.text = "Convert to Celsius"
}
else {
myTextField.text = "Convert to Fahrenheit"
}
}
// changes the myTextField text to intended reverse conversion after the buttonClicked func is completed.
func stateChanged(switchState: UISwitch) {
if switchState.on {
myTextField.text = "Convert to Celsius"
}
else {
myTextField.text = "Convert to Fahrenheit"
}
}
// do the intended conversion(old version of XCode 6.4)
#IBAction func buttonClicked(sender: AnyObject) {
if mySwitch.on {
var a = (User.text! as NSString).doubleValue
a = (a-32)*(5/9)
User.text="\(a)"
mySwitch.setOn(false, animated:true)
stateChanged(mySwitch)
}
else {
var a = (User.text! as NSString).doubleValue
a = a * (9/5) + 32
User.text="\(a)"
mySwitch.setOn(true, animated:true)
stateChanged(mySwitch)
}
}