How to convert Strings in Swift? - arrays

I've two cases where I need to convert strings to different formats.
for ex:
case 1:
string inputs: abc, xyz, mno, & llr // All Strings from a dictionary
output: ["abc","xyz", "mno", "llr"] //I need to get the String array like this.
But when I use this code:
var stringBuilder:[String] = [];
for i in 0..<4 {
stringBuilder.append("abc"); //Appends all four Strings from a Dictionary
}
print(stringBuilder); //Output is 0: abc, 1:xyz like that, how to get desired format of that array like ["abc", "xyz"];
Real usage:
let arr = Array(stringReturn.values);
//print(arr) // Great, it prints ["abc","xyz"];
let context = JSContext()
context?.evaluateScript(stringBuilder)
let testFunction = context?.objectForKeyedSubscript("KK")
let result = testFunction?.call(withArguments:arr); // Here when I debugger enabled array is passed to call() like 0:"abc" 1:"xyz". where as it should be passed as above print.
Secondly how to replace escape chars in swift: I used "\" in replaceOccurances(of:"\\'" with:"'"); but its unchanged. why and how to escape that sequnce.
case 2:
string input: \'abc\'
output: 'abc'

To get all values of your dictionary as an array you can use the values property of the dictionary:
let dictionary: Dictionary<String, Any> = [
"key_a": "value_a",
"key_b": "value_b",
"key_c": "value_c",
"key_d": "value_d",
"key_e": 3
]
let values = Array(dictionary.values)
// values: ["value_a", "value_b", "value_c", "value_d", 3]
With filter you can ignore all values of your dictionary that are not of type String:
let stringValues = values.filter({ $0 is String }) as! [String]
// stringValues: ["value_a", "value_b", "value_c", "value_d"]
With map you can transform the values of stringValues and apply your replacingOccurrences function:
let adjustedValues = stringValues.map({ $0.replacingOccurrences(of: "value_", with: "") })
// adjustedValues: ["a", "b", "c", "d"]

Why not try something like this? For part 1 of the question that is:
var stringReturn: Dictionary = Dictionary<String,Any>()
stringReturn = ["0": "abc","1": "def","2": "ghi"]
print(stringReturn)
var stringBuilder = [String]()
for i in stringReturn {
stringBuilder.append(String(describing: i.value))
}
print(stringBuilder)
Also, part 2 seems to be trivial unless I'm not mistaken
var escaped: String = "\'abc\'"
print(escaped)

case 1:
I have Implemented this solutions, Hope this will solve your problem
let dict: [String: String] = ["0": "Abc", "1": "CDF", "2": "GHJ"]
var array: [String] = []
for (k, v) in dict.enumerated() {
print(k)
print(v.value)
array.append(v.value)
}
print(array)
case 2:
var str = "\'abc\'"
print(str.replacingOccurrences(of: "\'", with: ""))

Related

merging element of two different arrays into dictionary in swift

i have two arrays like these
var arr1 = ["han", "Ji", "Kidda", "Ho", "Tusi"]
var arr2 = ["hello", "Ji"]
i want to create a new dictionary that have first element of first array and first element of second array and so on. when the third element of first array comes it should again get the first element of second array.
for example:-
dict = ["han" : "hello", "Ji" : "Ji", "Kidda" : hello, "Ho" : "Ji", "Tusi" : "hello"]
If the second array has 2 items you can do
var dict = [String: String]()
for (index, item) in arr1.enumerated() {
dict[item] = arr2[index % 2]
}
I believe this is what you're looking for (using arr1 as the keys and arr2 as the values repeating them as necessary):
var arr1 = ["han", "Ji", "Kidda", "Ho", "Tusi"]
var arr2 = ["hello", "Ji"]
let dict = Dictionary(uniqueKeysWithValues: zip(arr1, arr1.indices.map { arr2[$0 % arr2.count] }))
print(dict)
["Kidda": "hello", "Ji": "Ji", "han": "hello", "Ho": "Ji", "Tusi": "hello"]
Note:
Dictionaries have no specified ordering. Only the key/value pairings matter. This matches the example in your question.
Explanation:
zip is used to create a sequence of (key, value) tuples from two sequences that will become the key/value pairs for the new Dictionary. The keys come from arr1. map is used to generate the sequence of values from arr2 repeating them as many times as necessary to match the count of arr1. This sequence of (key, value) tuples is passed to Dictionary(uniqueKeysWithValues:) to turn that sequence into the desired Dictionary.
try:
var dict = ["arr1" : "hello", "arr2" : "Ji"]
then for third you can append by
dict[3] = ["arr3" : String(arr3.first())]
Try this:
var arr1 = ["han", "Ji", "Kidda", "Ho", "Tusi"]
var arr2 = ["hello", "Ji"]
var dict : [String : String] = [:]
var arr2Index = 0
for index in 0..<arr1.count {
let arr1Value = arr1[index]
if arr2Index == arr2.count {
arr2Index = 0
}
let arr2Value = arr2[arr2Index]
dict[arr1Value] = arr2Value
arr2Index += 1
}
Here's a fun way:
let arr1 = ["han", "Ji", "Kidda", "Ho", "Tusi"]
let arr2 = ["hello", "Ji"]
let arr3 = Array(repeating: arr2, count: arr1.count).joined()
let d = zip(arr1,arr3).reduce(into: [String:String]()) { $0[$1.0] = $1.1 }

