Related
I have created an Array of Dictionaries:
let tempArray = [["id":"1","Name":"ABC"],["id":"2","Name":"qwe"],["id":"3","Name":"rty"],["id":"4","Name":"uio"]]
Now I have to create an array of Name only.
What I have done is this:
var nameArray = [String]()
for dataDict in tempArray {
nameArray.append(dataDict["Name"]!)
}
But is there any other efficient way of doing this.
You can use flatMap (not map) for this, because flatMap can filter out nil values (case when dict doesn't have value for key "Name"), i.e. the names array will be defined as [String] instead of [String?]:
let tempArray = [["id":"1","Name":"ABC"],["id":"2","Name":"qwe"],["id":"3","Name":"rty"],["id":"4","Name":"uio"]]
let names = tempArray.flatMap({ $0["Name"] })
print(names) // ["ABC", "qwe", "rty", "uio"]
Use compactMap as flatMap is deprecated.
let tempArray = [["id":"1","Name":"ABC"],["id":"2","Name":"qwe"],["id":"3","Name":"rty"],["id":"4","Name":"uio"]]
let name = tempArray.compactMap({ $0["Name"]})
print(name)
I want to make this type of result :
{"":[["someId","someName"]]}
I m trying to make like this :
var fields:[AnyObject] = [AnyObject]()
for someId:String in Preferences.getAllIds(){
let someName = Preferences.getAllNames(someId)
let value = String(format: "%#,%#", someId,someName)
var field:[String] = [String]()
field.append(value)
fields.append(field as AnyObject)
}
let dict = ["": fields]
Output i m getting is:
{"":[["012345,test_name"]]}
AS you can see : there are double duotes before 012345 and after test_name
"012345,test_name"
But I want to add at start and end on both sides of the strings.
Like : "012345","test_name"
I have tried to achieve required output by this trick but failed unfortunately (don't know why this doesn't work) ... :(
value1 = value.replacingOccurrences(of: ",", with: "\",\"")
you need to define it's array like this, Hope it will help you
var fields:[[String]] = [[String]]()
for someId:String in Preferences.getAllIds(){
let someName = Preferences.getAllNames(someId)
var arrValue : [String] = [String]()
arrValue.append(someId)
arrValue.append(someName)// ["someid","somename"]
fields.append(arrValue as [String]) // [["someid","somename"]]
}
let dict = ["": fields] // {"" : [["someid","somename"]]}
if you have static value Then you can make array like this
let arrValue : [String] = ["\(someId!)","\(someName!)"]
I'm really confused with regards to how we create an empty array in Swift. Could you please show me the different ways we have to create an empty array with some detail?
Here you go:
var yourArray = [String]()
The above also works for other types and not just strings. It's just an example.
Adding Values to It
I presume you'll eventually want to add a value to it!
yourArray.append("String Value")
Or
let someString = "You can also pass a string variable, like this!"
yourArray.append(someString)
Add by Inserting
Once you have a few values, you can insert new values instead of appending. For example, if you wanted to insert new objects at the beginning of the array (instead of appending them to the end):
yourArray.insert("Hey, I'm first!", atIndex: 0)
Or you can use variables to make your insert more flexible:
let lineCutter = "I'm going to be first soon."
let positionToInsertAt = 0
yourArray.insert(lineCutter, atIndex: positionToInsertAt)
You May Eventually Want to Remove Some Stuff
var yourOtherArray = ["MonkeysRule", "RemoveMe", "SwiftRules"]
yourOtherArray.remove(at: 1)
The above works great when you know where in the array the value is (that is, when you know its index value). As the index values begin at 0, the second entry will be at index 1.
Removing Values Without Knowing the Index
But what if you don't? What if yourOtherArray has hundreds of values and all you know is you want to remove the one equal to "RemoveMe"?
if let indexValue = yourOtherArray.index(of: "RemoveMe") {
yourOtherArray.remove(at: indexValue)
}
This should get you started!
There are four ways to create a empty array in Swift 5 and shorthand syntax way is always preferred.
Method 1: Shorthand Syntax
var arr = [Int]()
Method 2: Array Initializer
var arr = Array<Int>()
Method 3: Array with an Array Literal
var arr:[Int] = []
Method 4: Credit goes to #BallpointBen
var arr:Array<Int> = []
var myArr1 = [AnyObject]()
can store any object
var myArr2 = [String]()
can store only string
You could use
var firstNames: [String] = []
There are 2 major ways to create/intialize an array in swift.
var myArray = [Double]()
This would create an array of Doubles.
var myDoubles = [Double](count: 5, repeatedValue: 2.0)
This would create an array of 5 doubles, all initialized with the value of 2.0.
If you want to declare an empty array of string type you can do that in 5 different way:-
var myArray: Array<String> = Array()
var myArray = [String]()
var myArray: [String] = []
var myArray = Array<String>()
var myArray:Array<String> = []
Array of any type :-
var myArray: Array<AnyObject> = Array()
var myArray = [AnyObject]()
var myArray: [AnyObject] = []
var myArray = Array<AnyObject>()
var myArray:Array<AnyObject> = []
Array of Integer type :-
var myArray: Array<Int> = Array()
var myArray = [Int]()
var myArray: [Int] = []
var myArray = Array<Int>()
var myArray:Array<Int> = []
Here are some common tasks in Swift 4 you can use as a reference until you get used to things.
let emptyArray = [String]()
let emptyDouble: [Double] = []
let preLoadArray = Array(repeating: 0, count: 10) // initializes array with 10 default values of the number 0
let arrayMix = [1, "two", 3] as [Any]
var arrayNum = [1, 2, 3]
var array = ["1", "two", "3"]
array[1] = "2"
array.append("4")
array += ["5", "6"]
array.insert("0", at: 0)
array[0] = "Zero"
array.insert(contentsOf: ["-3", "-2", "-1"], at: 0)
array.remove(at: 0)
array.removeLast()
array = ["Replaces all indexes with this"]
array.removeAll()
for item in arrayMix {
print(item)
}
for (index, element) in array.enumerated() {
print(index)
print(element)
}
for (index, _) in arrayNum.enumerated().reversed() {
arrayNum.remove(at: index)
}
let words = "these words will be objects in an array".components(separatedBy: " ")
print(words[1])
var names = ["Jemima", "Peter", "David", "Kelly", "Isabella", "Adam"]
names.sort() // sorts names in alphabetical order
let nums = [1, 1234, 12, 123, 0, 999]
print(nums.sorted()) // sorts numbers from lowest to highest
Array in swift is written as **Array < Element > **, where Element is the type of values the array is allowed to store.
Array can be initialized as :
let emptyArray = [String]()
It shows that its an array of type string
The type of the emptyArray variable is inferred to be [String] from the type of the initializer.
For Creating the array of type string with elements
var groceryList: [String] = ["Eggs", "Milk"]
groceryList has been initialized with two items
The groceryList variable is declared as “an array of string values”, written as [String].
This particular array has specified a value type of String, it is allowed to store String values only.
There are various properities of array like :
- To check if array has elements (If array is empty or not)
isEmpty property( Boolean ) for checking whether the count property is equal to 0:
if groceryList.isEmpty {
print("The groceryList list is empty.")
} else {
print("The groceryList is not empty.")
}
- Appending(adding) elements in array
You can add a new item to the end of an array by calling the array’s append(_:) method:
groceryList.append("Flour")
groceryList now contains 3 items.
Alternatively, append an array of one or more compatible items with the addition assignment operator (+=):
groceryList += ["Baking Powder"]
groceryList now contains 4 items
groceryList += ["Chocolate Spread", "Cheese", "Peanut Butter"]
groceryList now contains 7 items
As per Swift 5
// An array of 'Int' elements
let oddNumbers = [1, 3, 5, 7, 9, 11, 13, 15]
// An array of 'String' elements
let streets = ["Albemarle", "Brandywine", "Chesapeake"]
// Shortened forms are preferred
var emptyDoubles: [Double] = []
// The full type name is also allowed
var emptyFloats: Array<Float> = Array()
you can remove the array content with passing the array index or you can remove all
var array = [String]()
print(array)
array.append("MY NAME")
print(array)
array.removeFirst()
print(array)
array.append("MY NAME")
array.removeLast()
array.append("MY NAME1")
array.append("MY NAME2")
print(array)
array.removeAll()
print(array)
Swift 5
// Create an empty array
var emptyArray = [String]()
// Add values to array by appending (Adds values as the last element)
emptyArray.append("Apple")
emptyArray.append("Oppo")
// Add values to array by inserting (Adds to a specified position of the list)
emptyArray.insert("Samsung", at: 0)
// Remove elements from an array by index number
emptyArray.remove(at: 2)
// Remove elements by specifying the element
if let removeElement = emptyArray.firstIndex(of: "Samsung") {
emptyArray.remove(at: removeElement)
}
A similar answer is given but that doesn't work for the latest version of Swift (Swift 5), so here is the updated answer. Hope it helps! :)
Initiating an array with a predefined count:
Array(repeating: 0, count: 10)
I often use this for mapping statements where I need a specified number of mock objects. For example,
let myObjects: [MyObject] = Array(repeating: 0, count: 10).map { _ in return MyObject() }
Compatible with: Xcode 6.0.1+
You can create an empty array by specifying the Element type of your array in the declaration.
For example:
// Shortened forms are preferred
var emptyDoubles: [Double] = []
// The full type name is also allowed
var emptyFloats: Array<Float> = Array()
Example from the apple developer page (Array):
Hope this helps anyone stumbling onto this page.
Swift 5 version:
let myArray1: [String] = []
let myArray2: [String] = [String]()
let myArray3 = [String]()
let myArray4: Array<String> = Array()
Or more elegant way:
let myElegantArray1: [String] = .init()
extension Array {
static func empty() -> Self {
return []
}
}
let myElegantArray2: [String] = .empty()
The extension above, you can use for any type Array
I have created a dictionary like
var tempArray1 = ["sdds","dsads"]
var tempArray2: AnyObject = ["sddsa",34,tempArray1]
var dictionary: [String:Array] = ["key1":["value1"],"key2":["value2",6,tempArray2]]
The application crashed when I tried to print all values from the dictionary like
let allValues = [Array](dictionary.values)
for value in allValues{
println(value)
}
I just started learning dictionary concept in swift language. I want to know my approach is right or wrong.
Please help me to figure it out
As Swift arrays have associated I don't think that you can declare type with array without specifying its associated type. I am not sure why you do not get compile time errors. This should work:
var tempArray1 = ["sdds","dsads"]
var tempArray2: AnyObject = ["sddsa",34,tempArray1]
var dictionary: [String:Array<AnyObject>] = ["key1":["value1"],"key2":["value2",6,tempArray2]]
let allValues = [Array<AnyObject>](dictionary.values)
for value in allValues{
println(value)
}
Or even shorter:
var tempArray1 = ["sdds","dsads"]
var tempArray2: AnyObject = ["sddsa",34,tempArray1]
var dictionary: [String:[AnyObject]] = ["key1":["value1"],"key2":["value2",6,tempArray2]]
let allValues = dictionary.values
for value in allValues{
println(value)
}
You can try this also
var tempArray1 = ["sdds","dsads"]
var tempArray2: AnyObject = ["sddsa",34,tempArray1]
println("Array inside array \(tempArray2)")
var dictionary: [String:Array] = ["key1":["value1"],"key2":["value2",6,tempArray2]]
println(dictionary)
let allValues = Array(dictionary.values)
for value in allValues{
println(value)
}
Trying to fill an array with strings from the keys in a dictionary in swift.
var componentArray: [String]
let dict = NSDictionary(contentsOfFile: NSBundle.mainBundle().pathForResource("Components", ofType: "plist")!)
componentArray = dict.allKeys
This returns an error of: 'AnyObject' not identical to string
Also tried
componentArray = dict.allKeys as String
but get: 'String' is not convertible to [String]
Swift 3 & Swift 4
componentArray = Array(dict.keys) // for Dictionary
componentArray = dict.allKeys // for NSDictionary
With Swift 3, Dictionary has a keys property. keys has the following declaration:
var keys: LazyMapCollection<Dictionary<Key, Value>, Key> { get }
A collection containing just the keys of the dictionary.
Note that LazyMapCollection that can easily be mapped to an Array with Array's init(_:) initializer.
From NSDictionary to [String]
The following iOS AppDelegate class snippet shows how to get an array of strings ([String]) using keys property from a NSDictionary:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let string = Bundle.main.path(forResource: "Components", ofType: "plist")!
if let dict = NSDictionary(contentsOfFile: string) as? [String : Int] {
let lazyMapCollection = dict.keys
let componentArray = Array(lazyMapCollection)
print(componentArray)
// prints: ["Car", "Boat"]
}
return true
}
From [String: Int] to [String]
In a more general way, the following Playground code shows how to get an array of strings ([String]) using keys property from a dictionary with string keys and integer values ([String: Int]):
let dictionary = ["Gabrielle": 49, "Bree": 32, "Susan": 12, "Lynette": 7]
let lazyMapCollection = dictionary.keys
let stringArray = Array(lazyMapCollection)
print(stringArray)
// prints: ["Bree", "Susan", "Lynette", "Gabrielle"]
From [Int: String] to [String]
The following Playground code shows how to get an array of strings ([String]) using keys property from a dictionary with integer keys and string values ([Int: String]):
let dictionary = [49: "Gabrielle", 32: "Bree", 12: "Susan", 7: "Lynette"]
let lazyMapCollection = dictionary.keys
let stringArray = Array(lazyMapCollection.map { String($0) })
// let stringArray = Array(lazyMapCollection).map { String($0) } // also works
print(stringArray)
// prints: ["32", "12", "7", "49"]
Array from dictionary keys in Swift
componentArray = [String] (dict.keys)
You can use dictionary.map like this:
let myKeys: [String] = myDictionary.map{String($0.key) }
The explanation:
Map iterates through the myDictionary and accepts each key and value pair as $0. From here you can get $0.key or $0.value. Inside the trailing closure {}, you can transform each element and return that element. Since you want $0 and you want it as a string then you convert using String($0.key). You collect the transformed elements to an array of strings.
dict.allKeys is not a String. It is a [String], exactly as the error message tells you (assuming, of course, that the keys are all strings; this is exactly what you are asserting when you say that).
So, either start by typing componentArray as [AnyObject], because that is how it is typed in the Cocoa API, or else, if you cast dict.allKeys, cast it to [String], because that is how you have typed componentArray.
extension Array {
public func toDictionary<Key: Hashable>(with selectKey: (Element) -> Key) -> [Key:Element] {
var dict = [Key:Element]()
for element in self {
dict[selectKey(element)] = element
}
return dict
}
}
dict.keys.sorted()
that gives [String]
https://developer.apple.com/documentation/swift/array/2945003-sorted
From the official Array Apple documentation:
init(_:) - Creates an array containing the elements of a sequence.
Declaration
Array.init<S>(_ s: S) where Element == S.Element, S : Sequence
Parameters
s - The sequence of elements to turn into an array.
Discussion
You can use this initializer to create an array from any other type that conforms to the Sequence protocol...You can also use this initializer to convert a complex sequence or collection type back to an array. For example, the keys property of a dictionary isn’t an array with its own storage, it’s a collection that maps its elements from the dictionary only when they’re accessed, saving the time and space needed to allocate an array. If you need to pass those keys to a method that takes an array, however, use this initializer to convert that list from its type of LazyMapCollection<Dictionary<String, Int>, Int> to a simple [String].
func cacheImagesWithNames(names: [String]) {
// custom image loading and caching
}
let namedHues: [String: Int] = ["Vermillion": 18, "Magenta": 302,
"Gold": 50, "Cerise": 320]
let colorNames = Array(namedHues.keys)
cacheImagesWithNames(colorNames)
print(colorNames)
// Prints "["Gold", "Cerise", "Magenta", "Vermillion"]"
Swift 5
var dict = ["key1":"Value1", "key2":"Value2"]
let k = dict.keys
var a: [String]()
a.append(contentsOf: k)
This works for me.
NSDictionary is Class(pass by reference)
Dictionary is Structure(pass by value)
====== Array from NSDictionary ======
NSDictionary has allKeys and allValues get properties with
type [Any].
let objesctNSDictionary =
NSDictionary.init(dictionary: ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"])
let objectArrayOfAllKeys:Array = objesctNSDictionary.allKeys
let objectArrayOfAllValues:Array = objesctNSDictionary.allValues
print(objectArrayOfAllKeys)
print(objectArrayOfAllValues)
====== Array From Dictionary ======
Apple reference for Dictionary's keys and values properties.
let objectDictionary:Dictionary =
["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
let objectArrayOfAllKeys:Array = Array(objectDictionary.keys)
let objectArrayOfAllValues:Array = Array(objectDictionary.values)
print(objectArrayOfAllKeys)
print(objectArrayOfAllValues)
This answer will be for swift dictionary w/ String keys. Like this one below.
let dict: [String: Int] = ["hey": 1, "yo": 2, "sup": 3, "hello": 4, "whassup": 5]
Here's the extension I'll use.
extension Dictionary {
func allKeys() -> [String] {
guard self.keys.first is String else {
debugPrint("This function will not return other hashable types. (Only strings)")
return []
}
return self.flatMap { (anEntry) -> String? in
guard let temp = anEntry.key as? String else { return nil }
return temp }
}
}
And I'll get all the keys later using this.
let componentsArray = dict.allKeys()
// Old version (for history)
let keys = dictionary.keys.map { $0 }
let keys = dictionary?.keys.map { $0 } ?? [T]()
// New more explained version for our ducks
extension Dictionary {
var allKeys: [Dictionary.Key] {
return self.keys.map { $0 }
}
}