I was reading over some resources about Swift 5's String Interpolation and was trying it out in a Playground. I successfully combined two separate Strings but I am confused about how to combine an Array of Strings.
Here's what I did ...
String(stringInterpolation: {
let name = String()
var combo = String.StringInterpolation(literalCapacity: 7, interpolationCount: 1)
combo.appendLiteral("Sting One, ")
combo.appendInterpolation(name)
combo.appendLiteral("String Two")
print(combo)
return combo
}())
How would you do something like this with an Array of Strings?
It’s unclear what this is supposed to have to do with interpolation. Perhaps there’s a misunderstanding of what string interpolation is? If the goal is to join an array of strings into a single comma-separated string, just go ahead and join the array of strings into a single string:
let arr = ["Manny", "Moe", "Jack"]
let s = arr.joined(separator: ", ")
s // "Manny, Moe, Jack”
If the point is that the array element type is unknown but is string-representable, map thru String(describing:) as you go:
let arr = [1,2,3]
let s = arr.map{String(describing:$0)}.joined(separator: ", ")
s // "1, 2, 3”
Related
i have 2 arrays:
"interfaceTitles" with the values "USB ports", "digital inputs", "RS232, ...
"interfaceAmounts" with the values "3", "20", "1", ...
I need a merged Array with combined values. So the new array should have the following values:
"3 USB ports", "20 digital inputs" ...
So its not just concating, its fusionating :D
interfacesAdded = interfaceAmounts && interfaceTitles doesn't work
interfacesAdded = interfaceAmounts + interfaceTitles makes it into an string
"interfacesAdded" is declared as const interfacesAdded: any = ...
what can I do for this, Search function didn't help me, sorry im kinda unexperienced :(
Greetings
The below uses the map function to loop over the interfaceTitles list, and return a new list where the elements are the corresponding elements from the two lists joined by a space.
const result = interfaceTitles.map((_, i) => {
return interfaceAmounts[i] + " " + interfaceTitles[i];
});
Hope this is what you are looking for.
I think you could add the language you are using to help better answer,
the logic will be the same in different language, i'm doing it in js.
Admitting the string you want to concat are in the same position of the 2 arrays:
const array1 = [1, 4, 9, 16];
const array2 = ['a','b','c','d'];
// pass a function to map
// care in js we can use the + to concat string
// map will iterate over each element of array1
// x will be the current element of array1
// index will be the index of the current element,
// used to get the corresponding element in array2
const map1 = array1.map((x,index) => x+array2[index]);
console.log(map1);
// expected output: > Array ["1a", "4b", "9c", "16d"]
I have an array that is storing a large number of various names in string format. There can be duplicates.
let myArray = ["Jim","Tristan","Robert","Lexi","Michael","Robert","Jim"]
In this case I do NOT know what values will be in the array after grabbing the data from a parse server. So the data imported will be different every time. Just a list of random names.
Assuming I don't know all the strings in the array I need to find the index of the last occurrence of each string in the array.
Example:
If this is my array....
let myArray = ["john","john","blake","robert","john","blake"]
I want the last index of each occurrence so...
blake = 5
john = 4
robert = 3
What is the best way to do this in Swift?
Normally I would just make a variable for each item possibility in the array and then increment through the array and count the items but in this case there are thousands of items in the array and they are of unknown values.
Create an array with elements and their indices:
zip(myArray, myArray.indices)
then reduce into a dictionary where keys are array elements and values are indices:
let result = zip(myArray, myArray.indices).reduce(into: [:]) { dict, tuple in
dict[tuple.0] = tuple.1
}
(myArray.enumerated() returns offsets, not indices, but it would have worked here too instead of zip since Array has an Int zero-based indices)
EDIT: Dictionary(_:uniquingKeysWith:) approach (#Jessy's answer) is a cleaner way to do it
New Dev's answer is the way to go. Except, the standard library already has a solution that does that, so use that instead.
Dictionary(
["john", "john", "blake", "robert", "john", "blake"]
.enumerated()
.map { ($0.element, $0.offset) }
) { $1 }
Or if you've already got a collection elsewhere…
Dictionary(zip(collection, collection.indices)) { $1 }
Just for fun, the one-liner, and likely the shortest, solution (brevity over clarity, or was it the other way around? :P)
myArray.enumerated().reduce(into: [:]) { $0[$1.0] = $1.1 }
My goal is to combine an array of strings (apple,banana,orange) and an array of ints (4,1,3), then find the smallest int in that 2D array 1, and finally print the matching string to it banana. I tried using minOf and Arrays.deepToString , but they didn´t work together how I intended. If someone knows a better way maybe with pairs (I don´t know a lot about that), any help is appreciated!
fun main(){
var fruits = arrayOf("apple","banana","orange")
var ratings = intArrayOf(4,1,3)
var combined = arrayOf(fruits, ratings)
//did not work
println(minOf(Arrays.deepToString(combined)))
}
You could do something like this to first combine two arrays (you could also use lists, BTW) with zip, then find the minimum among the pairs, and deconstruct the pair fields again:
val fruits = arrayOf("apple", "banana", "orange")
val ratings = arrayOf(4, 1, 3)
val (minFruit, minRating) = fruits.zip(ratings).minBy {
(_ /* Swallow the fruit as we don't need it here */ , rating) ->
rating
} ?: throw IllegalArgumentException("Cannot find the minimum of an empty list.")
println(minFruit)
println(minRating)
I have two arrays of strings that I join together with a "-" separator which turns it into a full string like so "art-movies-sports". The code is below:
let myFirstArray: [String] = ["art", "movies", "sports"]
let firstJoinedArray = myFirstArray.joined(separator: "-")
let mySecondArray: [String] = ["art", "movies", "sports"]
let secondJoinedArray = mySecondArray.joined(separator: "-")
What I want is to call something when 3 or more words from "art-movies-sports" in firstJoinedArray are equal to 3 or more words in secondJoinedArray. In this case, it will of course be correct. In a nutshell, I want to have much longer strings (both containing different words but have 3 or 4 that are the same) and I want to call something when 3 or more are correct. Any help will be much appreciated! Thank you.
I would use the arrays directly, rather than the string. Then create sets out of them, so you can find their intersection:
let set1 = Set(myFirstArray)
let set2 = Set(mySecondArray)
let inCommon = set1.intersection(set2).count // If this is >= 3, do stuff
I have one text field but I want to be able to store the multiple values entered in that text field (eg. 1,2,3,4) stored into an array. So far, all it does is store it all as one element that still has the commas. How can I get rid of the commas and store each value separately?
You can use global split function which works on any Sequence (including String):
If you want it to be separated by commas only:
let array = split("x,y,z") { $0 == "," }
If you'd want to separate by either commas or spaces:
let array = split("x, y z") { contains(", ", $0) }
You can use the string method componentsSeparatedByString(separator: String) -> [String]
For example:
let example = "1,2,3,4"
let elements = textfieldValue.componentsSeparatedByString(",") // elements is an array with Strings.
Just try below :-
NSArray *valueArr=[[yourTextfield stringValue] componentsSeparatedByString:#","];