let me start with the code:
var lat1:CLLocationDegrees = 50.102760
var lat2:CLLocationDegrees = -26.135170
.
.
.
var lat191:CLLocationDegrees = 60.289139
var LocCount = 191
for var iLat = 3; iLat == LocCount; ++iLat{
AirportLat.append("lat" + iLat)
}
What i try is go to count up the name of the var that should be appended to my array is there a way to do this?
Well, that's a difficult way to do it.
How about:
var latArray = <CLLocationDegrees>()
latArray += [50.102760]
latArray += [-26.135170]
.
.
.
latArray += [60.289139]
println("LocCount check = \(latArray.count)")
A better still way to do it would be to put the latitudes into a file (so you can change them, add to them, etc. without recompiling your code) and read them in, but I'll leave that as an exercise...
...and if you want to use the other answer's dictionary idea, you can add
for i in 0 ..< latArray.count {
dict["lat\(i+1)"] = latArray[i]
}
First off its not good practice to define 191 variables. Use Dictionary instead where keys are: lat1, lat2 .... lat191.
After that you can loop over Dictionary values and manipulate with them.
But if you still want to aggregate all variables to Array you can use class_copyIvarList to fetch all variables start with lat and write as:
class Myclass : NSObject{
var lat1:CLLocationDegrees = 50.102760
var lat2:CLLocationDegrees = -26.135170
var lat3:CLLocationDegrees = 60.289139
var AirportLat:Array<CLLocationDegrees> = []
func fetchValues() -> Array<CLLocationDegrees>{
var aClass : AnyClass? = self.dynamicType
var propertiesCount : CUnsignedInt = 0
let propertiesInAClass : UnsafeMutablePointer<Ivar> = class_copyIvarList(aClass, &propertiesCount)
for var i = 0; i < Int(propertiesCount); i++ {
var propName:String = NSString(CString: ivar_getName(propertiesInAClass[Int(i)]), encoding: NSUTF8StringEncoding)
var propValue : AnyObject! = self.valueForKey(propName)
if propName.hasPrefix("lat") {
AirportLat.append(propValue as CLLocationDegrees)
}
}//for
return AirportLat
}
}
var cc = Myclass()
cc.fetchValues()
Output:
[50.10276, -26.13517, 60.289139]
Comment: the class must inherit NSObject
Related
So, this is my code. I want it to take the answer for each item in the array and load it into a new array once the answer is found. However, it is only solving the question for the first number in the array and then adding that answer to the array multiple times. I hope that makes sense.
var crosswindarray = [] as! [String]
func crossWindCalculation() {
var runwayNames = ["28", "36"]
for runwayNumbers in runwayNames {
var windSpeedInt = 20
var runwayHeadingString = runwayNumbers
runwayHeadingString.removeLast()
runwayHeadingString.append("0")
let crossWindSin: Float = Float(sin(50 * Double.pi / 180))
let crossWindAnswer: Float = crossWindSin * Float(windSpeedInt)
crosswindarray.append(String(format: "XW: %.f", crossWindAnswer))
}
}
Because you're making a new array each iteration of the loop - make an array scoped to the whole function:
func crossWindCalculation() {
var crosswindarray = [] as! [String]
for runwayNumbers in runwayNames {
// ...
let crossWindAnswer: Float = crossWindSin * Float(windSpeedInt)
crosswindarray.append(String(format: "XW: 5.f", crossWindAnswer))
}
// Do something with crosswindarray
}
I have an array of type "drugList", and they are derived from a struct "DrugsLibrary":
struct DrugsLibrary {
var drugName = ""
var drugCategory = ""
var drugSubCategory = ""
}
var drugList = [DrugsLibrary]()
//This is the dictionary i'm trying to build:
var dictionary = ["": [""," "]]
My data model is initialized using this function:
func createDrugsList() {
var drug1 = DrugsLibrary()
drug1.drugName = "drug1"
drug1.drugCategory = "Antibiotics"
drug1.drugSubCategory = "Penicillins"
self.drugList.append(drug1)
var drug2 = DrugsLibrary()
drug2.drugName = "drug2"
drug2.drugCategory = "Antibiotics"
drug2.drugSubCategory = "Penicillins"
self.drugList.append(drug2)
var drug3 = DrugsLibrary()
drug3.drugName = "drug2"
drug3.drugCategory = "Antibiotics"
drug3.drugSubCategory = "Macrolides"
self.drugList.append(drug3)
}
my problem is that i'm trying to create a dictionary from the drugList where the key is the drugSubCategory and the value is the drug name. The value should be an array if there are several drugs in this subcategory
for example, the dictionary should look something like this for this example:
dictionary = [
"Penicillins": ["drug1","drug2"]
"Macrolides": ["drug3"]
]
I tried this method:
for item in drugList {
dictionary["\(item.drugSubCategory)"] = ["\(item.drugName)"]
}
this gave a dictionary like this, and it couldn't append drug2 to "Penicllins":
dictionary = [
"Penicillins": ["drug1"]
"Macrolides": ["drug3"]
]
So I tried to append the items into the dictionary using this method but it didn't append anything because there were no common items with the key "" in the data model:
for item in drugList {
names1[item1.drugSubCategory]?.append(item1.drugName)
}
Anyone knows a way to append drug2 to the dictionary?
I would appreciate any help or suggestion in this matter.
You need to create a new array containing the contents of the previous array plus the new item or a new array plus the new item, and assign this to your dictionary:
for item in drugList {
dictionary[item.drugSubCategory] = dictionary[item.drugSubCategory] ?? [] + [item.drugName]
}
You can use .map and .filter and Set to your advantage here. First you want an array of dictionary keys, but no duplicates (so use a set)
let categories = Set(drugList.map{$0.drugSubCategory})
Then you want to iterate over the unique categories and find every drug in that category and extract its name:
for category in categories {
let filteredByCategory = drugList.filter {$0.drugSubCategory == category}
let extractDrugNames = filteredByCategory.map{$0.drugName}
dictionary[category] = extractDrugNames
}
Removing the for loop, if more Swifty-ness is desired, is left as an exercise to the reader ;).
I have two unrelated observations:
1) Not sure if you meant it as an example or not, but you've initialized dictionary with empty strings. You'll have to remove those in the future unless you want an empty strings entry. You're better off initializing an empty dictionary with the correct types:
var dictionary = [String:[String]]()
2) You don't need to use self. to access an instance variable. Your code is simple enough that it's very obvious what the scope of dictionary is (see this great writeup on self from a Programmers's stack exchange post.
Copy this in your Playground, might help you understand the Dictionaries better:
import UIKit
var str = "Hello, playground"
struct DrugsLibrary {
var drugName = ""
var drugCategory = ""
var drugSubCategory = ""
}
var drugList = [DrugsLibrary]()
//This is the dictionary i'm trying to build:
var dictionary = ["":""]
func createDrugsList() {
var drug1 = DrugsLibrary()
drug1.drugName = "drug1"
drug1.drugCategory = "Antibiotics"
drug1.drugSubCategory = "Penicillins"
drugList.append(drug1)
var drug2 = DrugsLibrary()
drug2.drugName = "drug2"
drug2.drugCategory = "Antibiotics"
drug2.drugSubCategory = "Penicillins"
drugList.append(drug2)
var drug3 = DrugsLibrary()
drug3.drugName = "drug2"
drug3.drugCategory = "Antibiotics"
drug3.drugSubCategory = "Macrolides"
drugList.append(drug3)
}
createDrugsList()
print(drugList)
func addItemsToDict() {
for i in drugList {
dictionary["item \(i.drugSubCategory)"] = "\(i.drugName)"
}
}
addItemsToDict()
print(dictionary)
So, i have a file data.swift with some informations
class Data {
var agen = [… ]
var tours = [… ]
var marseille = [… ]
……
}
In another viewcontroller, i m trying to get back a value from above with this.
I can get back a particular value with with command with success :
let entry = data.agen[indexPath.row]
It’s working but I would like set a variable in this command, I put this
var passedValue:String!
// passedValue coming from a segue from a previous VC
// passedValue could be "agen", "tours",”marseille” ...
let entry = data.passedValue[indexPath.row]
But it's not working message error told me "data doesn't have a member named "passedValue"
How could i set properly the variable ?
what about a slightly different syntax
class Data {
var agen = ["A","B","C"]
var tours = ["D","E"]
var marseille = ["F","G","H"]
subscript(index: String) -> [String]! {
switch index {
case "agen" : return agen
case "tours" : return tours
case "marseille" : return marseille
default: return []
}
}
}
let key = "agen"
let data = Data()
print(data[key][1])
(maybe make a bit more error prof)
Other solution is to create classes/structs for 'agen','tours', etc.
And set it in the Data object
class Data {
var agen = [Agen(title), Agen(title2)]
var tours = [Tour(title), Tour(title2)]
…… }
Because, probably you want to show some info about the object in tableView later, so you could go like this:
title.text = tour.title
subtitle.text = tour.placeName
imageView.image = tour.photos[1]
Can I add dictionary arrays (is this the correct term for a dictionary key holding multiple values?) to an array?
var dictionary = [String: [String]]()
var array = [String]()
var data1:String = "55a"
var data2:String = "95a"
var data3:String = "66"
var data4:String = "25"
var data5:String = "88b"
var data6:String = "#"
dictionary["3"] = [data1, data2, data3, data4, data5, data6]
var data7:String = "#"
var data8:String = "#"
var data9:String = "#"
var data10:String = "#"
var data11:String = "#"
var data12:String = "#"
dictionary["2"] = [data7, data8, data9, data10, data11, data12]
var data13:String = "100"
var data14:String = "101"
var data15:String = "102"
var data16:String = "103"
var data17:String = "104"
var data18:String = "105"
dictionary["1"] = [data13, data14, data15, data16, data17, data18]
I tried this:
array.extend([dictionary["1"], dictionary["2"], dictionary["3"]])
but there was an error "Cannot invoke 'extend' with an argument list of type '([[(String)?])"..
How do I add dictionary["1"], ["2"] & ["3"] accordingly into the array?
Your array type declaration is not correct. Please try below one
var array: [[String:[String]] = []
In case you are not interested in the order you might try:
array.extend(flatMap(dictionary.values, {$0}))
If order is important you might build your optionalArrays first:
let optionalArrays = [dictionary["1"], dictionary["2"], dictionary["3"]]
array.extend(flatMap(optionalArrays, {$0 ?? []}))
i.e. your dictionary returns an optional array, this causes the error you reported.
Hope this helps
If you wanted an array of arrays of Strings, you need to change your array's type to be [[String]], as the other answers said.
But, when getting values out of your dictionary, you shouldn't force unwrap! It may work for this example, but in the future you'll likely get into trouble with:
'fatal error: unexpectedly found nil while unwrapping an Optional
value'
You should check to see if a value exists in the dictionary for that key, using optional binding for example:
if let value = dictionary["1"] {
array.append(value)
}
// ...
Or, you could get all the values from your dictionary into an array like so:
let array = Array(dictionary.values)
If you actually did want an array of Strings, you could use flatMap:
let array = flatMap(dictionary.values) { $0 }
Your array variable must be an Array of Array with String elements.
Also don't forget to unwrap the values of the dictionaries by adding !.
Try this:
var dictionary = [String: [String]]()
var array = [[String]]()
var data1:String = "55a"
var data2:String = "95a"
var data3:String = "66"
var data4:String = "25"
var data5:String = "88b"
var data6:String = "#"
dictionary["3"] = [data1, data2, data3, data4, data5, data6]
var data7:String = "#"
var data8:String = "#"
var data9:String = "#"
var data10:String = "#"
var data11:String = "#"
var data12:String = "#"
dictionary["2"] = [data7, data8, data9, data10, data11, data12]
var data13:String = "100"
var data14:String = "101"
var data15:String = "102"
var data16:String = "103"
var data17:String = "104"
var data18:String = "105"
dictionary["1"] = [data13, data14, data15, data16, data17, data18]
array.extend([dictionary["1"]!, dictionary["2"]!, dictionary["3"]!])
Dictionary values are returned as optionals (thus indicating if a value exists for a key) so use the '!' to unwrap the values of each dictionary array (i.e. [dictionary["1"]!)
And as suggested in other answers change your array type as it currently defined as arrays of string rather then an array of dictionaries.
So i am trying to make a word jumlbe sort of program but i am running into some difficulties with the function for shuffelling the words
So i tried:
function klikk(evt){
var i:int = 0;
var ordet:String = inntastetOrd;
var lengde:int = ordet.length;
var tall:int = 0;
var karakter:String;
for(i=0;i<ordet.length; i++)
{
tall = Math.random() *ordet.length;
karakter = ordet[tall];
ordet[i] = ordet[tall];
ordet[tall] = karakter;
}
But i am getting: "Error #1069: Property "some value" not found on String and there is no default value."
Thanks for help!
If you want to chose a letter in a String, you need to transform this String into Array with the split method.
For example:
var letters:String = "word";
trace(letters[2]); // Error #1069
var a:Array = letters.split(""); // w,o,r,d
trace(a[2]); // r