Check for identical values swift - arrays

I'm trying to make a memory game where I apply images to 12 different buttons and check if the images are the same when 2 buttons are showing.
-------------------FINISHED FORM?-------------------------
Here is a try at Duncan C's suggestion;
func setImages() {
var values = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6]
values.shuffleInPlace()
button1.tag = values[0]
button2.tag = values[1]
button3.tag = values[2]
button4.tag = values[3]
button5.tag = values[4]
button6.tag = values[5]
button7.tag = values[6]
button8.tag = values[7]
button9.tag = values[8]
button10.tag = values[9]
button11.tag = values[10]
button12.tag = values[11]
}
#IBAction func buttonPressed(sender: UIButton) {
var images : [UIImage] = [
UIImage(named:"ye1")!,
UIImage(named:"ye2")!,
UIImage(named:"ye3")!,
UIImage(named:"ye4")!,
UIImage(named:"ye5")!,
UIImage(named:"ye6")!,
UIImage(named:"ye7")!,
UIImage(named:"ye8")!,
UIImage(named:"ye9")!,
UIImage(named:"ye10")!,
UIImage(named:"ye11")!,
UIImage(named:"ye12")!
]
images.shuffleInPlace()
let integrera = (sender.tag - 1)
let imageString:String = String(format: "ye%i", integrera)
if !firstButtonAlreadyPresssed {
firstButtonValue = sender.tag //remember the button for later
firstButtonAlreadyPresssed = true
sender.setImage(UIImage(named: imageString), forState: .Normal)
}
else
//We already have a first button pressed.
if sender.tag == firstButtonValue {
sender.setImage(UIImage(named: imageString), forState: .Normal)
}
else {
let secondimage = (sender.tag)
let secondString : String = String(format: "ye%i", secondimage)
sender.setImage(UIImage(named: secondString), forState: .Normal)
}
firstButtonAlreadyPresssed = false //reset the "isFirstButton" flag for the next time.
}
}

Hmm, there are a bit of lengthy and repetitive code here I believe. You can just add all buttons to the same #IBAction func. So you can have one #IBAction func buttonPressed(sender: UIButton) rather than 12 like you have now (I think, since your function is called #IBAction func button1PRESSED(sender: AnyObject)). So when you first click a button you store the button, and also store if its the first or second button clicked. When you click the second button you check if it has the same UIImage as the first one clicked, otherwise you what ever it is you are supposed to do.
#IBAction func buttonPressed(sender: UIButton) {
if self.firstButtonStored == true {
if self.firstButton.image == sender.image {
// They are the same
} else {
// they are not the same
}
} else {
self.firstButtonStored = true
self.firstButton = sender
}
}
I would also recommend storing all the buttons in one OutletCollection (works like an array) rather than 12 buttons in self. And I would also use something else than UIImage to check if they are the same, not sure if this actually works since you need the image name and not the image itself to make a comparison. Let me know if you need help.

Don't, dont, DON'T create 12 separate variables, card1-card12 and 12 IBActions button1PRESSED-button12PRESSED. This kind of thing where you have lots of exactly the same thing where the only thing that changes is a value is a "code smell". It tells you you are doing it wrong.
Instead, you should find a way to do it where you can use the same IBAction for all the buttons, and index into the array rather than having 12 separate variables.
I would suggest using tags on your buttons. Have button 1 use tag 1, button 2 use tag 2, etc.
Then in your IBAction, fetch the tag from the button and use that to figure out which button was pressed and what to do.
You will also need a flag that tells you if this was the first button pressed or the second, so you can tell if you need to test for matches (if it's the 2nd one) or just remember which one was pressed (if this is the first button pressed.)
var firstButtonValue: Int
var firstButtonAlreadyPresssed: Bool
#IBAction func buttonPressed(sender: UIButton)
{
if !firstButtonAlreadyPresssed
{
firstButtonValue = sender.tag //remember the button for later
firstButtonAlreadyPresssed = true
}
else
{
//We already have a first button pressed.
if sender.tag == firstButtonValue
{
//right answer. Handle it.
}
else
{
//wrong answer. Handle it.
}
firstButtonAlreadyPresssed = false //reset the "isFirstButton" flag for the next time.
}
}
You could have an array of the images to use for each value, and then fetch that image based on the value of firstButtonValue or sender.tag.

An approach, not a full solution
Create a struct Card with value and index properties and make it Equatable by value.
You can add more properties like done, status, image or whatever.
struct Card : Equatable, CustomStringConvertible {
let value : Int
let index : Int
var description : String { return "Card \(index)"}
}
func ==(lhs: Card, rhs: Card) -> Bool
{
return lhs.value == rhs.value
}
Shuffle the values and create an array of 12 cards
var values = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6]
values.shuffleInPlace()
var cards = [Card]()
for (index, value) in values.enumerate() {
cards.append(Card(value: value, index: index))
}
Implement a method to find the corresponding card
func twinCard(card : Card) -> Card {
return cards.filter({$0 == card && $0.index != card.index}).first!
}
In Interface Builder assign tags from 0 to 11 to the twelve buttons and connect all buttons to the same #IBAction
#IBAction func buttonPressed(sender: UIButton) {
let tag = sender.tag
let chosenCard = cards[tag]
let otherCard = twinCard(chosenCard)
// The following depends on the design of the UI
// for example get the corresponding button by viewWithTag(otherCard.index)
// or use an array which holds the button references.
...
}
Don't shuffle the view, shuffle the model ;-)

