How do I assign a variable to refer to an array? - arrays

Disclaimer: I am pretty much a novice to Swift so prepare to cringe.
I have a series of arrays set out, when a user taps a button I would like one of these arrays to be called so I can use it in a function. They are named with thisArray then a number, i.e: thisArray1, thisArray2, etc.
I cannot find a way to make this work, the closest I have come to what I want is shown below but as you can all tell this definitely does not work.
var currentArray = "thisArray" + selectedArrayNumber
The outcome of this is to use the variable like below:
button1.setTitle(currentArray[1], for .normal)
If any of you can shed some light on this situation and tell me how badly I have gone wrong that would be much appreciated.

Create an array of your arrays, and then retrieve it using the selectedArrayNumber.
let arrays = [thisArray1, thisArray2, etc]
let currentArray = arrays[selectedArrayNumber]

Related

Declare array of UIButtons

I want my swift code to create buttons using colors. I know I want to declare array but some of the things I have tried are not working. What I tried below is not working. I have tried to do various forms of wrapping but it did not work. The goal of this code is to not use any storyboards and do everything by code.
var red,blue = UIButton()
One compact way to declare two variables in one line is to use tuple notation:
let (red,blue) = (UIButton(), UIButton())
Perhaps that's what you're asking for. But there is no array in the story; it's hard to see why you mention arrays in the first place.
On the other hand, if you really do want an array as you claim, then it's hard to see what the names red and blue are for, since the elements of an array do not have names (with regard to the array). You could make an array of two new buttons by saying:
let arrayOfTwoButtons = (0..<2).map {_ in UIButton()}

shuffling multiple choice array in Swift 4

could someone explain me how to shuffle an array which contains several items, like this:
var answers = [["A","B","C"], ["D","E","F"], ["G","H","I"], ["J","K","L"]]
I know to shuffle a simple array, but this one is more complex and I tried many way, nothing works.
Thanks in advance.
There are plenty of questions on SO about shuffling array. The solution I personally use is a function provided by GameplayKit. You don't need to write a game to utilize it:
import GameplayKit
var answers = [["A","B","C"], ["D","E","F"], ["G","H","I"], ["J","K","L"]]
answers = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: answers) as! [[String]]

In Swift, What is the difference between var myArray: [myClass] and var myArray = [Array]() [duplicate]

Is there any difference between the following?
var array1_OfStrings = [String]()
var array2_OfStrings: [String] = []
var array3_OfStrings: [String]
Testing in Playground shows that 1 and 2 are the same but 3 behaves differently.
Can someone explain me the difference please? And also what will be the preferred way to declare an empty array of String?
First two have the same effect.
declare a variable array1_OfStrings, let it choose the type itself. When it sees [String](), it smartly knows that's type array of string.
You set the variable array2_OfStrings as type array of string, then you say it's empty by []
This is different because you just tell you want array3_OfStrings to be type array of string, but not given it an initial value.
I think the first one is recommended as The Swift Programming Language uses it more often.
While I might be late to the party, there is one thing that needs to be said.
First option set array1_OfStrings to array of Strings
The other option tells that array1_OfStrings is array of Strings and then set it empty.
While this might be a really small difference, you will notice it while compiling. For the first option compiler will automatically try to find out what is the type of array1_OfStrings. Second option won't do that, you will let compiler know that this actually is array of Strings and done deal.
Why is this important? Take a look at the following link:
https://thatthinginswift.com/debug-long-compile-times-swift/
As you can see, if you don't declare type of your variable that might impact build performance A LOT.

How do I iterate through one array and move every other element to two new arrays in Swift?

