comparing local images swift - swift

"Optional type Bool cannot be used as a boolean; test for !nil instead"
Is the error I'm getting
I'm trying to make a "slot machine" app, very basic,
You press the UIButton, and the three images should all change, randomly, if the 3 matches, print "You won!"
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var img1: UIImageView!
#IBOutlet weak var img2: UIImageView!
#IBOutlet weak var img3: UIImageView!
#IBOutlet weak var rollBtn: UIButton!
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.
}
#IBAction func onRollPress(sender: AnyObject) {
let randomRoll = ImgArray().getRandomImage()
img1.image = randomRoll
img2.image = randomRoll
img3.image = randomRoll
if (img1.image! == img2 && img3) {
print("You won!")
}
}
}

If your images are in an array, why not get the indexes of the images and compare that. Or you could convert the images to base64 strings and compare those.
Edit: Not knowing much about your ImgArray class, this may work for you:
#IBAction func onRollPress(sender: AnyObject) {
let randomRoll1 = ImgArray().getRandomImage()
let randomRoll2 = ImgArray().getRandomImage()
let randomRoll3 = ImgArray().getRandomImage()
img1.image = randomRoll1
img2.image = randomRoll2
img3.image = randomRoll3
let imgIndex1 = ImgArray().indexOf(randomRoll1)
let imgIndex2 = ImgArray().indexOf(randomRoll2)
let imgIndex3 = ImgArray().indexOf(randomRoll3)
if (imgIndex1 == imgIndex2 && imgIndex3) {
print("You won!")
}
}

Related

How to fix 'Swift Protocols/Delegates setting UIImages - Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value'?

I am letting the user choose a background image upon sign in. Base on user choice of image selection, I want to show another view controller with the image that the user selected. I follow some examples from youtube but I am getting 'Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value' and the image is not set.
protocol SelectionImageDelegate {
func setBackgroundImage(selectedImage: UIImage)
}
class SelectBackgroundViewController: UIViewController {
// MARK: IBOutlets
#IBOutlet weak var snowBackgroundImage: UIImageView!
#IBOutlet weak var desertBackgroundImage: UIImageView!
#IBOutlet weak var pathwayBackgroundImage: UIImageView!
#IBOutlet weak var beachBackgroundImage: UIImageView!
// MARK: Properties
var imageSelectionDelegate: SelectionImageDelegate!
// MARK: Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
self.imageSelectionDelegate = FootprintViewController()
setButtonCorners()
}
override func viewWillAppear(_ animated: Bool) {
snowBackgroundImage.center.x -= view.bounds.width
desertBackgroundImage.center.x -= view.bounds.width
pathwayBackgroundImage.center.x -= view.bounds.width
beachBackgroundImage.center.x -= view.bounds.width
}
#IBAction func didTappedSnowBackground(_ sender: Any) {
print("tapped snow")
imageSelectionDelegate.setBackgroundImage(selectedImage: UIImage(named: "Snow_Background")!)
print("set image")
let vc = (self.storyboard?.instantiateViewController(withIdentifier: "FootprintVC"))!
self.presentViewController(vc)
}
#IBAction func didTappedDesertBackground(_ sender: Any) {
imageSelectionDelegate.setBackgroundImage(selectedImage: UIImage(named: "Desert_Background")!)
let vc = (self.storyboard?.instantiateViewController(withIdentifier: "FootprintVC"))!
self.presentViewController(vc)
}
#IBAction func didTappedPathwayBackground(_ sender: Any) {
imageSelectionDelegate.setBackgroundImage(selectedImage: UIImage(named: "Pathway_Background")!)
let vc = (self.storyboard?.instantiateViewController(withIdentifier: "FootprintVC"))!
self.presentViewController(vc)
}
#IBAction func didTappedBeachBackground(_ sender: Any) {
imageSelectionDelegate.setBackgroundImage(selectedImage: UIImage(named: "Beach_Background")!)
let vc = (self.storyboard?.instantiateViewController(withIdentifier: "FootprintVC"))!
self.presentViewController(vc)
}
}
class FootprintViewController: UIViewController {
// MARK: IBOutlets
#IBOutlet weak var backgroundImageView: UIImageView!
#IBOutlet weak var emptyFootprintImageView: UIImageView!
// MARK: Life Cycles
override func viewDidLoad() {
super.viewDidLoad()
}
}
extension FootprintViewController: SelectionImageDelegate {
func setBackgroundImage(selectedImage: UIImage) {
backgroundImageView.image = selectedImage
}
}
class FootprintViewController: UIViewController {
// MARK: IBOutlets
#IBOutlet weak var backgroundImageView: UIImageView!
#IBOutlet weak var emptyFootprintImageView: UIImageView!
// MARK: Life Cycles
override func viewDidLoad() {
super.viewDidLoad()
}
}
extension FootprintViewController: SelectionImageDelegate {
func setBackgroundImage(selectedImage: UIImage) {
backgroundImageView.image = selectedImage
}
}
Please try to set optinal imageSelectionDelegate in SelectBackgroundViewController like this;
var imageSelectionDelegate: SelectionImageDelegate?
"implicitly unwrapping" means that you are trying to access an "implicitly unwrapped optional" value, which does not hold a value but is nil.
In your case, you are dealing with two optionals:
The delegate imageSelectionDelegate might not be set.
UIImage(named: "Snow_Background") might return nil
Accessing the delegate - if nil would result in the Unexpectedly found nil while implicitly unwrapping an Optional value error, while accessing the image - if nil - would result in Unexpectedly found nil while unwrapping an Optional value
So, since you observe the first error, the delegate is nil, which seems strange because you set it in viewDidLoad.
To investigate a little more, you could add some more trace information to your action handler, to check what happens:
#IBAction func didTappedSnowBackground(_ sender: Any) {
print("tapped snow")
guard imageSelectionDelegate != nil else {
print ("delegate is not set")
return
}
guard let bgImage = UIImage(named: "Snow_Background") else {
print ("Snow_Background image does not exist")
return
}
imageSelectionDelegate.setBackgroundImage(selectedImage: bgImage)
print("set image")
let vc = (self.storyboard?.instantiateViewController(withIdentifier: "FootprintVC"))!
self.presentViewController(vc)
}
Then check the output.

