Swift Get value from Array to Plist - swift

I would like to extract a value from an array loaded from plist
var buttonPointReload = data!["\(strFromPass)"] as? Dictionary<String, String>
if var dict = buttonPointReload {
for (one, two) in dict {
println(dict) // I have [Button 1: [-200, -90]]
println(one) // I have Button 1
println(two) // I have [-200, -90]
println("\(one[0])")
}}
I save my Array in this mode
var arrPosition : [String] = []
var x: Int = ("\(line)").toInt()!
var y: Int = ("\(column)").toInt()!
arrPosition = ["\(x)"]
arrPosition.append("\(y)")
dict["Button \(index)"] = "\(arrPosition)"
data?.setValue(dict, forKey: "\(strFromPass)")
data?.writeToFile(path, atomically: true)
I am trying in this way but I get
Int doesn't have member named 'substring'
how can I get the value -200 ?

You can use CGPointFromString to convert a String
"[-200, -90]"
into a CGPoint struct.
Once you have a CGPoint you can easily access the x and y values.
You can paste this code inside your FOR loop.
let point : CGPoint = CGPointFromString(two)
println("x: \(point.x) and y: \(point.y)") // "x: -200.0 and y: -90.0"
Just note the CGPoint stores the x and y into Float(s), not Int(s).

Related

Returning Asynchronous function then assigning a value swift

I'm attempting to return the value of an array and then assign its value to a variable, however when doing so, it returns a blank array. I'm assuming this is due to my lack of knowledge on how to use async in swift so was hoping someone could show me how to do so for this segment of code:
func assignWeights(){
var weightedList = [GMUWeightedLatLng]()
getCoords { coords in
self.coords = coords
for coord in coords {
let lat = Double(coords.location.latitude)!
let long = Double(coords.location.longitude)!
let coordinates = GMUWeightedLatLng(coordinate: CLLocationCoordinate2DMake(lat,long), intensity: 2.0)
weightedList.append(coordinates)
}
print(weightedList) //Array prints contents
}
print(weightedList) //Empty array
heatmapLayer.weightedData = weightedList //Sets to empty array [] as this is ran before getCoords{
}

Extracting the real part of an UnsafeMutablePointer as a Float and storing that on an array

I have this function
func arrayForPointer<T>(_ pointer: UnsafePointer<T>, count: Int) -> [T] {
let buffer = UnsafeBufferPointer<T>(start: pointer, count: count)
return Array(buffer)
}
and this call
let arrayComplex = self.arrayForPointer(&output, count: 4)
I want to enumerate thru arrayComplex and extract the real part to a regular array, like
var arrayReal: [Float] = []
for item in arrayComplex {
let myFloat = item.realp \\ get the real part of item
arrayReal.append(myFloat)
}
line
let myFloat = item.realp \\ get the real part of item
is not correct.
item is a UnsafeMutablePointer<Float>
How do I do that, for heavens sake?
Thanks.
=======================
This is output
var A = [Float](repeating:0, count:samples/2);
var B = [Float](repeating:0, count:samples/2)
var output = DSPSplitComplex(realp: &A, imagp: &B)
Try this.
Fix your func call:
let arrayComplex = arrayForPointer(output.realp, count: 4)
And then in your loop fix this line:
let myFloat = item \\ get the real part of item

Is there a way to concatenate the name of a var in swift?