Related

Save button states when we move segmented control

We have for example segmented control, and array of buttons. If we select one of button in one segment - button need to save state, and than we move to another segment and choose another button. but if we back to previous button - it should be in the position we chose earlier.
that is, each of the segments must store the state of the buttons.
how to do it better?
struct SegmentsModel {
let title: String
var answered: Bool
var buttonIndex: Int? = nil
}
#objc private func buttonsTapped(_ sender: UIButton) {
let _ = buttons.map({$0.isSelected = false})
sender.isSelected = true
guard let index = buttons.firstIndex(of: sender) else { return }
switch index {
case 0:
selectedSegment(segmentedControl, buttonSelected: true, indexButton: 0)
case 1:
selectedSegment(segmentedControl, buttonSelected: true, indexButton: 1)
case 2:
selectedSegment(segmentedControl, buttonSelected: true, indexButton: 2)
case 3:
selectedSegment(segmentedControl, buttonSelected: true, indexButton: 3)
default:
break
}
}
#objc private func selectedSegment(_ sender: UISegmentedControl,
buttonSelected: Bool, indexButton: Int) {
let currentIndex = sender.selectedSegmentIndex
if buttonSelected == true {
buttons[indexButton].isSelected = true
} else {
let _ = buttons.map({$0.isSelected = false})
}
switch currentIndex {
case 0:
arrayOfSegments[0].answered = buttonSelected
arrayOfSegments[0].buttonIndex = indexButton
case 1:
arrayOfSegments[1].answered = buttonSelected
arrayOfSegments[1].buttonIndex = indexButton
case 2:
arrayOfSegments[2].answered = buttonSelected
arrayOfSegments[2].buttonIndex = indexButton
default:
break
}
}
As I mentioned in my comments, there are many ways to achieve what you want. I will share one idea with you.
I see that you tried to store all your buttons in an array and had to keep looping over them to figure out which button was selected previously. Since you want the code to have simpler logic, I will give you a different idea.
One way to achieve what you want is using tags. Every UIView object has a tag and the default is set to 0.
Using storyboard I set the tag of the buttons to 100, 101, 102, 103 and this can be done programmatically also.
You can choose any integers that you like but it is important to give them some unique numbers so when you try to get a view by tag, you get only the view you want.
So after setting the tags, this is what I updated in the code.
struct SegmentsModel {
let title: String
var answered = false
var buttonIndex: Int? = nil
{
// Auto-update the value of answered when value of buttonIndex changes
didSet
{
answered = buttonIndex != nil
}
}
}
I did not do any major updates here. I only added a property observer so when the button index gets set, the answered variable also is auto set so you don't have to anything more for this
Next, below is all the logic to manage the segments and the buttons. I used UIViewController with a StoryBoard so you might need to ignore somethings.
All the important code has comments so you can follow along.
class ViewController: UIViewController {
// I will store the results in this array
var storedResults: [SegmentsModel] = []
// Segment control outlet
#IBOutlet weak var segmentControl: UISegmentedControl!
// Array of buttons
#IBOutlet var buttons: [UIButton]!
override func viewDidLoad() {
super.viewDidLoad()
// Loop over all segments
for index in 0 ..< segmentControl.numberOfSegments
{
// Initialize and store default results values in storedResults array
if let segmentTile = segmentControl.titleForSegment(at: index)
{
storedResults.append(SegmentsModel(title: segmentTile))
}
}
}
// Segment action
#IBAction func selectedSegment(_ sender: UISegmentedControl)
{
// Update the UI of buttons
reloadButtons()
}
#IBAction func buttonTapped(_ sender: UIButton)
{
// Reset your buttons
let _ = buttons.map({$0.isSelected = false})
// Set the current button to selected
sender.isSelected = true
// Get the current result so we can update it
var currentResult = storedResults[segmentControl.selectedSegmentIndex]
// Update the current segments selected button index using tag
currentResult.buttonIndex = sender.tag
// Put the result back into the array as structs as value types
storedResults[segmentControl.selectedSegmentIndex] = currentResult
}
// Reload button data
private func reloadButtons()
{
// Reset your buttons
let _ = buttons.map({$0.isSelected = false})
let currentResult = storedResults[segmentControl.selectedSegmentIndex]
// Check if current index has a selected button and if it does retrieve it
// with a tag
if let selectedButtonIndex = currentResult.buttonIndex,
let selectedButton = view.viewWithTag(selectedButtonIndex) as? UIButton
{
// Show the selected button in the UI
selectedButton.isSelected = true
}
}
}
The end result achieved can be seen in this youtube video which I believe is what you wanted.

