Adding a string from UserDefaults into an already made array Swift 3 - arrays

I've got my users first name and I've set it in a UserDefault and I call it like so..
let firstName = UserDefaults.standard.object(forKey: "firstName")
Then I have an array of strings and I would like to add the users first name into that..
var arrayOfTitle = ["HEY", "FIND EVENTS CLOSE TO YOU", "BOOK"]
I've tried what I would think it should look like which is
var arrayOfTitle = ["HEY \(firstName)", "FIND EVENTS CLOSE TO YOU", "BOOK"]
but that isn't working.
Would anyone be able to push me or demonstrate to get me in the right direction.
Thanks!

UserDefaults.string(forKey:)
Use UserDefaults.string(forKey:) instead of UserDefaults.object(forKey:).
let firstName = UserDefaults.standard.string(forKey: "firstName") ?? "YOU"
var arrayOfTitle = ["HEY \(firstName)", "FIND EVENTS CLOSE TO YOU", "BOOK"]
UserDefaults.standard.object(forKey:) returns Any? which you must unwrap and convert to a string. UserDefaults.standard.string(forKey:) converts the result to String? which can simplify your code.
The nil-coalescing operator, ??, unwraps the String? result if it contains a value, or returns the default value "YOU" if the result is nil. Without the ?? operator, if there is not a UserDefault stored for "firstName", it will return nil resulting in "HEY nil".
Optional Binding
You can use optional binding with UserDefaults.string(forKey:) if you want to conditionally run code if a value exists or not.
if let firstName = UserDefaults.standard.string(forKey: "firstName") {
print("\(firstName)")
}

if let name = UserDefaults.standard.object(forKey: "firstName") as? String{
arrayOfTitle.append(name)
}

Related

Swift Can't access Single object array

I am trying to access data from a json file. The problem is that some of the values are NSSingleObjectArrays (Arrays with only item) which I can't turn into strings.
class CarObject {
var pictureURL: String!
var carURL: String!
var carPrice: String!
required init(json: [String: AnyObject]) {
pictureURL = json["galleryURL"] as! String
carURL = json["viewItemURL"] as! String
carPrice = json["currentPrice"] as! String
}
}
I get the following error message:
Could not cast value of type '__NSSingleObjectArrayI' (0x10a2ec548) to 'NSString' (0x109729440).
I tried to access them like this:
"json["galleryURL"][0] as String!"
but I get the following error:
Type 'Any?' has no subscript members
The values look like this:
galleryURL = ("one value");
Do you guys know a way how to access them easily?
Thanks!
Just cast things to the appropriate types first. It sounds like your values are arrays containing a single string, so something like this:
var pictureURL: URL
required init?(json: [String: AnyObject]) {
guard let pictureURLString = (json["galleryURL"] as? [String])?.first,
let pictureURL = URLComponents(string: pictureURLString)?.url else {
return nil
}
self.pictureURL = pictureURL
}
Also, you may want to reconsider the types you're using for your properties. The pictureURL and carURL properties are URLs, so they make more sense typed as URL. The carPrice property is likely numeric, so it makes more sense as a Double.

How to Get Value from Array to Variable Swift