Cannot convert value of type 'String?' to type 'NSString' in coercion

Im trying to make this calculator for various math formulas and I'm stuck at this point. I was following this tutorial
Here's my code:
import UIKit
class pythagorasViewController: UIViewController {
#IBOutlet weak var aLabel: UILabel!
#IBOutlet weak var bLabel: UILabel!
#IBOutlet weak var aField: UITextField!
#IBOutlet weak var bField: UITextField!
#IBOutlet weak var answerLabel: UILabel!
#IBAction func calculateButton(_ sender: UIButton) {
var a = (aField.text as NSString).floatValue
var b = (bField.text as NSString).floatValue
var answer = sqrt(a*a + b*b)
answerLabel.text = "\(answer)"
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The part where I'm getting the error is at:
var a = (aField.text as NSString).floatValue
var b = (bField.text as NSString).floatValue
Prefer let to var when possible. You do not need to use NSString. You can cast String to Float?. You need to unwrap both the text property which is a String? (if you have a question about the type of a variable option click and it will show you) and the Float? conversion:
func calculateButton(_ sender: UIButton) {
guard let aText = aField.text,
let bText = bField.text,
let a = Float(aText),
let b = Float(bText) else {
return
}
let answer = sqrt(a*a + b*b)
answerLabel.text = "\(answer)"
}

How can I add several UIStepper Values to one Label?

I'm working right now on my first Swift project. I've got 2 stepper and one label - both stepper are sending their values to it. How can I add the value of the second stepper to the label, in which the value of the first stepper is already? Here is my code:
override func viewDidLoad() {
super.viewDidLoad()
stepper.wraps = true
stepper.autorepeat = true
stepper.maximumValue = 10000
stepper2.wraps = true
stepper2.autorepeat = true
stepper2.maximumValue = 10000
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBOutlet weak var valueLabel: UILabel!
#IBOutlet weak var stepper: UIStepper!
#IBAction func stepperValueChanged(sender: UIStepper) {
valueLabel.text = Int(sender.value).description
}
#IBOutlet weak var stepper2: UIStepper!
#IBAction func stepper2ValueChanged(sender: UIStepper) {
valueLabel.text = Int(sender.value).description
}
}
Thank you!
If you want to combine the two values to ONE String and show this String on your Label, than you have to create a new function that does this for you. I added such a function to your code:`
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
stepper.wraps = true
stepper.autorepeat = true
stepper.maximumValue = 10000
stepper2.wraps = true
stepper2.autorepeat = true
stepper2.maximumValue = 10000
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBOutlet weak var valueLabel: UILabel!
#IBOutlet weak var stepper: UIStepper!
#IBAction func stepperValueChanged(sender: UIStepper) {
// valueLabel.text = Int(sender.value).description
addValuesToASumAndPutItIntoTheLabel()
}
#IBOutlet weak var stepper2: UIStepper!
#IBAction func stepper2ValueChanged(sender: UIStepper) {
// valueLabel.text = String(sender.value)
addValuesToASumAndPutItIntoTheLabel()
}
func addValuesToASumAndPutItIntoTheLabel() {
let summe : Int = Int(stepper.value + stepper2.value)
valueLabel.text = summe.description
}
}`

