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
Related
I created a user defined variable i and put value 0.
In groovy I try to run on a list starting [i], but it returned 48.
when I hard coded put 0, the script is OK
why I is set to 48?
List<String> myList = props.get("myListKey");
int i = vars.get("i");
String id = myList[i];
//String id = myList[0];
System.out.println("id: " + id);
vars.putObject("id", id);
System.out.println("I is: " + i);
The correct way to convert String to number in groovy is using toInteger() function:
int value = vars.get("i").toInteger()
log.info("I2 is: " + value);
Currently you return the ASCII value of character 0 (48). you can check also other options to convert String to int.
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
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")
}
}
so I want to kind of build a "Decrypter", I have a dictionary with the keys being the symbol, and the value the respective value for the symbol, then I have this string that the code is suppose to look into, the translate will be saved in a other string, in this case called output. This is the way I did the loop part, but is not working:
var outputText = " "
for character in textForScan{
for key in gematriaToLetters{
if (gematriaToLetters.keys == textForScan[character]){
outputText.insert(gematriaToLetters.values, atIndex: outputText.endIndex)
}
}
}
You could also consider using map:
let outputText = "".join(map(textForScan) { gematriaToLetters[String($0)] ?? String($0) })
If you don't specify a specific letter in the dictionary it returns the current letter without "converting".
I think you are looking for something like this:
for aCharacter in textForScan {
let newChar = gematrialToLetters["\(aCharacter)"]
outputText += newChar
}
print(outputText)
How to select random item from a combo box, without selecting what is there already in the combobox.
I guess you want something like this:
Random random = new Random();
int newIndex = -1;
do {
newIndex = random.Next(comboBox.Items.Count);
} while (newIndex == comobBox.SelectedIndex && comboBox.Items.Count > 1);
comobBox.SelectedIndex = random.Next(comboBox.Items.Count);
Basically Combo box has items in string so if you can describe me some clear then we may help more anyway here is sample code
n you can do it
ComboBox b = new ComboBox();
Random rt = new Random();
string myText = "";
myText = b.Items[rt.Next(0, b.Items.Count - 1)].ToString();
You should use the Random class to get a random number between 0 and the max amount of items in the combobox. You should get this number repeatedly until you get one that doesn't match what is already selected within the combobox, like so:
Random random = new Random();
int newSelectedIndex = comboBox.SelectedIndex;
while (newSelectedIndex == comboBox.SelectedIndex) {
newSelectedIndex = random.Next(0, comboBox.Items.Count);
}
comboBox.SelectedIndex = newSelectedIndex;
// Item
// comboBox.Items[newSelectedIndex];
This may not work C/P'd, as I wrote it from the top of my head and don't have an IDE to test right now, but I hope you get the idea.
IMPORTANT: If you only have 1 item which is also selected, this may get into an endless loop...