Array (Inside of a String) Conversion, Swift 4 - swift4

Does anyone know the simplest way to convert an Array inside of a String to an actual Array without effecting any characters?
For Example:
var array: [String] = []
let myStr = "[\"Hello,\", \"World\"]"
// I would like 'array' to store: ["Hello,", "World"]
I thought it could be done with Array(myStr) but that would only make an array of all the characters.
Help would be appreciated. Thank you.

You can decode it with JSONDecoder, since it is a JSON.
Example below:
let myStr = "[\"Hello,\", \"World\"]"
let data = Data(myStr.utf8)
do {
let decoded = try JSONDecoder().decode([String].self, from: data)
print("Decoded:", decoded)
} catch {
fatalError("Error")
}
// Prints: Decoded: ["Hello,", "World"]
What is happening:
Your myStr string is converted to Data.
This data is then decoded as [String] - which is an array of strings.
The decoded data of type [String] is then printed.
We use a do-try-catch pattern to catch errors, such as incorrect format or data entered.

Related

Parsing Data Out of Dictionary<String, Any> in Swift

I'm trying to extract data out of a Dictionary<String, Any> in Swift. The dictionary returns the following when I run NSLog("\(terminalDict)"):
Optional(["DFEE22": <323c3c>, "DFEE20": <3c>, "DFEE21": <0a>, "DFEE17": <07>, "DFEE1E": , "DF10": <656e6672 65737a68>, "9F1C": <38373635 34333231>, "DFEE16": <00>, "DFEE15": <01>, "5F36": <02>, "DF11": <00>, "DFEE1F": <80>, "DFEE18": <80>, "9F1A": <0840>, "9F35": <21>, "9F4E": <31303732 31205761 6c6b6572 2053742e 20437970 72657373 2c204341 202c5553 412e>, "DF27": <00>, "DFEE1B": <30303031 35313030>, "DF26": <01>, "9F15": <1234>, "9F40": <f000f0a0 01>, "9F16": <30303030 30303030 30303030 303030>, "9F33": <6028c8>, "9F1E": <5465726d 696e616c>])
I want to get all the keys and values out of the dictionary and into one string variable (newSettings). This is how I was attempting to do that:
for (key, value) in terminalDict! {
NSLog("key is now= \(key)")
NSLog("value is now= \(value)")
let asString = value as! String
print(asString)
NSLog("Adding \(key) \(asString)")
newSettings = "\(newSettings)\(key)\(asString)"
}
which returns:
key is now= DFEE22
value is now= {length = 3, bytes = 0x323c3c}
Could not cast value of type 'NSConcreteMutableData' (0x204aff148) to 'NSString' (0x204afde30).
How can I get the "323c3c" out of the dictionary as a simple string without the length and bytes portion? I can't find much documentation on type 'NSConcreteMutableData'. Do I have to use substring functions in order to get rid of the "length=x bytes=" part? I'm guessing there's a better way to do this than manually getting the substrings. Thanks.
As Vadian says, your dictionaries contain Data values.
It looks like it is ASCII encoded text, but it's a bit hard to be sure.
This bit:
31303732 31205761 6c6b6572 2053742e 20437970 72657373 2c204341 202c5553 412e
Represents the string "10721 Walker St. Cypress, CA ,USA." when you treat it as ASCII.
you could use code like this:
for (key, value) in terminalDict! {
NSLog("key is now= \(key)")
// Decode the data into a String assuming it's ASCII
let asString = String(data: value, encoding: .ascii)
NSLog("value is now= '\(asString)'")
print(asString)
NSLog("Adding \(key) \(asString)")
newSettings = "\(newSettings)\(key)\(asString)"
}

How to convert Array of string to Array of URL?

Need to convert array of string value to array of URL. Some one help me to convert the String array to URL array in swift.
let urls = ["www.1.com", "www.1.com", "www.1.com", "randomSmth"].compactMap { URL(string: $0) }
"compactMap" ensures that it just ignores invalid urls.
Use compact map to filter non valid URLs
let arrayOfStrings = ["https://www.google.com","https://www.facebook.com", "notRerallyAnURL"]
let arrayOfURLs = arrayOfStrings.compactMap { URL(string:$0) }

