0

I am making a joke app for friends and to improve my swift coding by making a LoveCalculator. The calculator finds the length of the two names of the lovers, times the lengths together, then takes that number away from 100, giving your love percentage. However, each time I try the app, it displays the number -40906 each time. Any ideas? I have tried changing the UITextField to String conversion method. I am quite a novice at swift, any help would by appreciated!

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var outputLabel: UILabel!
    @IBOutlet weak var personOne: UITextField!
    @IBOutlet weak var personTwo: UITextField!

    @IBAction func calculateButton(sender: AnyObject) {

    var one = toString(personOne)
    var two = toString(personTwo)

    var oneLength = countElements(one)
    var twoLength = countElements(two)

    var firstCalc = oneLength * twoLength
    var finalCalc = 100 - firstCalc

    outputLabel.text  = "%\(finalCalc)"  
}
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Woodman
  • 1,502
  • 2
  • 12
  • 20
  • PS: When run in a playground WITHOUT toString conversions or inputs from texFields/ out to Label, the code work perfectly. – Woodman Mar 23 '15 at 10:22
  • 2
    Printing the the values of the variables one, two would reveal your error quickly ... – Martin R Mar 23 '15 at 10:38
  • Apart from that `UITextField` problem, you also have an algorithm problem. Names longer than 10 letters will always end in a negative number. – Sulthan Mar 23 '15 at 11:39
  • Good point Sulthan, I don't know how I missed that... – Woodman Mar 23 '15 at 21:07

4 Answers4

2

personOne and personTwo are UITextFields, not texts.

Change your code to:

var one = toString(personOne.text)
var two = toString(personTwo.text)
saurabh
  • 6,687
  • 7
  • 42
  • 63
0

As you use outputLabel.text to access the text of the label, you do the same with the textfield -> textfield.text.

Docs

vale
  • 1,376
  • 11
  • 25
0

Try this


@IBAction func calculateButton(sender: AnyObject) {


    var oneLength = countElements(personOne.text)
    var twoLength = countElements(personTwo.text)

    var firstCalc = oneLength * twoLength
    var finalCalc = 100 - firstCalc

    outputLabel.text  = "%\(finalCalc)"  
}
Ram Vadranam
  • 485
  • 5
  • 14
0

What your code is trying to do is to print the UITextField instance into a string which would result into something like: <UITextField: 0x7f936981ca50; frame = (225 201; 97 30); text = ''; clipsToBounds = YES; opaque = NO; autoresize = RM+BM; layer = <CALayer: 0x7f93698228c0>>.

Mainly, your code should look like this in order to count the number of characters in the textfield's text:

@IBAction func calculateButton(sender: AnyObject) {
  var oneLength = countElements(personOne.text)
  var twoLength = countElements(personOne.text)

  var firstCalc = oneLength * twoLength
  var finalCalc = 100 - firstCalc

  outputLabel.text  = "%\(finalCalc)"
}