Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

ios - cannot be applied to operands of type 'UITextField' and 'Int'

I am trying to populate a Label with a text field input * 365 I keep getting the message:

Binary operator '*' cannot be applied to operands of type 'UITextField' and 'Int'

var hours = (hoursTextField.text as NSString).doubleValue
var hoursInAYear = hoursTextField * 365
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your first line is calculating the doubleValue of what's entered into the text field, but you're not using that hours variable. Perhaps you want:

var hoursInAYear = hours * 365

The warning you are getting is telling you that you're trying to use the * operator between a variable whose type is UITextField and another variable whose type is Int (this is what your 365 literal is interpreted as).

This warning will come up any time we try to use an operator between two types for which the operator does not have an overload. It is particularly common when one of our operand's types is implicitly determined because we're using a literal somewhere. To resolve the issue, we must double check our instantiation of our operands and be sure they're of types for which our operator has an overload.

If they are not, then we should either change how we create these variables so they have the right type, or find some way of converting them when we use them with the operator.

When we change our mistaken variable from the text field to the double we just calculated, Swift is able to calculate this correctly. Despite previously claiming that 365 was an Int, being a literal, it can be interpreted as several different types, one of which includes Double.

When we attempt to use the * between a variable of type Double and a literal number, the literal number will be correctly converted to a Double, and we'll use the overload of the * operator which accepts two doubles (and returns a double).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...