Convert Array<String> to String then back to Array<String>

say I have a variable
let stringArray = "[\"You\", \"Shall\", \"Not\", \"PASS!\"]"
// if I show this, it would look like this
print(stringArray)
["You", "Shall", "Not", "PASS!"]
now let's have an Array< String>
let array = ["You", "Shall", "Not", "PASS!"]
// if I convert this into string
// it would roughly be equal to the variable 'stringArray'
if String(array) == stringArray {
print("true")
} else {
print("false")
}
// output would be
true
now say what should I do to convert variable 'stringArray' to 'Array< String>'
The answer would be to convert the string using NSJSONSerialization
Thanks Vadian for that tip
let dataString = stringArray.dataUsingEncoding(NSUTF8StringEncoding)
let newArray = try! NSJSONSerialization.JSONObjectWithData(dataString!, options: []) as! Array<String>
for string in newArray {
print(string)
}
voila there you have it, it's now an array of strings
A small improvement for Swift 4.
Try this:
// Array of Strings
let array: [String] = ["red", "green", "blue"]
let arrayAsString: String = array.description
let stringAsData = arrayAsString.data(using: String.Encoding.utf16)
let arrayBack: [String] = try! JSONDecoder().decode([String].self, from: stringAsData!)
For other data types respectively:
// Set of Doubles
let set: Set<Double> = [1, 2.0, 3]
let setAsString: String = set.description
let setStringAsData = setAsString.data(using: String.Encoding.utf16)
let setBack: Set<Double> = try! JSONDecoder().decode(Set<Double>.self, from: setStringAsData!)

Find unique values in a Swift Array

