So I'm practicing coding and I've set up an array of strings. What I want to happen is to have a function randomly select a string and if a certain string is selected, it would print out one message, and if any of the other strings are selected, it would print out a different one. I think setting up the messages could be done w/an if-else function, but I'm stuck on the earlier step of figuring out how to identify which string is called.
I did some searching and found this thread Get Random String from an Array and I copied the randomization code from it. I'm a bit overwhelmed with where to go from there.
What type of function/identifier etc would I need to set up so that the strings are uniquely identified?
class ViewController: UIViewController {
// Make collection of games and if Monsters is called, print "Take a break." If a diff string is called, print "Do your homework."
#IBAction func random(_ sender: UIButton) {
let games = ["Cards Against Humanity", "Mario Kart", "Halo", "Pixeljunk Monsters"]
let randomNumber = Int(arc4random_uniform(UInt32(games.count)))
_ = games[randomNumber]
}
} // end of class
Your expectation is not very clear from your question, but I guess you are beginner and need a help with processing randomly selected string.
#IBAction func random(_ sender: UIButton) {
let games = ["Cards Against Humanity", "Mario Kart", "Halo", "Pixeljunk Monsters"]
let randomNumber = Int(arc4random_uniform(UInt32(games.count)))
let randomlyPickedString = games[randomNumber]
if randomlyPickedString == "Cards Against Humanity" {
print("Print anything you want about Cards Against Humanity")
}
else if randomlyPickedString == "Mario Kart" {
print("Print anything you want about Mario Kart")
}
else if randomlyPickedString == "Halo" {
print("Print anything you want about Halo")
}
else {
print("Print anything you want about Pixeljunk Monsters")
}
}
If its a finite set of values in array, you can even decide to use switch
Related
I have two UITextFields that get the placeHolder.text randomly from an array. The part I am stuck on, is having an element in an array of answers, correspond to the placeHolder text.
Meaning: placeHolder.text is a question, user text input is the answer, and we check that the user answer is the same as the hard coded value.
sample code:
let questionArray = ["name of your cat?", "name of your other cat?"]
let questionArray2 = { more stupid questions ]
let answerArray = ["cat damen", "diabetes"]
let answerArray2 = [ more stupid answers ]
var answerContainer: String()
var answerContainer2: String()
uitextField1.placeHolder = questionArray.randomElement()
uitextField2.placeHolder = questionArray2.randomElement()
Heres where I get stupid :
func answerGenerator {
if UItextField1.placeHolder == questionArray[0] {
answerContainer = answerArray[0]
}
}
func submit(_ sender: UIButton) {
if uitextField.text == answerContainer && uitextField2.text == answerContainer2 {
do good stuff
}
}
I tried using a dictionary, but got stuck. I also thought about an Enum / Switch Case, but also got stuck as I have two textFields that need the placeHolder generated randomly.
so what happens is the actual answer that's supposed to be allocated to its question, maybe it happens, but I'm not grabbing it correctly to compare what the user will type in the textfield.
Its so easy, but I'm overthinking this.
I am facing the problem that I fill up an array with data and when I want to remove it later, even though I call the removeAll() the array still is not empty.
Better see my code for a more clear view on the problem
Updated new code
#objc func textFieldDidChange() {
doSearch()
if let commentText = commentTextField.text , !commentText.isEmpty {
sendButton.setTitleColor(UIColor.blue, for: UIControlState.normal)
sendButton.isEnabled = true
return
}
sendButton.setTitleColor(UIColor.lightGray, for: UIControlState.normal)
sendButton.isEnabled = false
}
func doSearch() {
let caption = commentTextField.text
let words = caption?.components(separatedBy: CharacterSet.whitespacesAndNewlines)
self.usersSuggestion.removeAll()
for var word in words! {
self.usersSuggestion.removeAll()
if word.hasPrefix("#") {
word = word.trimmingCharacters(in: CharacterSet.punctuationCharacters)
self.isCellSelected = true
self.usersSuggestion.removeAll()
API.User.suggestUsers(withText: word, completion: { (user) in
print("closure", word)
self.usersSuggestion.append(user)
self.tableView.reloadData()
print("#", self.usersSuggestion.count)
})
self.usersSuggestion.removeAll()
tableView.reloadData()
} else {
self.isCellSelected = false
self.usersSuggestion.removeAll()
tableView.reloadData()
}
self.usersSuggestion.removeAll()
tableView.reloadData()
}
}
I am facing the problem here that the array, even though I call multiple times the removeAll() method, never gets back to 0. When I have 2 user, link one, the next time I write an # I get the 2 users+ the linked user (so him twice). I can do it infinitely, having like 100 userSuggestions with just 2 existing users.
photos
You are printing the count immediately after inserting an element in the array. This will alway give a count of 1.
// count was zero
self.hashTags.insert(hashTag, at: 0) // adding one
print("# = ", self.hashTags.count) // count is now 1
Given that the API.user... function uses a completion handler, I would assume that this happens in a separate thread or at least asynchronously so you could event get into situations where the UI shows empty and suddenly shows one.
You may want to structure your code differently to better convey the separation between requesting data and displaying the (asynchronously obtained) results. Embedded completion handlers tend be misleading and give the impression that execution will happen in their visually organized sequence.
I'm a newbie to swift and believe me I've searched and searched for an answer already. I want to create UISliders that get their values from an array of numbers in Swift. Its a camera app so the example array should be obvious.
#IBAction func isoValueChanged(sender: UISlider) {
let isoArray = ["24", "32", "50","64","80","100","125","160","200","250","320","400","500","640","720","800","1000","1250","1600","1800"] // available iPhone 6s ISO settings I believe
let currentValue = // What do I need?
isoText.text = "\(currentValue)"
}
Even harder would be representing shutter speeds from 1/1000 - 32!
From what I see out there this is not an easy one because there is no mathematical representation to calc from the array. Is it even possible?
I'm not quite sure I understand what you want this for but I'm guessing this is right.
// Global Variable or something like this (accessible from multiple functions)
let isoArray = ["24", "32", "50","64","80","100","125","160","200","250","320","400","500","640","720","800","1000","1250","1600","1800"] // available iPhone 6s ISO settings I believe
func functionThatCreatesTheSliderYo(...) {
slider.minimumValue = 0
slider.maximumValue = isoArray.count
slider.continuous = false
}
#IBAction func isoValueChanged(sender: UISlider) {
// instead of Int(val) you may want to round(val) for a better UI
let currentValue = isoArray[Int(sender.value)]
isoText.text = "\(currentValue)"
}
This works for me
#IBAction func isoValueChanged(sender: UISlider) {
let isoArray = ["24", "32", "50","64","80","100","125","160","200","250","320","400","500","640","720","800","1000","1250","1600","1800"]
let currentValue = isoArray[Int(sender.value)]
isoText.text = "\(currentValue)"
}
So simple as it should be in Swift. Many thanks to Ty. Be sure to see the chat though.
I'm trying to learn swift by creating different short games or apps. while trying to test my new gain knowledge on a game, I realized that I need to create a func that I didnt know how to create. I've looked around and none of the answers I've found really helped me understand what I have to do.
I'll summarize my game:
Its a single view app.
I've got five func.
I want to randomly pick a function to be executed.
After the function is executed the user will press a button that runs the random pick function again to randomly pick a func, but this time only out of the four other func that are left, and so on. At the same time once the five functions have been executed I want to restart the pick a random func all over again. so the game goes on and on for ever.
I'm not sure how to place the func In an array to make it work.
For example I've been using the following script in the game.
Func one generates a Label that shows a random string.
I've used the following script to create a random word generator for a label with out repeats and once it runs through all the words in the array it restarts again randomly. (It works perfectly)
struct randword {
var wordstring : String! }
var stentenceword = [randword]
var stentecenumber = Int
func wordsinsentence (){
sentenceword = [randoword(wordstring:"House"), randoword(wordstring:"Truck"), randoword(wordstring:"Ladder")]
}
func pickword(){
if sentenceword.count > 0 {
sentencenumber = random () % sentenceword.count
wordlabel.text = sentecneword[sentencenumber].wordstring
sentenceword.removeAtIndex(sentencenumber)
); if sentenceword.count <= 0{
wordsinsentence() }
Func two generates a random Image using the same script as before, just slightly modified for images.
Func three is a timer game with another script... and so on..etc etc.
Now I want all five func to randomly be picked and removed then once there aren't anymore left to restart, as on the example script I placed above.
I've tried using the same script and modifying it to replace the string! array with a function array, but with no positive result.
Can anyone help me with a solution or showing me another option of how I should do it?
Your question is a little difficult to follow, but let's focus on your most clear questions:
I'm not sure how to place the func In an array to make it work.
I want to randomly pick a function to be executed.
no repeats
First, to pick values randomly with no repeats you take a list and shuffle it into a random order. There's no need to keep track of previously selected items. Shuffling in Swift is explained very well by Nate Cook at How do I shuffle an array in Swift?
So that brings us to the second question, how do we create an array of functions? That's the simplest part. You just make an array of functions.
func first() { print("first") }
func second() { print("second") }
func third() { print("third") }
let fs = [first, second, third]
That's all there is to it. Now let's put them together and call them in a random order:
for f in fs.shuffle() {
f()
}
I tried to copy paste your code to a playground and try to fix it but its kinda unreadable. Indentation is really good habit especially if someone else has to look at your code. Anyway imagine if you could just say Int.radomOutOf(5) and it just returns some random number between 0 and 5. well you can do just that by adding extension to the class Int or CGFloat or Double as you wish. and have function to keep track of your the games life time and call those random functions. here is how to do it (I hope I didn't forget anything)
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var textLabel: UILabel!
var randomIndex = Int()
let NumberOfFunctions = 4
var chosenIndexes: [Int] = []{
didSet{
if chosenIndexes.count == NumberOfFunctions { chosenIndexes.removeAll() }
}
}
#IBAction func buttonPressed(sender: UIButton) {
functionSelector()
}
func functionSelector(){
repeat{
randomIndex = Int.randomOutOf(NumberOfFunctions)
print("selected: \(randomIndex) \(chosenIndexes)")
} while chosenIndexes.contains(randomIndex)
chosenIndexes.append(randomIndex)
switch randomIndex {
case 0: function1()
case 1: function2()
case 2: function3()
case 3: function4()
default: break
}
}
func function1(){
textLabel.text = "sentence 1"
}
func function2(){
textLabel.text = "sentence 2"
}
func function3(){
textLabel.text = "sentence 3"
}
func function4(){
textLabel.text = "sentence 4"
}
}
//your extension to pick random
private extension Int {
static func randomOutOf(max:Int) ->Int{
print("max: \(max)")
return Int(arc4random() % UInt32(max)) // returns 0 - max
}
}
This is just to show the first answer runs just fine
I've written a small class that uses AVFoundation to play audio using an array. Basically an new element is appended to the array every time 'playAudio' is called. This allows multiple sounds to play without cutting each other off. Also, so that the array doesn't infinitely increase in size I've set it to cycle back to index 0 after filling 5 slots in the array. Now everything works perfectly but after 'audioPlayer' has been called a bunch of times, audio suddenly stops and I start getting the 'Error' in the Catch section but my app continues to function normally as if it has just been muted. Can anyone tell me why this is happening?
var audioIndexA = 0
public class AudioPlayer: NSObject {
var playerA = [AVAudioPlayer]()
func playAudio(audioFile audioFile: String){
do{
let path = NSBundle.mainBundle().pathForResource(audioFile, ofType:"wav")
let fileURL = NSURL(fileURLWithPath: path!)
playerA.insert(try AVAudioPlayer(contentsOfURL: fileURL, fileTypeHint: nil), atIndex: audioIndexA)
playerA[audioIndexA].prepareToPlay()
if audioIndexA < 5{
playerA[audioIndexA].play()
audioIndexA++
} else{
playerA[audioIndexA].play()
audioIndexA = 0
}
} catch{
print("Error")
}
}
}