insert array values into an empty dictionary [closed] - swift

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have an array = [14, 1087, 28474]. how am I suppose to make it like [fantasy, action, animation] where 14 = fantasy , 1087 = action and so on. I want to show only the string representation of those value to my ios label. Is there any way i can do that. Should I make an empty dictionary and if so then how am i suppose to generate the keys for those values inside the arrays

You haven't said what you have already tried, but a dictionary is probably the way to go. If you make the dictionary a var, you can add to it later. If you don't need to change it, define it as let as #Leo suggests
var dict : [Int : String] = [
14 : "fantasy",
1087 : "action",
28474 : "animation"
]
let thisNumber = 1087
let thisString = dict[thisNumber]

You can create a dictionary literal if your final goal is just to have a mapping from known numbers to known genres.
let dictionary = [14: "fantasy", 1087: "action", 28474: "animation"]
if you need to build the dictionary and add to it at run time you can loop through the array and add values to the dictionary with this syntax:
dictionary[22] = "genre"

Related

Round Double value in swift with addition before decimal [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
i have double value 70514.94971385633, now I want it to round the value and make it 70515.00. I have tried command rounded(), but it only rounds value after the decimal. How I can round value after the decimal and add the nearest value to a number before decimal? this is my code for rounding the value,
let totalBidValue = self.minBid / usdToAED!
let roundedValue = totalBidValue.rounded()
but it shows result 70514.95, i want it to add it before decimal value like 70515.00
Just small change in your code
let totalBidValue = self.minBid / usdToAED!
let roundedValue = totalBidValue.round()
or
let roundedValue = totalBidValue.rounded(.up)
Use ceil(_:) to get that working,
let value = 70514.94971385633
let result = ceil(value)
print(result) //70515.0
Use round()
let myDoubleValue = 70514.94971385633
let roundedOffValue = round(myDoubleValue)
print(roundedOffValue) // 70515.0
Your code is almost perfect...
let totalBidValue = self.minBid / usdToAED!
let roundedValue = totalBidValue.rounded(.toNearestOrAwayFromZero)
just add .toNearestOrAwayFromZero in your code

Display only some digits of an Int [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Let's say you have an Int.
let int = 12345
I want it to only display some of the digits.
For example: print(firstTwoDigits) --> 12
How do I do this and thank you in advance.
It depends on your specific requirements.
This prints the first two digits of an integer number
let intVal = 12345
print(String(intVal).prefix(2))
Output: 12
Another way which only prints certain ones in the number:
let intVal = 12345
let acceptableValues = ["1", "2"]
let result = String(intVal).filter {
acceptableValues.contains(String($0))
}
print(result)
Output: 12

Swift 3 - matching user input with dictionary values [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
The user of my app will be tested on their english. They will select different words from a list by placing a check mark next to the word. They will want to ONLY select the words that are nouns. If, for example, they choose 5 out of 10 correctly, how do I show them a score of 50%. I think that I need to filter dictionary values based on the user's input. The user's input being an array. What is the best way to code this?
Try the following code:
let myDictionary : [String : Any] =
[ "Nouns":["One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten"],
"Verbs":["Eat","play","dance","walk","run","sing","read","write","go","come"]]
var myUserSelectedArray:[String] = ["One","come","Three","go","Five","x","Six","x","x","Ten"];
let myNounArray = myDictionary["Nouns"] as? [String];
let myVerbArray = myDictionary["Verbs"] as? [String];
let set1:Set<String> = Set(myUserSelectedArray);
let set2:Set<String> = Set(myNounArray!);
let set3:Set<String> = Set(myVerbArray!);
let scroeInNoun = set1.intersection(set2).count;
let scroeInVerb = set1.intersection(set3).count;
print ("score in Verb \((scroeInVerb * 100)/set2.count) %")
print ("score in noun \((scroeInNoun * 10)/set3.count ) %")
let finalScore = (scroeInNoun + scroeInVerb) * 100 / ((myNounArray?.count)! + (myVerbArray?.count)!)
print ("final score in noun \(finalScore) %")

Why use variadic parameters [duplicate]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I am struggling to see if there is an obvious advantage over which method to use when passing values into a function. My code below may not be the best example to explain the decision I'm trying to make, but it is, in my opinion, the easiest to understand.
Variadic Parameter Approach
func arithmeticMean(numbers: Double...) -> Double {
var total: Double = 0
for value in numbers {
total += value
}
return total / Double(numbers.count)
}
arithmeticMean(5, 10, 15)
Array Parameter Approach
func arithmeticMean(numbers: [Double]) -> Double {
var total: Double = 0
for value in numbers {
total += value
}
return total / Double(numbers.count)
}
arithmeticMean([5, 10, 15])
Is either of the two techniques preferred? If so, why (speed, reliability or just ease of reading)? Thanks.
I think there is no speed difference.Because,inside the function,you use Variadic Parameter just as Array.
I think that if the parameters count is small,for example,less than 5,Variadic Parameter may be a better solution,because it is easy to read.
If the count of parameters is large. Array is better solution.
Also know that,Variadic Parameter have some limitation:
A function may have at most one variadic parameter, and it must always appear last in the parameter list, to avoid ambiguity when calling the function with multiple parameters.
If your function has one or more parameters with a default value, and also has a variadic parameter, place the variadic parameter after all the defaulted parameters at the very end of the list.
Just from my idea.Hopes helpful

Cannot assign sorted array to a variable in Swift [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm trying to sort one array and assign it to the other. Both arrays are identically defined like so:
var arrayA: [String: [Int]] = [:]
var sortedArrayA:[String: [Int]] = [:]
sortedArrayA = arrayA.sort{ $0.0 < $1.0 } // error on this line.
I am gettin this error:
Cannot assign value of type [(String, [Int])] to type [String : [Int]]
What I'm trying to achieve is to make this dictionary:
["c" : [1,2,3], "a" : [2,3,3], "b" : [4,4,4]]
sorted like this:
["a" : [2,3,3], "b" : [4,4,4], "c" : [1,2,3]]
If it makes sence.
Yeah, I know closures in Swift are cool. But they are not cool enough to infer that you want to sort an array from this code:
var arrayA: [Int] = []
var sortedArrayA:[Int] = []
sortedArrayA = arrayA{ $0 < $1 }
And your code is even worse! You didn't even declare arrays! What you declared are dictionaries which are supposed to not be sorted!
Anyway, just learn the syntax of arrays: it's a pair of square brackets surrounding the type of array you want. So an array of Ints will be [Int] and an array of Strings will be [String].
Got it? Cool.
"But I only have dictionaries, though..." you said sadly. If you only have dictionaries, you can either sort its keys or values. I think you probably need to sort the values.
let values = someDictionary.values // if you want to sort keys, use .keys instead
Now you need to actually call the sort method in order to sort. Just writing a closure is not going to work.
let sortedValues = values.sort(<)
You can do this with any arrays of course!
let array = [3, 2, 1]
let sortedArray = array.sort(<)
In your question you say that you use array but actually you are using dictionaries. And your syntax for this is wrong. you can declare empty dictionary like this: var dictionary: [String:Int] = (). But to answer your real question you can achieve it like this:
let arrayA = ["c" : [1,2,3], "a" : [2,3,3], "b" : [4,4,4]]
let sortedDict = arrayA.sort { $0.0 < $1.0 }
print("\(sortedDict)")
Try and figure out the array sorting in Playground, in swift you can just use .sort() to sort the array. For example, for array of integers:
var array = [Int]() //initial empty array
array = [2, 1, 4, 3]
array = array.sort() // array is now sorted