Ordered Map in Swift

Ordered map in Swift

You can order them by having keys with type Int.

var myDictionary: [Int: [String: String]]?

or

var myDictionary: [Int: (String, String)]?

I recommend the first one since it is a more common format (JSON for example).

Sorted Array/Map Swift

Simply sort your array:

let var_to_sort = data.sorted {
$0.score?.number ?? 0 > $1.score?.number ?? 0
}

In what order when add item to map in swift?

The existing answers are highly likely to be confusing depending on what sort of programming background you come from.

var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"

Given that code snippet, the type of occupations is a Swift Dictionary. As the other answers point out, a dictionary, in Swift, is a collection of key-value pairs.

Other languages have a similar data structure, but may refer to it by a different name.

  • C++'s map type
  • .NET's Hashtable type
  • Java's HashMap type
  • Objective-C's NSDictionary type

The list could go on. But these all represent roughly the same data structure: a store of key & value pairs.

In Swift, dictionaries do not have an order. Any perceived ordering you notice from printing or iterating over items in a dictionary is just that--perceived. It should not be relied on.

If you need an ordered dictionary, you will need to implement it on your own. Although I'm sure someone has probably already implemented it and you can find it on github. A very simple implementation for an ordered pairs of data could simply involve an array of tuples, but you wouldn't be able to do the same key look up you can with dictionaries.

What is important here is that there is no defined order for data in a Swift dictionary, so any perceived ordering that is happening should not be relied on.

Order of array returned by map

Yes, and here's your source.

"After applying the provided closure to each array element, the map(_:) method returns a new array containing all of the new mapped values, in the same order as their corresponding values in the original array."

What is the best way to use map and sorted together in Swift

You can use flatMap(_:) with replacingOccurrences(of:with:) to ignore the nil result while converting string to number and then sort the result array.

let array = ["1,8", "3,5", "2,5", "4"]
let sortedArray = array.flatMap({ Double($0.replacingOccurrences(of: ",", with: ".")) }).sorted()
print(sortedArray) //[1.8, 2.5, 3.5, 4.0]

Note: If your Swift version is 4.1 or greater than use compactMap(_:) because flatMap is deprecated in Swift 4.1.

let sortedArray = array.compactMap({ Double($0.replacingOccurrences(of: ",", with: ".")) }).sorted()

Swift array map without $0 (Higher-Order Functions )

map transforms each element from its type to other so that the transformation requires the parameter in the closure. But for convenience you can omit this parameter by making extensions for Range and ClosedRange:

extension Range where Bound: Strideable, Bound.Stride: SignedInteger {
public func map<T>(_ transform: () -> T) -> [T] {
map { _ in transform() }
}
}

extension ClosedRange where Bound: Strideable, Bound.Stride: SignedInteger {
public func map<T>(_ transform: () -> T) -> [T] {
map { _ in transform() }
}
}

let range = (0..<10).map { arc4random() }
print(range)
// Outputs: [676946806, 482060909, 1553829324, 1660236508, 606395000, 268649066, 1438948568, 1995527535, 918698113, 505678702]

let closedRange = (0...9).map { arc4random() }
print(closedRange)
// Outputs: [20467139, 198204705, 1585520963, 2022302907, 2518334206, 3304761403, 3782378335, 3830286797, 2200585433, 2387902936]

map high order function format in swift

You are using the following Dictionary initializer:

init<S>(_ keysAndValues: S, uniquingKeysWith combine: (Dictionary<Key, Value>.Value, Dictionary<Key, Value>.Value) throws -> Dictionary<Key, Value>.Value) rethrows where S : Sequence, S.Element == (Key, Value)

Note that S is a sequence where its elements are a tuple of key/value pairs.

When you pass nums1.map{ ($0, 1) } to the first parameter, you are creating an array of key/value tuples from nums1.

It fails when you use nums2.map{ $0, 1 } because that is missing the parentheses for the tuple.

Keep in mind that nums1.map{ ($0, 1) } is shorthand for nums1.map({ ($0, 1) }). That's all related to trailing closures which has nothing to do with the parentheses for the tuple that appear inside the { }.

Sort dictionary by keys in Swift

Dictionary already has a sorted method that takes a closure that defines the sorting function. You can sort by keys in the closure, then simply map over the resulting tuples to get the values only.

let sortedDictKeys = dict.sorted(by: { $0.key < $1.key }).map(\.value)

Swift Map Sorted Closure

Because sort method is func sorted(by:). So you have to add by
param name:

numbers.sorted(by: {(n1:Int, n2:Int) -> Bool in return n1 < n2})

What's the cleanest way of applying map() to a dictionary in Swift?

Swift 4+

Good news! Swift 4 includes a mapValues(_:) method which constructs a copy of a dictionary with the same keys, but different values. It also includes a filter(_:) overload which returns a Dictionary, and init(uniqueKeysWithValues:) and init(_:uniquingKeysWith:) initializers to create a Dictionary from an arbitrary sequence of tuples. That means that, if you want to change both the keys and values, you can say something like:

let newDict = Dictionary(uniqueKeysWithValues:
oldDict.map { key, value in (key.uppercased(), value.lowercased()) })

There are also new APIs for merging dictionaries together, substituting a default value for missing elements, grouping values (converting a collection into a dictionary of arrays, keyed by the result of mapping the collection over some function), and more.

During discussion of the proposal, SE-0165, that introduced these features, I brought up this Stack Overflow answer several times, and I think the sheer number of upvotes helped demonstrate the demand. So thanks for your help making Swift better!



Related Topics



Leave a reply



Submit