rissandimo rissandimo - 24 days ago 17
Swift Question

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.


  • Convert all letters to uppercase(completed)

  • Convert all letters to lowercase(completed)

  • Convert the uppercase letters to lowercase and vice versa(having trouble)



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++

Answer

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++
{
    ...
}
Comments