Thread1: Exc_Bad_Instruction

I can't figure out why am I keep getting this Thread:
Error message when running this program.
I'm new to programming and trying an exercise and keep getting this error message.
Also I was trying to figure out how to resize the pictures to fit on the screen.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var memberChoice: UISegmentedControl!
#IBOutlet weak var webView: UIWebView!
#IBAction func getMember(sender:AnyObject){
var member: String =
memberChoice.titleForSegmentAtIndex(memberChoice.selectedSegmentIndex)!
var imageURLString: String!
if member == "Daddy" {
imageURLString = "file: ///Users/natashamays/Desktop/Daddy.jpg"
}
else if member == "Tasha" {
imageURLString = "https://lh3.googleusercontent.com/-2c_GDVdcAFk/UBR7auHIHrI/AAAAAAAAEW8/gJ3F-MVUpL4/w140-h139-p/3.jpg"
}
else if member == "Jasmin" {
imageURLString = "file:///Users/natashamays/Desktop/IMG_3879.JPG"
}
var imageURL: NSURL = NSURL(string:imageURLString)!
webView.loadRequest(NSURLRequest(URL: imageURL))
}
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.
}

Parse.com for Xcode to make simple app like trivia crack type

//
// ViewController.swift
// AP Attack
//
// Created by ddfulton on 5/8/15.
// Copyright (c) 2015 ddfulton. All rights reserved.
//
import UIKit
import Parse
class ViewController: UIViewController {
var Question: String!
var Answers: [String]!
var Answer: String!
#IBOutlet weak var QuestionLabel: UILabel!
#IBOutlet weak var Button1: UIButton!
#IBOutlet weak var Button2: UIButton!
#IBOutlet weak var Button3: UIButton!
#IBOutlet weak var Button4: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
CallData()
}
func CallData(){
var query : PFQuery = PFQuery(className: "QuestionsandAnswers")
query.getObjectInBackgroundWithId("Mo4HYEB8EC"){
(ObjectHolder : PFObject!, error : NSError!) -> Void in
if (error == nil){
self.Question = ObjectHolder["Question"] as String!
self.Answers = ObjectHolder["Answers"] as Array!
self.Answer = ObjectHolder["Answer"] as String!
if (self.Answers.count > 0){
self.QuestionLabel.text = self.Question
self.Button1.setTitle(self.Answers[0], forState : UIControlState.Normal)
self.Button2.setTitle(self.Answers[1], forState : UIControlState.Normal)
self.Button3.setTitle(self.Answers[2], forState : UIControlState.Normal)
self.Button4.setTitle(self.Answers[3], forState : UIControlState.Normal)
}
}
else{
NSLog("Error. Wrong!")
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func Button1Action(sender: AnyObject) {
}
#IBAction func Button2Action(sender: AnyObject) {
}
#IBAction func Button3Action(sender: AnyObject) {
}
#IBAction func Button4Action(sender: AnyObject) {
}
}
That's my entire code. My Parse.com is organized as objectId, createdAt, updatedAt, ACL, Questions (string), Answers (array of strings), Answer (string but its value is a number.)
https://www.youtube.com/watch?v=3Yeicy7wCBA this is the youtube video that I'm following directly.
I know I'm definitely missing something, otherwise it would work, but I'm just having a shitty time debugging it.
I had the same problem. Spent a half a day on this one. I made two changes.
Check on Parse and make sure that your Answer column is named "Answer". Mine was named "Array", and that was screwing me up.
I tinkered with the optionals and their exclamation points and question marks. See the code below.
(ObjectHolder : PFObject?, error : NSError?) -> Void in
if (error == nil){
self.Question = ObjectHolder?["Question"] as! String
self.Answers = ObjectHolder?["Answers"] as! Array
self.Answer = ObjectHolder?["Answer"] as! String