This question already has answers here:
Dictionary error: Ambiguous reference to member '+' [duplicate]
(4 answers)
Closed 5 years ago.
teaching myself swift I am trying to understand how dictionaries work. Using playground. I have made a simple dictionary called "menu" that has a list of items with their name as keys and their price as values. Like so:
let menu = ["crisps": 2,
"oranges": 3,
"chicken": 8,
"meat": 12]
Then, I try to add the values of those items like so:
let costOfMeal = menu["crisps"]! + menu["oranges"]! + menu["chicken"]! + menu["meat"]!
This gives me the error: ambiguous reference to member '+'
not sure what's going on. Any input appreciated.
Thanks,
David
let costOfMeals = Array(menu.values).reduce(0, +)
You are trying to add up every key and value together! You should only add up the values. You know the dictionary is Key and Value, and you should only add up the Value's.
This is merely the compiler's automatic type casting getting confused by the multiple additions of unwrapped optionals.
You can help it along by adding an actual integer in the formula.
let costOfMeal = 0 + menu["crisps"]! + menu["oranges"]! + menu["meat"]! + menu["chicken"]!
Don't let it bother you as it has nothing to do with what you're trying to learn and your formula was correct (albeit not safe for production).
Related
This question already has an answer here:
Can we use keywords as parameter names in SWIFT?
(1 answer)
Closed 4 years ago.
I am a new iOS programming. I am creating a sample app which get data and set data using Firestore. For the collection contains some documents which and named those properties like extension... So in programming I need to create variable with that name extension in order to set data to Firestore but Xcode is warning me that I don't have to declare that variable name.
I have been trying to figure it out but not work. So, I decided to ask my own question if there any technique to delacre variable name which is warning by Xcode.
var `extension`: String?
var username: String?
init(`extension`: String, username: String) {
self.`extension` = `extension`
self.username = username
}
I think this will work by using ``.
I'm trying to do a very easy task, add an item to a dictionary using "append".
This is the dict:
var myDictionary: [String:Int] = [
"Apple" : 1,
"Banana" : 2,
"Strawberry" : 3
]
I've tried this
myDictionary+=["Raspberry":4]
Here I get the error message:
binary operator cannot be apllied to two operands
and also I tried:
myDictionary.append("Raspberry":4)
and
myDictionary.append[("Raspberry":4)]
as well, but I get the error that it has :
no member 'append.
What exactly is the problem, how could I add the 4th item ?
Thanks for your help
append is the wrong tool here. You just want to set the value:
myDictionary["Raspberry"] = 4
append applies to things that conform to RangeReplaceableCollection. Dictionary does not. When you insert new things into a dictionary, they are not being appended to the end. They're being inserted into the appropriate buckets (perhaps replacing things already in place). If you use append to add something, you should reasonably expect last to then return that thing, but that's not promised (or even very likely) in a dictionary. Set is similar, and also has no append.
This question already has answers here:
Swift 3: replace c style for-loop with float increment
(1 answer)
#warning: C-style for statement is deprecated and will be removed in a future version of Swift [duplicate]
(4 answers)
Closed 6 years ago.
I have search a bit online but being new to Swift, I couldn't find anything that helped me convert a for loop to the upcoming Swift version.
I have this
for var i: CGFloat = start; i <= stop; i += step {
and trying to convert to the new format but unsure how.
Can someone please help before my code stops working?
Thanks :)
for i in number.stride(through: toSecondNumber, by: withStep)
where i - name for you variable
number - start value of i
secondNumber - lastValue of range
withStep - step of iteration
you can you through to include last value or to to exclude last value
You should use 'stride' keyword.
More info about your solution.
This question already has answers here:
How to check if an element is in an array
(18 answers)
Closed 7 years ago.
Swift 2 - so, I have an array and a uitextfield that a user inputs a string, I want to check whether the textfield.text is equal to ANY of the values in the array, can I do this with one line of code rather than lots of if's and else if's?!?
This is a generic code that will do what you are looking for. The if statement checks to see if a given value is equal to something that is located in the array. Simply replace the arr.contains() with the output you have given for your UITextfield.text Try to do a little research before you post. I can see that you are new here, so here is a little bit of help.
var arr = [1,2,3,4]
if arr.contains(3) {
//do something
}
I seem to have a problem with a very simple scenario.
I'm trying to add values captured by two text fields (called T1 and T2) and display their total upon pressing a button (GoButton) on a label (Label1).
I tried wording the syntax in multiple ways and it still doesn't work. I feel that some of the syntax I found on the web didn't work for me. I use Xcode 6.3 on Yosemite.
Screenshot:
Is there a chance that there is something I'm missing with my Xcode to accept swift syntax? Please help.
Dante-
There's still a chance the values could be nil. You've correctly !'ed the TextFields so they unwrap automatically, but the Int conversion is also Optional (the Int still thinks it may get a nil value).
Label1.text = "\(T1.text.toInt()! + T2.text.toInt()!)"
Helpful Hint- If you paste your code in here (rather than a screenshot) it's much easier for folks to copy and paste your code into their IDE and test it out.
For those here smarter than me (everyone) I'm curious why Xcode doesn't complain about a single Int conversion:
Label1.text = "\(T1.text.toInt())" // no complaint from the compiler
Value T1.text.toInt() is an Optional Integer. So you must unwrap it first. So use Label1.text = "\(T1.text.toInt()! + T2.text.toInt()!)"
Good luck
Thats because toInt() returns an optional value. You can cast your String to NSString and extract the integer value without returning an optional.
Label1.text = ((T1.text! as NSString).integerValue + (T2.text! as NSString).integerValue + (T3.text! as NSString).integerValue + (T4.text! as NSString).integerValue).description
Label1.text = "\(T1.text.toInt()! + T2.text.toInt()!)" //T1.text.toInt()
is an optional so you should use ! mark otherwise it will return nil
value