Storing var in array - arrays

Do I have to set the array to a specific type so that it will store the images or is it something else. The images are stored in the Images.xcassets
class GameScene: SKScene {
var blueTexture = SKTexture(imageNamed: "BlueBall.png")
var greenTexture = SKTexture(imageNamed: "GreenBall.png")
var redTexture = SKTexture(imageNamed: "redTexture.png")
var array = [blueTexture, greenTexture, redTexture]
//error: GameScene does not have a member called blueTexture
//this goes for the other textures as well

This is because you can't access other properties during initialization, so you could replace you current code with this:
var blueTexture = SKTexture(imageNamed: "BlueBall.png")
var greenTexture = SKTexture(imageNamed: "GreenBall.png")
var blueTexture = SKTexture(imageNamed: "BlueBall.png")
var array:[SKTexture]!
override func didMoveToView(view: SKView)
{
array = [blueTexture,greenTexture,blueTexture]
}
Also, you made two blueTextures.

Related

how to merge two arrays into a struct

What I want my swift code to do is take the two arrays initilized in view controller and then move them into the struct added. I want to do the transfer in view did load. I dont know what I am doing so I put some code that I thought might be helpful but right now my code is not compiling in view did load.
import UIKit
class ViewController: UIViewController {
var emptyA = [Int]()
var emptyb = [UIImage]()
override func viewDidLoad() {
super.viewDidLoad()
added.init(emptyA, emptyb)
}
}
struct added {
var arrayOne = //emptyA
var arrayTwo = //emptyb
}
You need to declare your struct like this:
struct Added {
var arrayOne: [Int]
var arrayTwo: [UIImage]
}
Then to declare an instance you would do this:
let a = Added(arrayOne: emptyA, arrayTwo: emptyb)
Also, it's typically good form to start the name of your structs with a capital letter.

make an array from custom object properties

I have a custom class like:
class Tender: NSObject {
public var code = ""
public var name = ""
}
A method returns an array of Tender type. From this array, I want to prepare an array that contains only name.
Example,
public func fetchTenderArray() -> [Tender] {
var tenderArray = [Tender]()
let tender1 = Tender()
tender1.code = "t1"
tender1.name = "tenderName1"
let tender2 = Tender()
tender2.code = "t2"
tender2.name = "tenderName2"
tenderArray.append(tender1)
tenderArray.append(tender2)
return tenderArray
}
Now, I have a method that uses this tenderArray. I need to form an array with the names of [Tender].
public func formTenderNamesArray() -> [String] {
let tenderArray = fetchTenderArray()
var tenderNames = [String]()
for tender in tenderArray {
tenderNames.append(tender.name)
}
return tenderNames // returns ["tenderName1","tenderName2"]
}
Is there a short and a best way to prepare that array of strings using swift3?
Try using map functionality,
it should be something like this.
let tenderArray = fetchTenderArray()
let tenderNames = tenderArray.map {$0.name}
For more information please see this link.
https://useyourloaf.com/blog/swift-guide-to-map-filter-reduce/
//Try this
public func formTenderNamesArray() -> [String] {
let tenderArray = fetchTenderArray()
var tenderNames = (tenderArray as! NSArray).value(forKey: "name") as! [String]
return tenderNames
}

Swift: How to define a fixed array of flexible String array

I already have several arrays for strings. I want to add them to a list of arrays, so I can use a predefined (enum) index. The individual arrays are already in place, I only need to access them via index (fixed with enum or within a loop with index from enum type). So there should be no copy of the strings within the array, only a reference to the array itself.
I already have this in mind:
enum TypeOfArray: Int {
case Src = 0, Dest, SrcCache, DstCache, N
}
var srcFolders : [String] = []
var dstFolders : [String] = []
var srcFoldersCache : [String] = []
var dstFoldersCache : [String] = []
var allFolders: [[String]] = []
Then I want to initilaze the main array by assigning each of the individual arrays. But this is rejected by the compiler: ("Cannot subscript a value of type '[[String]]' with an index of type 'TypeArray'")
allFolders[TypeOfArray.Src] = srcFolders
I don't know if this "typesave" index is even possible.
Can I use a fixed index range 0..N when defining for optimizing memory or speed?
Any ideas?
A dictionary would be a good solution for this:
var dict = [TypeOfArray:[String]]()
dict[TypeOfArray.Src] = srcFolders
Singleton
If you want to share the content of your arrays, an you want the updates to be reflected in your code, you can use a Singleton
final class ImageNameManager {
static let sharedInstance = ImageNameManager()
var srcFolders: [String]
var dstFolders: [String]
var srcFoldersCache: [String]
var dstFoldersCache: [String]
private init() {
// populate: srcFolders, dstFolders, srcFoldersCache, dstFoldersCache
srcFolders = []
dstFolders = []
srcFoldersCache = []
dstFoldersCache = []
}
enum ImageType: Int {
case Src = 0, Dest, SrcCache, DstCache
}
func imageNames(imageType: ImageType) -> [String] {
switch imageType {
case .Src: return srcFolders
case .Dest: return dstFolders
case .SrcCache: return srcFoldersCache
case .DstCache: return dstFoldersCache
}
}
}
Usage
Now you can populate one of your array
ImageNameManager.sharedInstance.dstFolders.append("Hello")
and receives the new data in another section of your code
let dstFolders = ImageNameManager.sharedInstance.imageNames(.Dest)
// ["Hello"]
Update
In order to share the same array across your app you cal also use this code
final class ImageNameManager {
static let sharedInstance = ImageNameManager()
var srcFolders: [String] = []
var dstFolders: [String] = []
var srcFoldersCache: [String] = []
var dstFoldersCache: [String] = []
}
Now alway reference it the array with this code ImageNameManager.sharedInstance.dstFolders, look
ImageNameManager.sharedInstance.dstFolders.append("Hello")
ImageNameManager.sharedInstance.dstFolders.append("World")
ImageNameManager.sharedInstance.dstFolders // ["Hello", "World"]

Swift: Get multiple array values like "x"

For example, I have an array like var myArray = ['player_static.png', 'player_run0.png', 'player_run1.png', 'player_run2.png', 'player_jump0.png', 'player_jump1.png']
Is there any simple way to get only the "player_runX.png" images?
You can use filter to get all elements that hasPrefix("player_run"):
let myArray = ["player_static.png", "player_run0.png", "player_run1.png", "player_run2.png", "player_jump0.png", "player_jump1.png"]
let playerRuns = myArray.filter{$0.hasPrefix("player_run")}
print(playerRuns) //["player_run0.png", "player_run1.png", "player_run2.png"]
One way to do this would be to iterate over the array and retrieve the elements that match the pattern. A very quick sample would be something like this:
var myArray = ["player_static.png", "player_run0.png", "player_run1.png", "player_run2.png", "player_jump0.png", "player_jump1.png"]
func getSubArray(array:[String],prefix:String) -> [String]
{
var newArray = [String]()
for img in array
{
if img.substringToIndex(img.startIndex.advancedBy(prefix.characters.count)) == prefix
{
newArray.append(img)
}
}
return newArray
}
var test = getSubArray(myArray, prefix: "player_run")

How to Create 2D array in Swift?

Hi there I am new to Swift, I am trying to save Longitude and Latitude and place name from map's coordinate object to an Multidimensional array i.e:
Can anyone please help me how do i create these dynamically?
var pinArray[0][Lat] = 51.130231
var pinArray[0][Lon] = -0.189201
var pinArray[0][Place] = "Home"
var pinArray[1][Lat] = 52.130231
var pinArray[1][Lon] = -1.189201
var pinArray[1][Place] = "Office"
var pinArray[2][Lat] = 42.131331
var pinArray[2][Lon] = -1.119201
var pinArray[2][Place] = "Dinner"
You can make an array of dictionaries, but I suggest using structs instead.
Array of dictionaries
Create an empty array of dictionaries:
var pinArray = [[String:AnyObject]]()
Append dictionaries to the array:
pinArray.append(["lat":51.130231, "lon":-0.189201, "place":"home"])
pinArray.append(["lat":52.130231, "lon":-1.189201, "place":"office"])
But since your dictionaries hold two types of value (Double and String) it will be cumbersome to get the data back:
for pin in pinArray {
if let place = pin["place"] as? String {
print(place)
}
if let lat = pin["lat"] as? Double {
print(lat)
}
}
So, better use structs instead:
Array of structs
Create a struct that will hold our values:
struct Coordinates {
var lat:Double
var lon:Double
var place:String
}
Create an empty array of these objects:
var placesArray = [Coordinates]()
Append instances of the struct to the array:
placesArray.append(Coordinates(lat: 51.130231, lon: -0.189201, place: "home"))
placesArray.append(Coordinates(lat: 52.130231, lon: -1.189201, place: "office"))
It's then easy to get the values:
for pin in placesArray {
print(pin.place)
print(pin.lat)
}
Without more information, this is what I can offer.
var pinArray = [[AnyObject]]()
for location in mapLocations {
var innerArray = [location["latitude"], location["longitude"], location["place"]]
pinArray.append(innerArray)
}
Solution using an enum for Lat/Lon/Place (as you don't show us what these are):
enum Pos {
case Lat
case Lon
case Place
static let allPositions = [Lat, Lon, Place]
}
var myMatrix = [[Pos:Any]]()
myMatrix.append([.Lat: 51.130231, .Lon: -0.189201, .Place: "Home"])
myMatrix.append([.Lat: 52.130231, .Lon: -1.189201, .Place: "Office"])
myMatrix.append([.Lat: 42.131331, .Lon: -1.119201, .Place: "Dinner"])
/* check */
for (i,vector) in myMatrix.enumerate() {
for pos in Pos.allPositions {
print("myMatrix[\(i)][\(pos)] = \(vector[pos] ?? "")")
}
}
/*
myMatrix[0][Lat] = 51.130231
myMatrix[0][Lon] = -0.189201
myMatrix[0][Place] = Home
myMatrix[1][Lat] = 52.130231
myMatrix[1][Lon] = -1.189201
myMatrix[1][Place] = Office
myMatrix[2][Lat] = 42.131331
myMatrix[2][Lon] = -1.119201
myMatrix[2][Place] = Dinner */

Resources