Swift, use string name to reference a variable - string

Plan to use a string value to for referencing which variable I want to update. Combining string from a few different user selected sources. To many possibilities to use if/case statements. Thanks in advance
var d1000: Int = 0
// ...
var d1289: Int = 0
// ...
var d1999: Int = 0
var deviceIDtype: Character = "d" // button press assigns some value, d used for example
var deviceIDsection: String = "12" // button press assigns some value, 12 used for example
var deviceID: String = "89" // button press assigns some value, 89 used for example
var ref:String = ""
func devName(dIDt:Character, dIDs: String, dID: String) -> String {
var combine: String = String(dIDt) + (dIDs) + (dID)
return (combine)
}
ref = devName(deviceIDtype, dIDs: deviceIDsection, dID: deviceID) // ref equals d1289 in this example
// d1289 = 1234 // trying to set this using the ref variable value, failed attempts below
/(ref) = 1234 // set d1289 variable to equal "1234"
"/(ref)" = 1234 // set d1289 variable to equal "1234"
get(ref) = 1234 // set d1289 variable to equal "1234"
get.ref = 1234 // set d1289 variable to equal "1234"

It is possible!!!
let index = 1000
if let d1000 = self.value(forKey: "d\(index)") as? Int {
// enjoy
}

How about using a dictionary, [String : Int]?
This will allow you to achieve what you want - storing values for different keys.
For example, instead of using
var d1000 = 0
var d1289 = 0
var d1999 = 0
You could use
var dictionary: [String : Int] = [
"d1000" : 0,
"d1289" : 0,
"d1999" : 0
]
To store a value in the dictionary, just use
dictionary[key] = value
//for example, setting "d1289" to 1234
dictionary["d1289"] = 1234
and to get the value from the dictionary, use
let value = dictionary[key]
//for example, getting the value of "d1289"
let value = dictionary["d1289"]
So, you could use something like this
//initialize your dictionary
var myDictionary: [String : Int] = [:]
//your key initialization data
var deviceIDtype: Character = "d"
var deviceIDsection: String = "12"
var deviceID: String = "89"
var ref: String = ""
//your code
func devName(/*...*/){/*...*/}
ref = devName(/*...*/)
//set the key ref (fetched from devName) to 1234
myDictionary[ref] = 1234
Just as a side note, you could really clean some of your code
func devName(type: Character, section: String, id: String) -> String{
return String(type) + section + id
}
//...
let key = devName(deviceIDtype, section: deviceIDsection, id: deviceID)
let value = 1234
myDictionary[key] = value

Related

how separate string into key/value pair in dart?

how can a string be separated into key/value pair in dart? The string is separated by a "=". And how can the pair value be extracted?
main(){
var stringTobeSeparated = ['ab = cd','ef = gh','ld = kg'];
Map<String ,dynamic> map = {};
for (String s in stringTobeSeparated) {
var keyValue = s.split("=");
//failed to add to a map , to many positiona arguments error
map.addAll(keyValue[0],keyValue[1]);
}
}
The split() function gives you a List of Strings, so you just need to check if the length of this List is equal to 2 and then you can add those values in a Map like this:
Map<String, String> map = {};
for (String s in stringTobeSeparated) {
var list = s.split("=");
if(list.length == 2) {
// list[0] is your key and list[1] is your value
map[list[0]] = list[1];
}
}
You can use map for this, the accepted answer is correct, but since your string looks like this
var stringTobeSeparated = ['ab = cd','ef = gh','ld = kg'];
I would rather use regex to remove spaces from final result (replace the line with split with this):
var list = s.split(RegExp(r"\s+=\s+"));

Swift OS X String to Int Conversion Error

