Replace array in range - arrays

I have an array of strings ["", "", "", "1"]
And I want an arrays with all empty strings replaced with zeros - ["0", "0", "0", "1"]
Is there a built-in operator, function or method to help me do this without having to re-invent the wheel?

If your transformation needs strings as result, the comment from TusharSharma provides a solution that answers exactly your question (I'll not repeat it, because I hope he'll enter it as an answer).
However, looking at your example, it seems that you deal with numeric strings. For the records, I'd like to suggest then to simply consider to produce an array of integers.
let s = ["", "", "", "1"]
let r = s.map{Int($0) ?? 0}
If the numbers are doubles:
let r2 = s.map{String(Double($0) ?? 0.0)}
Using the numerics allows you to easily use more advanced build-in formatting:
let r3 = s.map{String(format: "%.2f", Double($0) ?? 0.0)}
or even use some custom number formatter able to use the locales (more here)

Related

How i can collect array's values as number?

i want from tableview to collect MyArray's as value like
Swift:
let total = UILabel()
var MyArray = ["2", "9", "33", "4"]
total.text = ?? // i want result be like this [2+9+33+4] = 48
and if add some value or remove some the result change
i hope i delivered right question and i hope i get the right answer
Iterate through your array, using conditional binding, if the value is invalid, e.g "hello", it won't enter the condition.
var result = 0
for element in MyArray { // MyArray should have the first letter lowercased and have a more meaningful name.
if let number = Int(element) { // or NSNumber, Double, etc...
result = result + number
}
}
total.text = "\(result)" // consider naming it totalLabel
Convert the myArray elements type from String to Double using compactMap. Then add the elements using reduce method. Then convert the result to string to show in label.
var myArray = ["2", "9", "33", "4", "wot?", "🐶"]
total.text = String(myArray.lazy.compactMap{ Double($0) }.reduce(0, +))//48.0
Two suggestions:
With reduce to sum up the values and ignore non-integer values
total.text = String(myArray.reduce(0, {$0 + (Int($1) ?? 0)}))
With NSExpression if the array contains only string representations of integers. joined converts the array to "2+9+33+4"
let additionExpression = NSExpression(format: myArray.joined(separator: "+"))
total.text = "\(additionExpression.expressionValue(with: nil, context: nil)!)"
There are two steps::
Calculate the total.
Consider:
let array = ["200", "900", "33", "4"]
let total = array
.lazy
.compactMap { Double($0) }
.reduce(0, +)
Note, unlike other suggestions, I’m refraining from placing this in a single line of code (although one could). The goal of functional programming patterns is to write expressive yet efficient code about which it is easy to reason. Placing all of this onto one line is contrary to that goal, IMHO, though it is arguably a matter of personal preference.
Setting the text of the label.
When setting the text of the label, it’s very tempting to want to just do String(total). But that is not a very user-friendly presentation (e.g. the sum 1,137 will be shown as “1137.0”). Nor is it localized.
The typical solution when displaying a result (whether numbers, dates, time intervals, etc.) in the user interface is to use a “formatter”. In the case of numeric values, one would typically use a NumberFormatter:
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
label.text = formatter.string(for: total)
For a user in the US, that will show “1,137”, whereas the German user will see “1.137”. So each device sees the number presented in a format consistent with the users’ localization preferences.

How do I select a random value from an array in TestComplete?

I'm using JScript to test the character limit of a textbox, and also to make sure that numbers, characters, and special characters are accepted.
If I have an array like ("a", "2", "$", "D"), how can I choose one random value at a time?
I know about Math.round(Math.random()*9), but I don't want to return just an integer.
Thank you.
Here is what I did:
str = new Array("a", "2", "$", "D");
var result = str[Math.floor(Math.random()*str.length)];
textBox.Keys(result);

Swift - pruning elements from an Array, converting integer strings to integers

I have an array that contains numbers and empty strings, like ["", "2", "4", "", "", "1", "2", ""]. I would like to pare this down to a list of numbers, like [2,4,1,2].
My first effort split this into two steps, first strip out the empty strings, then do the string-to-integer conversion. However, my code for step one isn't working as desired.
for (index,value) in tempArray.enumerate(){
if value == "" {
tempArray.removeAtIndex(index)
}
}
This fails, I believe because it is using the index values from the original, complete array, though after the first deletion they are not longer accurate.
What would be a better way to accomplish my goal, and what is the best way to convert the resulting array of integer strings to an array of integers?
var str = ["", "2", "4", "", "", "1", "2", ""]
let filtered = str.filter {$0 != "" }
let intArr = filtered.map {($0 as NSString).integerValue}
With Swift 2 we can take advantage of flatMap and Int():
let stringsArray = ["", "2", "4", "", "", "1", "2", ""]
let intsArray = stringsArray.flatMap { Int($0) }
print(intsArray) // [2, 4, 1, 2]
Explanation: Int() returns nil if the string does not contain an integer, and flatMap ignores nils and unwraps the optional Ints returned by Int().

Writing an Int-Array to a text file

I need to write a dictionary to a text file. I couldn't find anything handy. But writing an array is solved only for strings:
let pieces = [ "1", "5", "1", "4" ]
let joined = "\n".join(pieces)
How could I join integers without creating my own loop?
If there is a simple solution for dictionary itself, that would be better! ;-)
So you have an array of Int
let numbers = [1,2,3,4,5]
And you want to concatenate the text representations of these numbers without writing a loop right?
You can write this:
let joined = "\n".join( numbers.map { "\($0)" } )
Now joined has this value: "1\n2\n3\n4\n5"
Hope this helps.

Accessing values from Dictionaries that are part of an Array in Swift

G'day,
I'm trying to use a for loop to access the values for the same key within an array of dictionaries in Swift.
For example,
let dictionaryOne = [
"name": "Peter",
"age": "42",
"location": "Milwaukee"]
let dictionaryTwo = [
"name": "Paul",
"age": "89",
"location": "Denver"]
let arrayOfDictionaries = [dictionaryOne, dictionaryTwo]
I'm attempting to create a function using a for loop that will output an array containing the values for location i.e. ["Milwaukee", "Denver"]
I have looked at other responses but I can only find how to access the value for "location" straight from the dictionary itself, which would be cumbersome if there were many different dictionaries rather than just two.
Many thanks for any help you can provide!
You can take advantage of the map method, whose purpose is to loop through the array and transform each element into another type:
arrayOfDictionaries.map { (dict: [String : String]) -> String? in
return dict["location"]
}
The closure passed to the map receives an array element, and returns the transformed value - in your case, it retrieves and returns the value for the location key.
You can also use the compact form:
arrayOfDictionaries.map { $0["location"] }
Note that this method returns an array of optional strings, because the dictionary subscript operator always returns an optional. If you need an array of non optionals, then this is the unsafe version:
let x = arrayOfDictionaries.map { $0["location"]! }
Of course if the value for "location" key doesn't exist for an array element, a runtime exception will be raised.
More info about map at the Swift Standard Template Library
The way I see it, you would populate a new array of Strings from the cities listed before.
var locations = [String]()
for dictionary in arrayOfDictionaries{
locations.append(dictionary["location"]!)
}
println(locations)
There are a few ways you could do this. One is to use key-value coding (KVC):
let locations = (arrayOfDictionaries as NSArray).valueForKey("location") as [String]

Resources