I have a Questions
I want to move Value in array to Variable
ex.
[1,2,3] = array
i want to get "1" to Variable
Var = 1 <= Which "1" is Value in array
My code :
//Loop For Seach Value
for result in 0...DataSearch.count-1 {
let Object = DataSearch[result] as! [String:AnyObject];
self.IDMachine_Array.append(Object["IDMac"] as! String!);
self.Password_Array.append(Object["password"] as! String!);
self.Conpassword_Array.append(Object["password_con"] as! String!);
self.Tel_Array.append(Object["Tel"] as! String!);
self.Email_Array.append(Object["Email"] as! String!);
self.Email = String(self.Email_Array);
}
I try Value Email = Email_Array
Result print :
[xxxx#xxxx.com]
but i want Result is :
xxxx#xxxx.com -> without []
Please Help me please.
Thank you.
Sorry if my solution is wrong.
Just get the first element from the array?
self.Email = self.EmailArray.first!
(this is the same as self.Email = self.EmailArray[0])
NB: first! or [0] will both crash if the array is empty. The original question uses as! so obviously just need this to work. However, if you wanted safety you would use something like
if let email as self.EmailArray.first {
self.Email = email
}
or
self.Email = self.EmailArray.first ?? "no email found"

"hasPrefix" not working in Swift

I have an array of dictionary & I try to filter with prefix from using one of the key as follow:
let b = [["id":1,"name":"India"],["id":2,"name":"america"],["id":3,"name":"africa"],["id":4,"name":"indonesia"],["id":5,"name":"jakarta"],["id":6,"rec_name":"Zimba"]]
let g = b.filter({String(describing: $0["name"]).hasPrefix("I")})
print(g) //retun Empty array
If I try with contains then it working fine
or
If I try with only pure String array then also it working fine
Thank you,
Since your array (b) contains dictionaries where name is not always present (you have an object with rec_name), you could modify your filter to something like this:
let g = b.filter {
guard let name = $0["name"] as? String else { return false }
return name.hasPrefix("I")
}
and thus making sure that only dictionaries with a value for that key are matched by your filter
Fun fact: The reason why the original code doesn't work (as Martin points out) is pretty obvious when we do something like this:
let g = b.map({String(describing: $0["name"])})
print(g)
Which prints:
["Optional(\"India\")", "Optional(\"america\")", "Optional(\"africa\")", "Optional(\"indonesia\")", "Optional(\"jakarta\")", "nil"]
Please check with this.
let b = [["id":1,"name":"India"],["id":2,"name":"america"],["id":3,"name":"africa"],["id":4,"name":"indonesia"],["id":5,"name":"jakarta"],["id":6,"rec_name":"Zimba"]]
let g = b.filter({String(describing: $0["name"] as? String ?? "").hasPrefix("I")})
print(g)
Try this code you'll get the proper solution.
let b = [["id":1,"name":"India"],["id":2,"name":"america"],
["id":3,"name":"africa"],["id":4,"name":"indonesia"],["id":5,"name":"jakarta"],
["id":6,"rec_name":"Zimba"]]
let g = b.filter({($0["name"] as? String ?? "").hasPrefix("I")})
print(g)

Swift: Accessing array value in array of dictionaries

I am currently struggling with obtaining a value from an array inside an array of dictionaries. Basically I want to grab the first "[0]" from an array stored inside an array of dictionaries. This is basically what I have:
var array = [[String:Any]]()
var hobbies:[String] = []
var dict = [String:Any]()
viewDidLoad Code:
dict["Name"] = "Andreas"
hobbies.append("Football", "Programming")
dict["Hobbies"] = hobbies
array.append(dict)
/// - However, I can only display the name, with the following code:
var name = array[0]["Name"] as! String
But I want to be able to display the first value in the array stored with the name, as well. How is this possible?
And yes; I know there's other options for this approach, but these values are coming from Firebase (child paths) - but I just need to find a way to display the array inside the array of dictionaries.
Thanks in advance.
If you know "Hobbies" is a valid key and its dictionary value is an array of String, then you can directly access the first item in that array with:
let hobby = (array[0]["Hobbies"] as! [String])[0]
but this will crash if "Hobbies" isn't a valid key or if the value isn't [String].
A safer way to access the array would be:
if let hobbies = array[0]["Hobbies"] as? [String] {
print(hobbies[0])
}
If you use a model class/struct things get easier
Given this model struct
struct Person {
let name: String
var hobbies: [String]
}
And this dictionary
var persons = [String:Person]()
This is how you put a person into the dictionary
let andreas = Person(name: "Andreas", hobbies: ["Football", "Programming"])
persons[andreas.name] = Andreas
And this is how you do retrieve it
let aPerson = persons["Andreas"]

Convert [String]? to String in Swift

For my project, I extracted tweets from a CSV file in Swift. Problem is now all tweets are parsed as one element in an array, separated by ",".
let tweetsOfColumns = columns["tweet"]
let seperatedColumns = tweetsOfColumns.componentsSeparatedByString(",")
Error message: '[String]?' does not have a member named
'componentsSeparatedByString'.
I checked if tweetsOfColumns contains multiple elements, but it doesn't allow me to subscript with tweetsOfColumns[index].
Looking at the link you reference, columns["tweets"] is going to give you back an array of the values from the "tweets" column, so it's what you need already, there's no additional comma's to split things on, you just need:
let seperatedColumns = columns["tweet"]
to have an array containing the tweet column for each row.
When you try to get an element from a dictionary, like
columns["tweet"]
it will give you back an optional, because if there is nothing associated with the key, it gives you back nil (None), otherwise the value wrapped in an optional (Some(data)).
So you have to unwrap the optional for example:
columns["tweet"]!
You have to either use the optional ? to access the string:
let seperatedColumns = tweetsOfColumns?.componentsSeparatedByString(",")
But you should unwrap it:
if let unwrappedTweets = tweetsOfColumns?.componentsSeparatedByString(","){
let seperatedColumns = unwrappedTweets
}
The problem is probably that you'll get an optional back, which you have to unwrap. And the easiest and most elegant is to use the if-let unwrapper.
if let tweetsOfColumns = columns["tweet"] {
let seperatedColumns = tweetsOfColumns.componentsSeparatedByString(",")
// do something with the seperatedColumns
}
Based on David's question and the OP's response in the OP comments, you can use map on the Array returned by columns["tweet"]. Please post actual data/code in the future.
let columns = [
"tweet":["handleX,tag1,tag2,textA,textB",
"handleY,tag1,tag2,textC,textD"]]
var chunk = [[String]]()
if columns["tweet"] != nil {
chunk = columns["tweet"]!.map {
return $0.componentsSeparatedByString(",")
}
}

Resources