user2829664
user2829664

Reputation:

Swift count string size in for loop

for my homework assignment I have to convert the sentence the user has typed in 3 different ways.

I believe my logic is correct but I don't know where I am wrong.

This is my code:

//
//  ViewController.swift
//  Lower Upper Converter
//
//  Created by Mac User on 9/27/15.
//  Copyright © 2015 Omid Nassir. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

   private var input = ""
    private var i = 0
    var sentense = [String]()
    //var sentenseChar: [Character] = []

   //input fields
    @IBOutlet weak var input1: UITextField!

    @IBOutlet weak var input2: UITextField!




    //caps button
    @IBAction func capsBtn(sender: AnyObject)
    {
        if input1.text != nil
        {
            input = input1.text!.uppercaseString
            input2.text = input
        }
        else
        {
            input2.text = ""
        }
    }

    //lower case button
    @IBAction func lowsBtn(sender: AnyObject)
    {
        if input1.text != nil
        {
            input = input1.text!.lowercaseString
            input2.text = input
        }
        else
        {
            input2.text = ""
        }
    }


    //word converter button
    @IBAction func capsLowsBtn(sender: AnyObject)
    {

        if input1.text != nil
        {

          for i=0; i < count(input1.text); i++
          {
            input = advance(input1.startIndex, i)
            str[input]
            sentense[i] = advance(input.startIndex, i)
          }

          }

    }//end of convert function


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

I am getting an error message:

 Cannot invoke 'count' with an argument list of type '(String?)'

for this statement: for i=0; i < count(input1.text); i++

Upvotes: 2

Views: 923

Answers (2)

footyapps27
footyapps27

Reputation: 4042

A better way of doing this will be: (Tested in Swift 3.x)

for i in 0 ..< input1.text!.characters.count
{
  ...
}

Upvotes: 1

Peter Kreinz
Peter Kreinz

Reputation: 8636

Note! With Swift 2 you have to use a new syntax:

Change your code to:

for var i = 0; i < input1.text!.characters.count; i++
{
    ...
}

Upvotes: 2

Related Questions