I do realize similar questions have been asked before, I looked at them before seeking help. But they were either not in Swift or too complex for me to decipher. My question is different from How do I shuffle an array in Swift? in that I have already done some of the work, like shuffling. The title was actually different from the question asked, which was "How do I randomize or shuffle the elements within an array in Swift?" I am only interested in iterating the resulting array and I couldn't separate that part from the rest of the code in the answers given for a question that encompassed so much more. That said, there are some great suggestions on that page so I think people like me will benefit from having both pages available. Maybe someone can set up a reciprocal link on that page as I have done here.
Admittedly, I am new to Swift and not a seasoned programmer in any language, but please don't assume I am coming here seeking help without trying to figure it out on my own. I am spending many hours learning the fundamentals of all C based languages and reading the Swift literature at developer.apple.com.
So the question will be more obvious, I and attempting to build the card game War. Thus far I have accomplished constructing the (an array) deck of cards and randomized it (shuffled). I am stuck at looping through the resulting array of 52 objects and assigning (moving) them to the two players hands (two new arrays). I'm not sure how much of my code I should display in order to help me but if you need more, I'll gladly provide it. Please note that this is only an exercise, practice for me to learn how to write complex programs, and some code, like the function to randomize, is not mine, I found it right here at stackoverflow. I'd almost prefer if you didn't just hand me the code that will work, I'm not likely going to learn as much that way, but if providing steps in plain English so I can figure out the syntax is too much trouble, so be it, provide an example, I'm sure I'll get plenty of chances to write/use the syntax later.
One more note, I'm only working in a playground at the moment, when and if I can get all the code working, I'll move to the UI stuff.
Thanks in advance, Rick
/* Skipping past everything I did to get here,
the array (shuffledDeck) has 52 shuffled cards (elements) in it.
The array is NSMutableArray and contains strings like
2Hearts, 5Spades, 14Clubs, etc. Each suit has 14 cards.*/
shuffledDeck
// create vars to hold shuffled hands
var playerOneHand = []
var playerTwoHand = []
/* Started a for loop to assign cards to each hand
but don't know which method(s) is/are best to use
to remove the first or last card and alternately
append (move) it to the (hopefully) initialized
variables playerOneHand and PlayerTwoHand.
Optionally, since the cards are already shuffled,
I could just split the deck using the range method,
whichever is easier. I tried and failed at both ways.*/
var i = 0
for dealtCard in shuffledDeck {
}
var shuffledDeck:[String] = ["2Hearts", "5Spades", "14Clubs", "etc"]
//shuffledDeck will of course be your shuffled deck
var playerOneHand:[String] = []
var playerTwoHand:[String] = []
for (index, cardString) in enumerate(shuffledDeck) {
if index % 2 == 0 {
playerOneHand.append(cardString)
}else{
playerTwoHand.append(cardString)
}
}
I’m looping through every item in the shuffledDeck, but with that I use the index of the array to get a number. I use this number to see if that number devided by 2 is equal to 0 (the number is even) or not (uneven) if a number is even, I get the item that is in the array at the given index and add that item to the hand of player one. If the index is uneven I add the item to the second player’s hand. This means the first item goed to player one’s hand, the second item goes to the hand of the second player. the third Item goes back to the first player and so on.
As mentioned by Martin R you can use the range method to assign the first half of the deck to the first player and the second to the second player as follow:
let cards:[String] = ["2♦️","3♦️","4♦️","5♦️","6♦️","7♦️","8♦️","9♦️","T♦️","J♦️","Q♦️","K♦️","A♦️","2♠️","3♠️","4♠️","5♠️","6♠️","7♠️","8♠️","9♠️","T♠️","J♠️","Q♠️","K♠️","A♠️","2♥️","3♥️","4♥️","5♥️","6♥️","7♥️","8♥️","9♥️","T♥️","J♥️","Q♥️","K♥️","A♥️","2♣️","3♣️","4♣️","5♣️","6♣️","7♣️","8♣️","9♣️","T♣️","J♣️","Q♣️","K♣️","A♣️"]
extension Array {
var shuffled:[T] {
var elements = self
for index in 0..<elements.count - 1 {
swap(&elements[index], &elements[Int(arc4random_uniform(UInt32(elements.count - 1 - index))) + index])
}
return elements
}
}
let cardsShuffled = cards.shuffled
let playerOneHand = cardsShuffled[0...25]
let playerTwoHand = cardsShuffled[26...51]
Note: The shuffle extension was created using this answer as reference

How to pass the objects of myArray?

I'm a newbie, I have gone through basics but couldn't figure this one out. I've googled so much but finally I land here.
fontFamily = [[UIFont alloc]init];
fontSize = [[NSMutableArray alloc]initWithObjects:#"10",#"15",#"20",#"25",#"30", nil ];
[text setFont: [[UIFont familyNames] size:<-----
And now, how can I pass the objects to size?
I truly don't know what your looking for. But if you are looking to access the strings you put in the array, you can do so like this:
[fontSize objectAtIndex:2]
You can put that any place you would want to put #"20" since that is what is at index 2.
You should note that you are putting string values in the array not number values.
Edit in response to comment.
You don't really want to just pass the array anywhere what you want to do is something like:
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
// if calling for size component
return fontSize.count;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
// if calling for size component
return [fontSize objectAtIndex:row];
}
If I'm off a little I apologize, I don't use pickerViews much.

Resources