I have an API call that brings an array of CustomDescription. Each element of this array has a name, so, I created the following:
A string array named namArray
A for loop that runs my CustomDescription array, and append it's elements to namArray.
My problem comes when I print my namArray after my for loop, and it just shows one element inside the array, it doesn't append the elements corresponding to the calls.
Here is my code:
func getTypes(typesUrl: String, handler: #escaping([CustomDescription]) -> Void) {
AF.request(typesUrl).validate().responseTypes { (types) in
guard let typeData = types.value,
let typeNames = typeData.names else { return }
var namArray = [String]()
for name in typeNames {
guard let types = name.name else { return }
if name.language?.name == "es" {
namArray.append(types)
}
}
print(namArray)
handler(typeNames)
}
}
And my console logs the following:
You've got 94 species successfully
["Planta"]
["Veneno"]
I want to get ["Planta", "Veneno"] instead, but can't figure out how.
I'm building swift quiz app I want to show random questions with no repeat.
var sorular: Array = ["soru1","soru2","soru3","soru4","soru5"]
var gorulensoru = [Int]()
var sayac: Int = 0
var sorularcevaplar = ["D","Y","D","Y","D"]
var cevaplar: Array<Any> = []
var dogru: Int = 0
var yanlis: Int = 0
func chooseRandom() -> String {
if gorulensoru.count == sorular.count { return "" }
let randomItem = Int(arc4random() % UInt32(sorular.count)) //get
if (gorulensoru.contains(randomItem)) {
return chooseRandom()
}
let requiredItem = sorular[randomItem]
gorulensoru.append(randomItem)
return requiredItem
}
override func viewDidLoad() {
super.viewDidLoad()
soruText.text = chooseRandom()
}
What is the problem in my code? I'm tried insert selected random item to inside gorulensoru array but it shows again selected item
if (gorulensoru.contains(randomItem)) {
return chooseRandom()
}
This statement doesn't run.
Your code only runs once.
Also, you shouldn't include potential infinite recursive calls because it can easily get to a level where it causes a hang or crash.
Use shuffle() and then iterate over the array.
Change this and it may work:
let requiredItem = sorular[randomItem]
gorulensoru.append(requiredItem)
I am using iterators to cycle through an array of flash cards, but the iterator is going every other, for example, I tested it by entering in numbers 1-7 as new cards (in order) but when I flip through the deck it only displays 2, then 4, then 6, then back to 2. When I print out the deckIterator in the functions it gives a corresponding integer back, so for card 2 the iterator prints 2. I'm not sure If i'm using the iterator correct, could anyone point me in the right direction?
override func viewDidLoad() {
super.viewDidLoad()
fetchData()
}
func fetchData() {
deckArray.removeAll()
deckIterator = nil
do {
fetched = try context.fetch(Card.fetchRequest())
for each in fetched {
let term = each.term
let definition = each.definition
termLabel.text = each.term!
definitionLabel.text = each.definition!
let Card = card(term: term!, definition: definition!)
deckArray.append(Card)
}
} catch {
print(error)
}
deckIterator = deckArray.makeIterator()
}
#IBAction func leftSwipe(_ sender: UISwipeGestureRecognizer) {
getNextCardPlease()
self.definitionLabel.isHidden = true
alreadyFlipped = false
}
func getNextCardPlease(){
if(deckIterator?.next() == nil){
fetchData()
} else {
let next = deckIterator?.next()
termLabel.text = next?.term
definitionLabel.text = next?.definition
}
}
Every time you call next(), we iterate. So every call to getNextCardPlease iterates twice. Count them:
if(deckIterator?.next() == nil){ // 1
fetchData()
} else {
let next = deckIterator?.next() // 2
The problems was once if(deckIterator?.next() == nil) gets called, the iterator iterates. Iterators do not work like linked lists.
I am currently using 2 arrays:
let letters:[Character] =
[" ","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","!","#","#","$","%","^","&","*","(",")","1","2","3","4","5","6","7","8","9","0","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","E","S","T","U","V","W","X","Y","Z"]
let cypher:[Character] = ["o","p","q","r","a","b","c","d","e","f","g","h","i","u","v","w","x","y","z","j","k","l","m","n","s","t","$","#","#","!","&","%","^","*","("," ",")","5","7","2","9","8","0","1","3","2","4","Q","W","E","R","T","Y","U","I","O","P","A","S","D","F","G","H","J","K","L","Z","X","C","V","B","N","M"]
Both 73 characters.
I am using this line of code to encode the inserted text:
var encode:[Character:Character] = [:]
for (index, letter) in letters.enumerated() { encode[letter] = cypher[index] }
let encodeStep1 = String(insertedText.characters.map({ encode[$0] ?? $0 }))
randomNumber = Int(arc4random_uniform(9) + 1)
var encodeStep2 = cypher.rotate(shift: randomNumber)
for (index, letter) in letters.enumerated() { encode[letter] = encodeStep2[index] }
let final = String(encodeStep1.characters.map({ encode[$0] ?? $0 }))
Decode:
var decode:[Character:Character] = [:]
let step1 = cypher.rotate(shift: (randomNumber))
for (index, letter) in step1.enumerated() { decode[letter] = letters[index] }
let step1Decoded = String(insertedEncryptedText.characters.map({ decode[$0] ?? $0 }))
for (index, letter) in cypher.enumerated() { decode[letter] = letters[index] }
let step2Decoded = String(step1Decoded.characters.map({ decode[$0] ?? $0 }))
Rotate function:
extension Array {
func rotate(shift:Int) -> Array {
var array = Array()
if (self.count > 0) {
array = self
if (shift > 0) {
for i in 1...shift {
array.append(array.remove(at: 0))
}
}
else if (shift < 0) {
for i in 1...abs(shift) {
array.insert(array.remove(at: array.count-1),at:0)
}
}
}
return array
}
}
For some very odd reason, number "3" is often shown as a number "9" when decoded. From what I have seen, the problem occurs at step2Decoded. I just can not figure out what I am doing wrong. This is however a part of the code, if I need to post more I can do that.
It's because you have a typo. Your cypher array has two "2"s in it, one at cypher[39] and another 6 indices further at cypher[45]. When you're decoding in the final step you're expecting decoded["2"] to map to the value "3" in the letters array, which it does, but it's getting overwritten when it hits the "2" again setting it to the value 6 indices further in the letters array which has a value of "9".
I assume you want to change that second "2" value in the letters array to "6" instead (since I noticed there was no "6" in there). That would solve your problem.
This is the code i have made so far. I have two words, red and black. when the red button is pressed i want an if statement that tells the user if they are wrong or right. The code picks randomly either red or black but i can't seem to figure how to match the if statement with word that is randomly picked.
#IBAction func red(sender: AnyObject) {
let array = ["Red", "Black"]
let randomIndex = Int(arc4random_uniform(UInt32(array.count)))
print(array[randomIndex])
if array == Int("Red") {
colorLabel.text = "You're right"
} else {
colorLabel.text = "Wrong! It was a Black"
}
}
There's a few things wrong with your code...
You don't want to pass a string into an Int initializer, or you'll get nil:
Int("Red") // don't do this
Next, you're matching on your entire array anyway which won't work either:
if array == Int("Red") // will never == true
You want to match based on whats in your print statement:
var word = array[randomIndex] // set up a new variable
Solution
You're going to want to try something more like this:
#IBAction func red(sender: AnyObject) {
let array = ["Red", "Black"]
let randomIndex = Int(arc4random_uniform(UInt32(array.count)))
var word = array[randomIndex]
if word == "Red" {
colorLabel.text = "You're right"
} else {
colorLabel.text = "Wrong! It was a Black"
}
}