Saving a generated word to an array/list of words when a button is pressed

I bet this is a pretty simple question for most of you so I'll be quick. Essentially my Swift app generates a random word, and I want the users to be able to select buttons labeled 1 2 and 3, and that word is then saved to that particular number in an array. Later on (including after when the app has been closed etc.) the user can view all the words they have assigned a number to. I know it involves creating a new class and placing the respective arrays there but I really have no idea where to start, so any help is appreciated. Sorry if this isn't as clear as you'd like, as you can tell I'm pretty new to Swift/programming. As of right now, all I have related to this part of the app is the buttons:
var chosenNumber : String = ""
#IBAction func chosenOne(_ sender: Any) {
chosenDifficulty = "one"
}
#IBAction func chosenTwo(_ sender: Any) {
chosenNumber = "two"
}
#IBAction func chosenThree(_ sender: Any) {
chosenNumber = "three"
}
thanks
Create a computedProperty In your ViewController that saves if there's a new value and return the saved value when you access it anywhere in your viewController:
var savedWords: [String: Any]? {
set{
guard let value = newValue else {
UserDefaults.standard.removeObject(forKey: "SavedWords")
UserDefaults.standard.synchronize()
return
}
UserDefaults.standard.set(value, forKey: "SavedWords")
UserDefaults.standard.synchronize()
}
get{
return UserDefaults.standard.string(forKey: "SavedWords") as? [String: Any]
}
}
and a dictionary that contains a key-value pair of current words that you're going to add/delete into
var currentWords: [String: Any]? = ["button1": "one","button2": "two","button3": "three"]
Now, whenever your button is clicked you can add your particular word to currentWords dictionary in association with the currentButton key by:
currentWords["button1"] = /*selectedValue from button*/
After assigning if you want to save those currentWords just do
self.savedWords = currentWords
If you want to retrieve savedWords and assign it to currentWords, you can simply do:
self.currentWords = savedWords

How would I view the next image in an array of images?

