Indexed array not printing elements in array - arrays

My code below is trying to index every new entry to the array when the button is pressed. So automatically sort the element when the button is pressed.
var arrayOfInt = [Int]()
#IBAction func submitText(_ sender: Any) {
if let text = enterText.text {
if let number = Int(text) {
var index = 0
for num in arrayOfInt {
if num > number {
arrayOfInt.insert(number, at: index)
break
}
index += 1
}
print(arrayOfInt)
} else {
print("Please enter number")
}
}}
When printed this is what is coming out []. None of the numbers are printed.

Initially arrayOfInt is empty array. So it will never go inside this as the array is empty
for num in arrayOfInt {
//Whatever is here
}
Your logic is also wrong for whatever you are trying to achieve.
Array has already sort(by:(Element, Element) -> Bool) method
You better write the code as follows:-
var arrayOfInt = [Int]()
#IBAction func submitText(_ sender: Any) {
if let text = enterText.text , let number = Int(text) {
arrayOfInt.append(number)
arrayOfInt.sort { return $0 > $1 } //Modify accordingly the order you want
print(arrayOfInt)
} else {
print("Please enter number")
}
}

Your arrayOfInt variable has no elements, it's empty... so the for loop won't iterate over a zero index array, it would have no sense... that's why the code inside the curly brackets is never executed.
If you would have debugged your code with either a breakpoint or using a print statement this issue would have been shown by itself.
I would avoid using if let every time the guard statement could solve the same. Basically because it looks more readable and it's kind of the Swift approach... at the same time you are avoiding the pyramid of doom.
My suggestion would be:
var arrayOfInt = [Int]()
#IBAction func submitText(_ sender: Any) {
guard let text = enterText.text else {
print("Please enter a number")
return
} // guard
guard let number = Int(text) else {
print("Can't creates an integer value from the given string.")
return
} // guard
arrayOfInt.append(number)
arrayOfInt.sort() // From lowest to highest by default.
//arrayOfInt.sort { $0 < $1 } // From lowest to highest using a higher order function.
//arrayOfInt.sort { $0 > $1 } // From highest to lowest using a higher order function.
} // submitText

Related

Swift I can't append two different strings on the same array

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.

How to select items from array no repeat

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)

Iterator in swift is skipping elements?

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.

Replacing text won't go correctly with encoding and decoding

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.

if Statements calling on random array

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"
}
}

Resources