I'm having trouble converting a String to Int in my Swift OS X Xcode project. I have some data saved in a text file in a comma delimited format. The contents of the text file is below:
1,Cessna 172,3,54.4,124,38.6112
(and a line break at the end)
I read the text file and seperate it, first by \n to get each line by itself, and then by , to get each element by itself. The code to do this is below:
if let dir : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
let path = dir.stringByAppendingPathComponent("FSPassengers/aircraft.txt")
do {
let content = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding)
if content != "" {
let astrContent:[String] = content.componentsSeparatedByString("\n")
for aeroplane in astrContent {
let aSeperated:[String] = aeroplane.componentsSeparatedByString(",")
print(aSeperated[0])
print(Int(aSeperated[0]))
//self.aAircraft.append(Aircraft(id: aSeperated[0], type: aSeperated[1], passengerCapacity: Int(aSeperated[2])!, cargoCapacityKg: Double(aSeperated[3])!, cruiseSpeed: Int(aSeperated[4])!, fuelLitresPerHour: Double(aSeperated[5])!))
}
}
}
catch {
print("Error")
}
}
The end result here will be to assign each record (each line of the text file) into the array aAircraft. This array is made up of a custom object called Aircraft. The custom class is below:
class Aircraft: NSObject {
var id:Int = Int()
var type:String = String()
var passengerCapacity:Int = Int()
var cargoCapacityKg:Double = Double()
var cruiseSpeed:Int = Int()
var fuelLitresPerHour:Double = Double()
override init() {}
init(id:Int, type:String, passengerCapacity:Int, cargoCapacityKg:Double, cruiseSpeed:Int, fuelLitresPerHour:Double) {
self.id = id
self.type = type
self.passengerCapacity = passengerCapacity
self.cargoCapacityKg = cargoCapacityKg
self.cruiseSpeed = cruiseSpeed
self.fuelLitresPerHour = fuelLitresPerHour
}
}
In the first code extract above, where I split the text file contents and attempt to assign them into the array, you will see that I have commented out the append line. I have done this to get the application to compile, at the moment it is throwing me errors.
The error revolves around the conversion of the String values to Int and Double values as required. For example, Aircraft.id, or aSeperated[0] needs to be an Int. You can see that I use the line Int(aSeperated[0]) to convert the String to Int in order to assign it into the custom object. However, this line of code is failing.
The two print statements in the first code extract output the following values:
1
Optional(1)
If I add a ! to the end of the second print statement to make them:
print(aSeperated[0])
print(Int(aSeperated[0])!)
I get the following output:
I understand what the error means, that it tried to unwrap an optional value because I force unwrapped it, and it couldn't find an Int value within the string I passed to it, but I don't understand why I am getting the error. The string value is 1, which is very clearly an integer. What am I doing wrong?
Because Casena 172 is not convertible to an Int. You also have other decimal numbers which you will lose precision when casting them to Int. Use NSScanner to create an initializer from a CSV string:
init(csvString: String) {
let scanner = NSScanner(string: csvString)
var type: NSString?
scanner.scanInteger(&self.id)
scanner.scanLocation += 1
scanner.scanUpToString(",", intoString: &type)
self.type = type as! String
scanner.scanLocation += 1
scanner.scanInteger(&self.passengerCapacity)
scanner.scanLocation += 1
scanner.scanDouble(&self.cargoCapacityKg)
scanner.scanLocation += 1
scanner.scanInteger(&self.cruiseSpeed)
scanner.scanLocation += 1
scanner.scanDouble(&self.fuelLitresPerHour)
}
Usage:
let aircraft = Aircraft(csvString: "1,Cessna 172,3,54.4,124,38.6112")
As #mrkxbt mentioned, the issue was related to the blank line after the data in the text file. The string was being split at the \n which was assigning two values into the array. The first value was a string containing the data and the second was an empty string, so obviously the second set of splitting (by ,) was failing. Amended and working code is below:
if let dir : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
let path = dir.stringByAppendingPathComponent("FSPassengers/aircraft.txt")
do {
let content = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding)
if content != "" {
let astrContent:[String] = content.componentsSeparatedByString("\n")
for aeroplane in astrContent {
if aeroplane != "" {
let aSeperated:[String] = aeroplane.componentsSeparatedByString(",")
print(aSeperated[0])
print(Int(aSeperated[0])!)
self.aAircraft.append(Aircraft(id: Int(aSeperated[0])!, type: aSeperated[1], passengerCapacity: Int(aSeperated[2])!, cargoCapacityKg: Double(aSeperated[3])!, cruiseSpeed: Int(aSeperated[4])!, fuelLitresPerHour: Double(aSeperated[5])!))
}
}
}
}
catch {
print("Error")
}
}

Swift and XCode 6 - Converting Integer to String

I have an Xcode project with a label and a UIAction button. Upon tapping the button, I want the value displayed in the label to increase by 1. The problem is that I can't display the variable "value" in the label, because it's an integer, and the label takes a String data type. Here is the code I have so far:
var value = 0
#IBOutlet var label: UILabel!
#IBAction func button(sender: AnyObject) {
value = value + 1
label.text = value
}
label.text = String(value)
Or
label.text = "\(value)"
Or
label.text = value.description
Of course I would save some typing and express it this way:
value++
label.text = value.description
In the end it is the same thing as:
value = value + 1
label.text = value.description
you can convert value before saving core data directly just like that
//core data
userid value = string
we need to store Int value we have to convert the value explicitly like that. I tried that and it works fine
core data contain task entity having user_id attribute
tasksEntity.user_id = string
that should work

Selecting a tuple index using a variable in Swift

That is what i am trying to do:
var i = 0
var string = "abcdef"
for value in string
{
value.[Put value of variable i here] = "a"
i++
}
How can i insert the value of i in the code?
Easiest is probably just convert it to an NSMutableString:
let string = "abcdef".mutableCopy() as NSMutableString
println( "\(string)")
for var i = 0; i < string.length; ++i {
string.replaceCharactersInRange(NSMakeRange(i, 1), withString: "a")
}
println( "\(string)")
Yes, it's a bit ugly but it works.
A much cleaner way is to use Swifts map function:
var string = "abcdef"
let result = map(string) { (c) -> Character in
"a"
}
println("\(result)") // aaaaaa
You should just be able to use the following but this doesn't compile:
map(string) { "a" }
In you comments you mention you want to split up the string on a space, you can just use this for that:
let stringWithSpace = "abcdef 012345"
let splitString = stringWithSpace.componentsSeparatedByString(" ")
println("\(splitString[0])") // abcdef
println("\(splitString[1])") // 012345

How to get SubstringValues from Textbox

len = int.Parse(tE1Clt.Text);
front=int.Prase(tE_Fstng.text);
string result = tE3_Series.Text.Substring(front, len);
tE1_Sub.Text = result.ToString();
I'm getting error
[index and length must refer to a location within the string. Parameter name: `length`]
if (TeInput.Text.Length > 1)
{
string Input = TeInput.Text, Store1 = string.Empty, store2 = string.Empty;
int Start = 0, End = 0;
Start = int.Parse(TeStart.Text);
End = int.Parse(TeEnd.Text);
string Output = TeOutput.Text;
Store1 = Input.Remove(0, Start).Trim();
store2 = Store1.Remove(Store1.Length-End).Trim();
TeOutput.Text = store2;
You can do like this,
var str = "----takemeout----";
var start = str.IndexOf('t'); // start index of first t
var length = 9; // length of takemeout string
var result = str.Substring(start, length);
Value or result will be "takemeout"

Resources