In this function, I need to change the image of the image view, moving it onto the next image in the array.
private func updateImage(index: Int) {
for x in 0..<urlArray.count
{
let imageUrl:URL = URL(string: "\(urlArray.object(at: x) as! String)")!
let request:URLRequest = URLRequest.init(url: imageUrl)
NSURLConnection.sendAsynchronousRequest(request, queue: OperationQueue.main, completionHandler: { (response, imageDta, error) in
if (error == nil)
{
self.imagesArray.add(UIImage(data: imageDta!)!)
if self.imagesArray.count > 0
{
self.iv.image = self.imagesArray.object(at: 0) as! UIImage
}
}else{
print("ERROR - \(error!)")
}
})
}
}
However, currently, the image being used is set as the image at index 0 in my array. How would I move onto the next image if this function is called multiple times?
This is the line that I mainly need help with:
self.iv.image = self.imagesArray.object(at: 0) as! UIImage
UPDATE: I've tried to add the code Charly Pico suggested to my functions but it doesn't seem to be moving onto the next image in the array, I think it's to do with how it's being called. I'm going to go into detail in how my file is constructed and works to hopefully clarify how I want to use the change image code.
var urlArray:NSMutableArray! = NSMutableArray()
var imagesArray:NSMutableArray! = NSMutableArray()
These arrays which hold the URL's and Images are outside of any function.
func GetTheStories() {
let ref = FIRDatabase.database().reference().child("Content")
ref.observe(FIRDataEventType.value, with: {(snapshot) in
self.fileArray.removeAll()
if snapshot.childrenCount>0{
for content in snapshot.children.allObjects as![FIRDataSnapshot]{
let contentInfo = content.value as? [String: String]
let contentType = contentInfo?["contentType"]
let storyLink = contentInfo?["pathToImage"]
let content = storyLink
self.urlArray = NSMutableArray.init(array:[storyLink])
}
}
})
}
This is the function I call to append the URL's from my Firebase server to the URLSARRAY.
override func viewDidAppear(_ animated: Bool) {
for x in 0..<urlArray.count
{
let imageUrl:URL = URL(string: "\(urlArray.object(at: x) as! String)")!
let request:URLRequest = URLRequest.init(url: imageUrl)
NSURLConnection.sendAsynchronousRequest(request, queue: OperationQueue.main, completionHandler: { (response, imageDta, error) in
if (error == nil)
{
self.imagesArray.add(UIImage(data: imageDta!)!)
if self.imagesArray.count > 0
{
self.iv.image = self.imagesArray.object(at: 0) as! UIImage
}
}else{
print("ERROR - \(error!)")
}
})
}
}
This is the function Charly created and explained which allows me to set the initial image on the ImageView when the screen loads
private func updateImage(index: Int) {
var imageToPresent = 0
for x in 0..<urlArray.count
{
let imageUrl:URL = URL(string: "\(urlArray.object(at: x) as! String)")!
let request:URLRequest = URLRequest.init(url: imageUrl)
NSURLConnection.sendAsynchronousRequest(request, queue: OperationQueue.main, completionHandler: { (response, imageDta, error) in
if (error == nil)
{
self.imagesArray.removeAllObjects()
self.imagesArray.add(UIImage(data: imageDta!)!)
if self.imagesArray.count > 0
{
for x in 0..<self.imagesArray.count
{
if self.iv.image == self.imagesArray.object(at: x) as! UIImage
{
imageToPresent = x + 1
if imageToPresent >= self.imagesArray.count
{
imageToPresent = 0
}
}
}
self.iv.image = self.imagesArray.object(at: imageToPresent) as! UIImage
}
}else{
print("ERROR - \(error!)")
}
})
}
}
This is the function being called to update the image to the next one in the array. However, I believe it's not working either because my attempt to apply Charly's code below is not correct. This function is called in the ViewDidLoad like so
updateImage(index: 0)
And it is called to update the image here. This function is called when the Segmented progress bar changes to the next one.
func segmentedProgressBarChangedIndex(index: Int) {
print("Now showing index: \(index)")
updateImage(index: index)
}
I know it's a bit confusing as to why I'm not using buttons and actions, this is mainly because I'm trying to create an Instagram-style story, with segments that when finished, or the screen is tapped, change the image to the next in the array. I know there's a lot to look over but I think this will explain how I want to use the images array in greater detail.
so, lets say that your imagesArray contains 2 images, what I recommend doing is the following:
//Create a #IBAction and attach it to a UIButton in your Storyboard as a touchUpInside action.
#IBAction func changeImage()
{
//Set a variable with Int as 0.
var imageToPresent = 0
//Create a for to check image by image inside the array.
for x in 0..<imagesArray.count
{
//Compare the image at self.iv with the image in imagesArray at index x. And if the images are the same add a + 1 to imageToPresent.
if self.iv.image == imagesArray.object(at: x) as! UIImage
{
imageToPresent = x + 1
//Check if imageToPresent isn't bigger or equal than imagesArray, otherwise we will get an error and the App will crash.
if imageToPresent >= imagesArray.count
{
//If imageToPreset if bigger or equal to imagesArray.count, it means that there are no more images at a higher index, so we return imageToPresent to 0.
imageToPresent = 0
}
}
}
//Set the new image of imagesArray at index imageToPresent as UIImage to self.iv.
self.iv.image = imagesArray.object(at: imageToPresent) as! UIImage
}
Every time you want to change self.iv image you need to touch the button for the action to be triggered.
UPDATE
So I added a NSTimer to simulate that in 3 seconds your Progress View finishes animating, after the 3 seconds it rotates the image to another one, you can add this code after the for that loads all the images from the urls:
Timer.scheduledTimer(withTimeInterval: 3.0, repeats: true) { (timer) in
self.changeImage()
}
And first of all update your urlArray to this:
urlArray = NSMutableArray.init(array: ["https://firebasestorage.googleapis.com/v0/b/motive-73352.appspot.com/o/Content%2F20170525130622.jpg?alt=media&token=1e654c60-2f47-43c3-9298-b0282d27f66c","https://www.videomaker.com/sites/videomaker.com/files/styles/magazine_article_primary/public/articles/18984/363%20C03%20Lighting%20primary.png"])
So you have at least 2 images to make the image rotation.
change the line to use the index being passed into your function like this
self.iv.image = self.imagesArray.object(at: index) as! UIImage
This function is trying to do a lot of things at once, so it's hard to tell how to make it do what you want, but, you do have an index parameter. Using that instead of the 0 here:
if self.imagesArray.count > index
{
self.iv.image = self.imagesArray.object(at: index) as! UIImage
}
Would wait for that image to load and then set that to the view.
NOTE: you need to check that the index is within bounds