Cannot convert value of type Substring to expected argument type String - Swift 4

Trying to get substring of String and append it to array of Strings:
var stringToSplit = "TEST TEXT"
var s = [String]()
let subStr = anotherString[0 ..< 6]
s.append(subStr) // <---- HERE I GET THE ERROR
As #Leo Dabus mentioned, you need to initialize a new String with your substring:
Change:
s.append(subStr)
To:
s.append(String(subStr))
my two cents for serro in different context.
I was trying to get an array of "String" splitting a string.
"split" gives back "Substring", for efficiency reason (as per Swift.org litre).
So I ended up doing:
let buffer = "one,two,three"
let rows = buffer.split(separator:",")
let realStrings = rows.map { subString -> String in
return String(subString)
}
print(realStrings)
Ape can help someone else.

Convert UInt8 Array to String

I have decrypted using AES (CrytoSwift) and am left with an UInt8 array. What's the best approach to covert the UInt8 array into an appripriate string? Casting the array only gives back a string that looks exactly like the array. (When done in Java, a new READABLE string is obtained when casting Byte array to String).
I'm not sure if this is new to Swift 2, but at least the following works for me:
let chars: [UInt8] = [ 49, 50, 51 ]
var str = String(bytes: chars, encoding: NSUTF8StringEncoding)
In addition, if the array is formatted as a C string (trailing 0), these work:
str = String.fromCString(UnsafePointer(chars)) // UTF-8 is implicit
// or:
str = String(CString: UnsafePointer(chars), encoding: NSUTF8StringEncoding)
I don't know anything about CryptoSwift. But I can read the README:
For your convenience CryptoSwift provides two function to easily convert array of bytes to NSData and other way around:
let data = NSData.withBytes([0x01,0x02,0x03])
let bytes:[UInt8] = data.arrayOfBytes()
So my guess would be: call NSData.withBytes to get an NSData. Now you can presumably call NSString(data:encoding:) to get a string.
SWIFT 3.1
Try this:
let decData = NSData(bytes: enc, length: Int(enc.count))
let base64String = decData.base64EncodedString(options: .lineLength64Characters)
This is string output
Extensions allow you to easily modify the framework to fit your needs, essentially building your own version of Swift (my favorite part, I love to customize). Try this one out, put at the end of your view controller and call in viewDidLoad():
func stringToUInt8Extension() {
var cache : [UInt8] = []
for byte : UInt8 in 97..<97+26 {
cache.append(byte)
print(byte)
}
print("The letters of the alphabet are \(String(cache))")
}
extension String {
init(_ bytes: [UInt8]) {
self.init()
for b in bytes {
self.append(UnicodeScalar(b))
}
}
}

Swift: How to convert a String to UInt8 array?

How do you convert a String to UInt8 array?
var str = "test"
var ar : [UInt8]
ar = str
Lots of different ways, depending on how you want to handle non-ASCII characters.
But the simplest code would be to use the utf8 view:
let string = "hello"
let array: [UInt8] = Array(string.utf8)
Note, this will result in multi-byte characters being represented as multiple entries in the array, i.e.:
let string = "é"
print(Array(string.utf8))
prints out [195, 169]
There’s also .nulTerminatedUTF8, which does the same thing, but then adds a nul-character to the end if your plan is to pass this somewhere as a C string (though if you’re doing that, you can probably also use .withCString or just use the implicit conversion for bridged C functions.
let str = "test"
let byteArray = [UInt8](str.utf8)
swift 4
func stringToUInt8Array(){
let str:String = "Swift 4"
let strToUInt8:[UInt8] = [UInt8](str.utf8)
print(strToUInt8)
}
I came to this question looking for how to convert to a Int8 array. This is how I'm doing it, but surely there's a less loopy way:
Method on an Extension for String
public func int8Array() -> [Int8] {
var retVal : [Int8] = []
for thing in self.utf16 {
retVal.append(Int8(thing))
}
return retVal
}
Note: storing a UTF-16 encoded character (2 bytes) in an Int8 (1 byte) will lead to information loss.