var object1 = "C_active.scn"
var object86 = "Soap.scn"
var object41 = "image.scn"
var object9 = "NaCl.scn"
Name of different .SCN files
public func addBox(sceneView: ARSCNView) {
let imagePlaneScene = SCNScene(named: "art.scnassets/" + object1)
let imagePlaneNode = imagePlaneScene?.rootNode.childNode(withName: "object1", recursively: true)
imagePlaneNode?.position = positioner
I have a code reader that gives me a number and from that Int I have to place a specific .SCN file. I don't want to add 100 if statements like I do below. Is the some way to concatenate a string with a Int and turn that into a var in swift? (The numbers after each object is the number I receive from my code reader)
if(coding == 1) {
sceneView.scene.rootNode.addChildNode(imagePlaneNode!)
} else if(coding == 2) {
sceneView.scene.rootNode.addChildNode(imagePlaneNode!)
} else {
sceneView.scene.rootNode.addChildNode(imagePlaneNode!)
}
Something like
var("object" + coding) -> coding41 (Var)
Why don't you just use a dictionary to store your file names?
var object: [Int: String] = [1: "C_active.scn", 9: "NaCl.scn" ...]
When you need a particular filename, just use the number key attached to that string.
print(object[9]) //Prints "NaCl.scn"

Swift3 loop dictionary to add value

I m new to programming I just playing around in playground, I am trying to loop in a dictionary to do some calculation and add them into new dictionary however, I can only add one dictionary value back. I am not sure why. Can anymore tell me and point out the point?
var name:String?
var popDict: [String: Array<Double>]?
var FinalDict: [String: Array<Double>]?
var mean: Double?
var elementSideArr: Array<Double>?
var nameArray = ["Olivia": [1,2,2,2,1,2,1,0.0001,0,1,2], "Amber": [52,52,65,66,57,63,62,0.0001,0,0,0]]
var doubleArr = [Double]()
for (key, value) in nameArray{
let thisValue = value
let arrayS = thisValue.prefix(7)
let slice = arrayS[0...6]
let popSideArr = Array(slice)
let average: Double = (popSideArr as NSArray).value(forKeyPath: "#avg.self") as! Double
mean = average
let thatValue = value
let arraySS = thatValue.suffix(3)
let sslice = arraySS[8...10]
elementSideArr = Array(sslice)
elementSideArr?.insert(average, at: 0)
let dict = ["\(key)": elementSideArr!]
for (key,value) in dict{
popDict = dict
}
}
print(popDict!)
["Olivia": [1.5714285714285714, 0.0, 1.0, 2.0]] // It is the only output but it should be 2 items.
Problem is in your inner for loop you are initializing whole new dictionary to popDict also you don't need for loop if you are having single key and value pair with your dictionary.
Replace line of codes:
let dict = ["\(key)": elementSideArr!]
for (key,value) in dict{
popDict = dict
}
With:
popDict["\(key)"] = elementSideArr!
Note: No need to cast swift array to NSArray to calculate average you can simply use reduce to get total and then divide the total with array count.
let array = popSideArr as? [Int] ?? []
let res = Double(array.reduce(0, +)) / Double(popSideArr.count)

How can I remove a certain CGPoint from a dictionaries

I have seen a number of posts on looping through a dictionary but they are a different and simpler than what I want to achieve here, in my opinion. I have the following arrays:
pt1.array = [0:[pt2.point],
1:[pt8.point, pt12.point, pt4.point],
2:[pt20.point, pt14.point, pt3.point],
3:[pt7.point, pt8.point, pt9.point]]
pt2.array = [0:[pt5.point],
1:[pt8.point, pt11.point, pt1.point],
2:[pt10.point, pt9.point, pt3.point],
3:[pt6.point, pt1.point, pt4.point]]
pt3.array = [0:[pt13.point],
1:[pt1.point, pt15.point, pt7.point],
2:[pt19.point, pt14.point, pt2.point],
3:[pt10.point, pt11.point, pt12.point]]
pt4.array = [0:[pt8.point],
1:[pt9.point, pt11.point, pt13.point],
2:[pt14.point, pt15.point, pt6.point],
3:[pt3.point, pt2.point, pt1.point]]
pt5.array = [0:[pt18.point],
1:[pt8.point, pt6.point, pt1.point],
2:[pt3.point, pt17.point, pt4.point],
3:[pt16.point, pt15.point, pt14.point]]
allPoints = [pt1, pt2, pt3, pt4, pt5]
How can I iterate to remove pt3.point which is a CGPoint from all the Int-[CGPoint] dictionaries in the allPoints array?
I tried the following:
for pt in allPoints {
for ptArrIndex in pt.arrays {
for (key, value) in ptArrIndex {
//remove point from dict here
}
}
}
but I got the error:
Type '(key: Int, value:[CGPoint])' (aka'(key: Int, value: Array<CGPoint>)') does not conform to protocol 'Sequence'
at the line:
for (key, value) in ptArrIndex {
EDIT
The struct that creates each of the points is below:
struct Point {
var point: CGPoint
var arrays: [Int: [CGPoint]]
}
UPDATED QUESTION
Based on Rob Napier’s suggestion I’ve updated the question:
I have a struct below:
struct Location {
var point: CGPoint
var changedLoc: [Int: [CGPoint]]
}
where point represents a CGPoint for Location and changedLoc represents all the possible groups of CGPoints Location can change to. I calculate this randomly.
I have the following Locations
var location1 = Location(point: initialBallPosition, changedLoc: [0: [CGPoint(x: 421.0, y: 43.0), CGPoint(x: 202.0, y: 69.0)], 1: [CGPoint(x: 121.0, y: 198.0)]])
var location2 = Location(point: initialBallPosition, changedLoc: [0: [CGPoint(x: 421.0, y: 43.0), CGPoint(x: 123.0, y: 254.0)], 1: [CGPoint(x: 90.0, y: 104.0)]])
var allLocations = [location1, location2]
From allLocations how can I remove the point CGPoint(x: 421.0, y: 43.0) which is in both location1 and location2 changedLoc?
func locationsRemoving(changedLoc removePoint: CGPoint, from locations: [Location]) -> [Location] {
return locations.map { location in
var changedLoc: [Int: [CGPoint]] = [:]
for (key, values) in location.changedLoc {
changedLoc[key] = values.filter{ $0 != removePoint }
}
return Location(point: location.point, changedLoc: changedLoc)
}
}
let removePoint = CGPoint(x: 421.0, y: 43.0)
print(allLocations)
print(locationsRemoving(changedLoc: removePoint, from: allLocations))
The confusing thing you have is that the property named array in the ptN instances is actually a Dictionary<Int, [CGPoint]>
So, for the structure you currently have, you'll need to amend your code to match:
for pt in allPoints {
for (key, ptArray) in pt.array {
for elem in ptArray {
//remove point from dict here
}
}
}