Related
I have an array like this, and I need to multiply a number if it is 3, but in the end reduce eliminates all numbers equal to 3, and multiplies the rest. How do I fix this ?
let arr = [2, 4, 3, 1, 4, 3, 1, 3, 10, 4, 2, 13]
let aaa = arr.reduce([]) { $1 == 3 ? $0 : $0 + [$1 * 5] }
//[10, 20, 5, 20, 5, 50, 20, 10, 65]
//[2,4,15,1,4,15,1,15,10,4,2,13] need this
You should use map instead of reduce
let arr = [2, 4, 3, 1, 4, 3, 1, 3, 10, 4, 2, 13]
let result = arr.map { $0 == 3 ? 15 : $0 }
// [2, 4, 15, 1, 4, 15, 1, 15, 10, 4, 2, 13
Or if it should work for any multiple of 3
let result = arr.map { $0.isMultiple(of: 3) ? $0 * 5 : $0 }
I was given a list of apps along with their ratings:
let appRatings = [
"Calendar Pro": [1, 5, 5, 4, 2, 1, 5, 4],
"The Messenger": [5, 4, 2, 5, 4, 1, 1, 2],
"Socialise": [2, 1, 2, 2, 1, 2, 4, 2]
]
I want to write a func that takes appRating as input and return their name and average rating, like this.
["Calendar Pro": 3,
"The Messenger": 3,
"Socialise": 2]
Does anyone know how to implement such a method that it takes (name and [rating]) as input and outputs (name and avgRating ) using a closure inside the func?
This is what I have so far.
func calculate( appName: String, ratings : [Int]) -> (String, Double ) {
let avg = ratings.reduce(0,+)/ratings.count
return (appName, Double(avg))
}
Fundamentally, what you're trying to achieve is a mapping between one set of values into another. Dictionary has a function for this, Dictionary.mapValues(_:), specifically for mapping values only (keeping them under the same keys).
let appRatings = [
"Calendar Pro": [1, 5, 5, 4, 2, 1, 5, 4],
"The Messenger": [5, 4, 2, 5, 4, 1, 1, 2],
"Socialise": [2, 1, 2, 2, 1, 2, 4, 2]
]
let avgAppRatings = appRatings.mapValues { allRatings in
return computeAverage(of: allRatings) // Dummy function we'll implement later
}
So now, it's a matter of figuring out how to average all the numbers in an Array. Luckily, this is very easy:
We need to sum all the ratings
We can easily achieve this with a reduce expression. StWe'll reduce all numbers by simply adding them into the accumulator, which will start with 0
allRatings.reduce(0, { accumulator, rating in accumulator + rate })
From here, we can notice that the closure, { accumulator, rating in accumulator + rate } has type (Int, Int) -> Int, and just adds the numbers together. Well hey, that's exactly what + does! We can just use it directly:
allRatings.reduce(0, +)
We need to divide the ratings by the number of ratings
There's a catch here. In order for the average to be of any use, it can't be truncated to a mere Int. So we need both the sum and the count to be converted to Double first.
You need to guard against empty arrays, whose count will be 0, resulting in Double.infinity.
Putting it all together, we get:
let appRatings = [
"Calendar Pro": [1, 5, 5, 4, 2, 1, 5, 4],
"The Messenger": [5, 4, 2, 5, 4, 1, 1, 2],
"Socialise": [2, 1, 2, 2, 1, 2, 4, 2]
]
let avgAppRatings = appRatings.mapValues { allRatings in
if allRatings.isEmpty { return nil }
return Double(allRatings.reduce(0, +)) / Double(allRatings.count)
}
Add in some nice printing logic:
extension Dictionary {
var toDictionaryLiteralString: String {
return """
[
\t\(self.map { k, v in "\(k): \(v)" }.joined(separator: "\n\t"))
]
"""
}
}
... and boom:
print(avgAppRatings.toDictionaryLiteralString)
/* prints:
[
Socialise: 2.0
The Messenger: 3.0
Calendar Pro: 3.375
]
*/
Comments on your attempt
You had some questions as to why your attempt didn't work:
func calculate( appName: String, ratings : [Int]) -> (String: Int ) {
var avg = ratings.reduce(0,$0+$1)/ratings.count
return appName: sum/avg
}
$0+$1 isn't within a closure ({ }), as it needs to be.
appName: sum/avg isn't valid Swift.
The variable sum doesn't exist.
avg is a var variable, even though it's never mutated. It should be a let constant.
You're doing integer devision, which doesn't support decimals. You'll need to convert your sum and count into a floating point type, like Double, first.
A fixed version might look like:
func calculateAverage(of numbers: [Int]) -> Double {
let sum = Double(ratings.reduce(0, +))
let count = Double(numbers.count)
return sum / count
}
To make a function that processes your whole dictionary, incoroprating my solution above, you might write a function like:
func calculateAveragesRatings(of appRatings: [String: [Int]]) -> [String: Double?] {
return appRatings.mapValues { allRatings in
if allRatings.isEmpty { return nil }
return Double(allRatings.reduce(0, +)) / Double(allRatings.count)
}
}
This a simple solution that takes into account that a rating is an integer:
let appRatings = [
"Calendar Pro": [1, 5, 5, 4, 2, 1, 5, 4],
"The Messenger": [5, 4, 2, 5, 4, 1, 1, 2],
"Socialise": [2, 1, 2, 2, 1, 2, 4, 2]
]
let appWithAverageRating: [String: Int] = appRatings.mapValues { $0.reduce(0, +) / $0.count}
print("appWithAverageRating =", appWithAverageRating)
prints appWithAverageRating = ["The Messenger": 3, "Calendar Pro": 3, "Socialise": 2]
If you'd like to check whether an app has enough ratings before returning an average rating, then the rating would be an optional Int:
let minimumNumberOfRatings = 0 // You can change this
var appWithAverageRating: [String: Int?] = appRatings.mapValues { ratingsArray in
guard ratingsArray.count > minimumNumberOfRatings else {
return nil
}
return ratingsArray.reduce(0, +) / ratingsArray.count
}
If you'd like the ratings to go by half stars (0, 0.5, 1, ..., 4.5, 5) then we could use this extension:
extension Double {
func roundToHalf() -> Double {
let n = 1/0.5
let numberToRound = self * n
return numberToRound.rounded() / n
}
}
Then the rating will be an optional Double. Let's add an AppWithoutRatings and test our code:
let appRatings = [
"Calendar Pro": [1, 5, 5, 4, 2, 1, 5, 4],
"The Messenger": [5, 4, 2, 5, 4, 1, 1, 2],
"Socialise": [2, 1, 2, 2, 1, 2, 4, 2],
"AppWithoutRatings": []
]
let minimumNumberOfRatings = 0
var appWithAverageRating: [String: Double?] = appRatings.mapValues { ratingsArray in
guard ratingsArray.count > minimumNumberOfRatings else {
return nil
}
let rating: Double = Double(ratingsArray.reduce(0, +) / ratingsArray.count)
return rating.roundToHalf()
}
And this prints:
appWithAverageRating = ["Calendar Pro": Optional(3.0), "Socialise": Optional(2.0), "The Messenger": Optional(3.0), "AppWithoutRatings": nil]
I decided to make an Dictionary extension for this, so it is very easy to use in the future.
Here is my code I created:
extension Dictionary where Key == String, Value == [Float] {
func averageRatings() -> [String : Float] {
// Calculate average
func average(ratings: [Float]) -> Float {
return ratings.reduce(0, +) / Float(ratings.count)
}
// Go through every item in the ratings dictionary
return self.mapValues { $0.isEmpty ? 0 : average(ratings: $0) }
}
}
let appRatings: [String : [Float]] = ["Calendar Pro": [1, 5, 5, 4, 2, 1, 5, 4],
"The Messenger": [5, 4, 2, 5, 4, 1, 1, 2],
"Socialise": [2, 1, 2, 2, 1, 2, 4, 2]]
print(appRatings.averageRatings())
which will print the result of ["Calendar Pro": 3.375, "Socialise": 2.0, "The Messenger": 3.0].
Just to make the post complete another approach using reduce(into:) to avoid using a dictionary with an optional value type:
extension Dictionary where Key == String, Value: Collection, Value.Element: BinaryInteger {
var averageRatings: [String : Value.Element] {
return reduce(into: [:]) {
if !$1.value.isEmpty {
$0[$1.key] = $1.value.reduce(0,+) / Value.Element($1.value.count)
}
}
}
}
let appRatings2 = ["Calendar Pro" : [1, 5, 5, 4, 2, 1, 5, 4],
"The Messenger": [5, 4, 2, 5, 4, 1, 1, 2],
"Socialise" : [2, 1, 2, 2, 1, 2, 4, 2] ]
let keySorted = appRatings2.averageRatings.sorted(by: {$0.key<$1.key})
keySorted.map{ print($0,$1) }
Calendar Pro 3
Socialise 2
The Messenger 3
I would like to use the Array.partition(by:) to move some predefined elements from an array to the the end of it.
Example:
var my_array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
let elementsToMove = [1, 3, 4, 5, 8]
// desired result: [0, 2, 6, 7, 9, ...remaining items in any order...]
Is there an elegant way to do that? Observe that elementsToMove does not follow a pattern.
partition(by:) does not preserve the order of the elements:
var my_array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
let elementsToMove = [1, 3, 4, 5, 8]
_ = my_array.partition(by: { elementsToMove.contains($0) } )
print(my_array) // [0, 9, 2, 7, 6, 5, 4, 3, 8, 1]
A simple solution would be to filter-out and append the elements from
the second array:
let my_array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
let elementsToMove = [1, 3, 4, 5, 8]
let newArray = my_array.filter({ !elementsToMove.contains($0) }) + elementsToMove
print(newArray) // [0, 2, 6, 7, 9, 1, 3, 4, 5, 8]
For larger arrays it can be advantageous to create a set of the
to-be-moved elements first:
let my_array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
let elementsToMove = [1, 3, 4, 5, 8]
let setToMove = Set(elementsToMove)
let newArray = my_array.filter({ !setToMove.contains($0) }) + elementsToMove
print(newArray) // [0, 2, 6, 7, 9, 1, 3, 4, 5, 8]
If you have unique object in your my_array then you can try something like this.
var my_array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var tempArray = my_array //Preserve original array
let elementsToMove = [1, 3, 4, 5, 8]
let p = tempArray.partition(by: elementsToMove.contains)
//Now sort first part of tempArray on basis of your my_array to get order you want
let newArray = tempArray[0..<p].sorted(by: { my_array.index(of: $0)! < my_array.index(of: $1)! }) + tempArray[p...]
print(newArray)
Output
[0, 2, 6, 7, 9, 5, 4, 3, 8, 1]
NSMutableArray *sample;
I have an NSmutableArray, and I want to split it into chunks. I have tried checking the internet didn't find the solution for it. I got the link to split integer array.
How about this which is more Swifty?
let integerArray = [1,2,3,4,5,6,7,8,9,10]
let stringArray = ["a", "b", "c", "d", "e", "f"]
let anyObjectArray: [Any] = ["a", 1, "b", 2, "c", 3]
extension Array {
func chunks(_ chunkSize: Int) -> [[Element]] {
return stride(from: 0, to: self.count, by: chunkSize).map {
Array(self[$0..<Swift.min($0 + chunkSize, self.count)])
}
}
}
integerArray.chunks(2) //[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
stringArray.chunks(3) //[["a", "b", "c"], ["d", "e", "f"]]
anyObjectArray.chunks(2) //[["a", 1], ["b", 2], ["c", 3]]
To Convert NSMutableArray to Swift Array:
let nsarray = NSMutableArray(array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
if let swiftArray = nsarray as NSArray as? [Int] {
swiftArray.chunks(2) //[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
}
If you wanna insist to use NSArray, then:
let nsarray = NSMutableArray(array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
extension NSArray {
func chunks(_ chunkSize: Int) -> [[Element]] {
return stride(from: 0, to: self.count, by: chunkSize).map {
self.subarray(with: NSRange(location: $0, length: Swift.min(chunkSize, self.count - $0)))
}
}
}
nsarray.chunks(3) //[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
You can use the subarray method.
let array = NSArray(array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
let left = array.subarray(with: NSMakeRange(0, 5))
let right = array.subarray(with: NSMakeRange(5, 5))
I found how to convert hexa string into bytes [UInt8] but I have not found how to convert bytes [UInt8] into an hexa string in Swift
this hexstring convert to string code:
static func bytesConvertToHexstring(byte : [UInt8]) -> String {
var string = ""
for val in byte {
//getBytes(&byte, range: NSMakeRange(i, 1))
string = string + String(format: "%02X", val)
}
return string
}
samething like this result:
"F063C52A6FF7C8904D3F6E379EB85714ECA9C1CB1E8DFD6CA5D3B4A991269D60F607C565C327BD0ECC0985F74E5007E0D276499E1ADB4E0C92D8BDBB46E57705B2D5390FF5CBD4ED1B850C537301CA7E"
UInt8 array: [0, 11, 8, 15, 6, 6, 5, 8, 8, 4, 14, 14, 0, 0, 9, 12, 6, 4, 10, 6, 4, 8, 6, 2, 14, 2, 6, 13, 3, 3, 12, 4, 3, 12, 8, 13, 14, 4, 10, 1, 12, 15, 4, 0, 14, 14, 0, 8, 8, 14, 6, 15, 2, 2, 9, 15, 13, 6, 2, 6, 8, 15, 4, 2, 12, 1, 0, 13, 13, 4, 6, 0, 9, 6, 8, 2, 7, 0, 6, 1, 3, 3, 9, 15, 5, 7, 12, 8, 7, 5, 13, 14, 15, 6, 7, 6, 12, 6, 7, 7, 11, 9, 6, 0, 14, 5, 6, 14, 1, 5, 13, 10, 12, 13, 14, 2, 13, 14, 4, 7, 13, 0, 3, 10, 6, 11, 9, 12, 7, 11, 5, 3, 5, 11, 4, 9, 6, 10, 14, 0, 11, 7, 15, 9, 3, 14, 5, 1, 10, 14, 5, 6, 12, 4, 12, 14, 4, 3, 9, 8, 0]
Xcode 11 • Swift 5.1 or later
extension StringProtocol {
var hexa: [UInt8] {
var startIndex = self.startIndex
return (0..<count/2).compactMap { _ in
let endIndex = index(after: startIndex)
defer { startIndex = index(after: endIndex) }
return UInt8(self[startIndex...endIndex], radix: 16)
}
}
}
extension DataProtocol {
var data: Data { .init(self) }
var hexa: String { map { .init(format: "%02x", $0) }.joined() }
}
"0f00ff".hexa // [15, 0, 255]
"0f00ff".hexa.data // 3 bytes
"0f00ff".hexa.data.hexa // "0f00ff"
"0f00ff".hexa.data as NSData // <0f00ff>
Note: Swift 4 or 5 syntax click here
Thanks to Brian for his routine. It could conveniently be added as a Swift extension as below.
extension Array where Element == UInt8 {
func bytesToHex(spacing: String) -> String {
var hexString: String = ""
var count = self.count
for byte in self
{
hexString.append(String(format:"%02X", byte))
count = count - 1
if count > 0
{
hexString.append(spacing)
}
}
return hexString
}
}
Example of call:
let testData: [UInt8] = [15, 0, 255]
print(testData.bytesToHex(spacing: " ")) // 0F 00 FF
One liner:
testData.map{ String(format:"%02X", $0) }.joined(separator: " ")
XCode 12-beta 6.
I know its late but I use this simple routine that gives an arbitrary spacing. I converted it from Java on Android. I also have C and other language versions of this - it easy to go from language to language when you cant remember all the language-specific libraries.
public static func bytesToHex(bytes: [UInt8], spacing: String) -> String
{
var hexString: String = ""
var count = bytes.count
for byte in bytes
{
hexString.append(String(format:"%02X", byte))
count = count - 1
if count > 0
{
hexString.append(spacing)
}
}
return hexString
}
It creates a two-digit hex string with an arbitrary spacing string between elements. I use it like this, for example, to display the results of a characteristic read
let charValue = [UInt8](characteristic.value ?? Data())
print("Characteristic \(characteristic.uuid) read with value: \(Btle.bytesToHex(bytes: charValue, spacing: " "))")
with an output that looks like this:
Characteristic System ID read with value: 00 1C 05 FF FE FF E8 74
My experience with Swift and iOS is very limited; perhaps the seasoned Swift people can 'Swiftify' it.