I am building a project that tells me the unique words in a piece of text.
I have my orginal string scriptTextView which I have added each word into the array scriptEachWordInArray
I would now like to create an array called scriptUniqueWords which only includes words that appear once (in other words are unique) in scriptEachWordInArray
So I'd like my scriptUniqueWords array to equal = ["Silent","Holy"] as a result.
I don't want to create an array without duplicates but an array that has only values that appeared once in the first place.
var scriptTextView = "Silent Night Holy Night"
var scriptEachWordInArray = ["Silent", "night", "Holy", "night"]
var scriptUniqueWords = [String]()
for i in 0..<scriptEachWordInArray.count {
if scriptTextView.components(separatedBy: "\(scriptEachWordInArray[i]) ").count == 1 {
scriptUniqueWords.append(scriptEachWordInArray[i])
print("Unique word \(scriptEachWordInArray[i])")}
}
You can use NSCountedSet
let text = "Silent Night Holy Night"
let words = text.lowercased().components(separatedBy: " ")
let countedSet = NSCountedSet(array: words)
let singleOccurrencies = countedSet.filter { countedSet.count(for: $0) == 1 }.flatMap { $0 as? String }
Now singleOccurrencies contains ["holy", "silent"]
Swift
lets try It.
let array = ["1", "1", "2", "2", "3", "3"]
let unique = Array(Set(array))
// ["1", "2", "3"]
Filtering out unique words without preserving order
As another alternative to NSCountedSet, you could use a dictionary to count the the number of occurrences of each word, and filter out those that only occur once:
let scriptEachWordInArray = ["Silent", "night", "Holy", "night"]
var freqs: [String: Int] = [:]
scriptEachWordInArray.forEach { freqs[$0] = (freqs[$0] ?? 0) + 1 }
let scriptUniqueWords = freqs.flatMap { $0.1 == 1 ? $0.0 : nil }
print(scriptUniqueWords) // ["Holy", "Silent"]
This solution, however (as well as the one using NSCountedSet), will not preserve the order of the original array, since a dictionary as well as NSCountedSet is an unordered collection.
Filtering out unique words while preserving order
If you'd like to preserve the order from the original array (removing element which appear more than once), you could count the frequencies of each word, but store it in a (String, Int) tuple array rather than a dictionary.
Making use of the Collection extension from this Q&A
extension Collection where Iterator.Element: Hashable {
var frequencies: [(Iterator.Element, Int)] {
var seen: [Iterator.Element: Int] = [:]
var frequencies: [(Iterator.Element, Int)] = []
forEach {
if let idx = seen[$0] {
frequencies[idx].1 += 1
}
else {
seen[$0] = frequencies.count
frequencies.append(($0, 1))
}
}
return frequencies
}
}
// or, briefer but worse at showing intent
extension Collection where Iterator.Element: Hashable {
var frequencies: [(Iterator.Element, Int)] {
var seen: [Iterator.Element: Int] = [:]
var frequencies: [(Iterator.Element, Int)] = []
for elem in self {
seen[elem].map { frequencies[$0].1 += 1 } ?? {
seen[elem] = frequencies.count
return frequencies.append((elem, 1))
}()
}
return frequencies
}
}
... you may filter out the unique words of your array (while preserving order) as
let scriptUniqueWords = scriptEachWordInArray.frequencies
.flatMap { $0.1 == 1 ? $0.0 : nil }
print(scriptUniqueWords) // ["Silent", "Holy"]
you can filter the values that are already contained in the array:
let newArray = array.filter { !array.contains($0) }

Swift: How to filter json data

if a NSArray data like this:
var arrayData:NSArray = [{name:"aaa",tel:"0000"},{name:"bbb",tel:"0000"}]
how do I filter name = "aaa"
thanks.
In Swift you can use the filter method in Array. The method takes a closure indicating whether to include the value in the new array. For example:
let array: NSArray = ["aaa", "bbb", "ccc"]
let fiteredArray = (array as! Array).filter { $0 != "aaa" }
filteredArray now only contains "bbb" and "ccc".

How can I put each word of a string into an array in Swift?

Is it possible to put each word of a string into an array in Swift?
for instance:
var str = "Hello, Playground!"
to:
var arr = ["Hello","Playground"]
Thank you :)
edit/update:
Xcode 10.2 • Swift 5 or later
We can extend StringProtocol using collection split method
func split(maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: (Character) throws -> Bool) rethrows -> [Self.SubSequence]
setting omittingEmptySubsequences to true and passing a closure as predicate. We can also take advantage of the new Character property isLetter to split the string.
extension StringProtocol {
var words: [SubSequence] {
return split { !$0.isLetter }
}
}
let sentence = "• Hello, Playground!"
let words = sentence.words // ["Hello", "Playground"]
Neither answer currently works with Swift 4, but the following can cover OP's issue & hopefully yours.
extension String {
var wordList: [String] {
return components(separatedBy: CharacterSet.alphanumerics.inverted).filter { !$0.isEmpty }
}
}
let string = "Hello, Playground!"
let stringArray = string.wordList
print(stringArray) // ["Hello", "Playground"]
And with a longer phrase with numbers and a double space:
let biggerString = "Hello, Playground! This is a very long sentence with 123 and other stuff in it"
let biggerStringArray = biggerString.wordList
print(biggerStringArray)
// ["Hello", "Playground", "This", "is", "a", "very", "long", "sentence", "with", "123", "and", "other", "stuff", "in", "it"]
That last solution (from Leo) will create empty elements in the array when there are multiple consecutive spaces in the string. It will also combine words separated by "-" and process end of line characters as words.
This one won't :
extension String
{
var wordList: [String]
{
return componentsSeparatedByCharactersInSet(NSCharacterSet.alphanumericCharacterSet().invertedSet).filter({$0 != ""})
}
}

Resources