NSTimer in Swift making a label an array value

Hello I am trying to take an array I have and update a label to display each element in the array one second apart. An example would be me having the array [3,6,2] and my label would show 3 then wait a second and show 6 then wait a second and show 2. I've seen many NSTimer examples with update functions doing things like this but only with an incrementation on a number, never trying to parse an array. Can anyone help?
Update
I am calling my timer in a UIButton and am running into a problem. The timer works fine but my code in the button function under my timer runs before the timer and update function. My code below generates a random array of numbers then should display them one second apart. It is doing this correct but my print statement under my timer is running before it updates and displays the numbers in the textbook. I do not know why? Is the timer running on a different thread?
func updateCountdown() {
if(numbersIndex <= numberLimit){
self.counter.text = String(numbers[numbersIndex])
}else if(numbersIndex == numberLimit+1){
self.counter.text = ""
}else{
timer!.invalidate()
timer=nil
}
numbersIndex+=1
}
#IBAction func startButton(_ sender: AnyObject){
startB.setTitle("", for: .normal)
var highestLength = 3
//for trialNumber in 0...11{
var numberSequence = Array(repeating:11, count: highestLength)
for count in 0...highestLength-1{
var randomNumber = Int(arc4random_uniform(10))
if(count>0){
while(numberSequence.contains(randomNumber) || randomNumber-1 == numberSequence[count-1]){
randomNumber = Int(arc4random_uniform(10))
}
}
numberSequence[count] = randomNumber
}
print(numberSequence)
self.numbers = numberSequence
self.numbersIndex = 0
self.numberLimit = numberSequence.count-1
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateCountdown), userInfo: nil, repeats: true)
print("this should be last")
//do other stuff too
//}
}
you can do something like this.
var counter = 0
var list: [String] = ["Eggs", "Milk"]
override func viewDidLoad() {
super.viewDidLoad()
var timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.update), userInfo: nil, repeats: true)
}
func update() {
label.text = "\(list[counter])"
counter += 1
if (counter >= list.count) {
counter = 0
}
}
this is assumming the name of you Label is label

WKPickerItems and ranges

I am trying to make a picker view in Watch Kit from -273 to 273. Sadly Watch Kit only allows a string as title so I converted my range using .map Now when I run the App it display a range from 0 to 546, but will not go into the negative range I tried changing both values but the picker always starts at 0 and won't go back further.
I isolated the problem into these lines:
let pickerItems: [WKPickerItem] = (-273...273).map {
let pickerItem = WKPickerItem()
pickerItem.title = "\($0)"
return pickerItem
}
I just tried it out and your code does show negative values in the picker. Then when the user picks a value you have to take the value and use it to retrieve the "real" value from your pickerItems array:
class InterfaceController: WKInterfaceController {
#IBOutlet var picker: WKInterfacePicker!
var pickerItems: [WKPickerItem]?
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
pickerItems = (-273...273).map {
let pickerItem = WKPickerItem()
pickerItem.title = "\($0)"
return pickerItem
}
picker.setItems(pickerItems)
}
#IBAction func pickerDidChange(value: Int) {
let pickedItem = pickerItems![value] // value = 0..576
if let pickedValue = Int(pickedItem.title!) {
print(pickedValue) // -273..273
}
}
}

Resources