for循环中的Swift计数字符串大小

时间:2015-09-29 21:19:34

标签: arrays string swift for-loop

对于我的家庭作业,我必须转换用户以3种不同方式输入的句子。

  • 将所有字母转换为大写(已完成)
  • 将所有字母转换为小写(已完成)
  • 将大写字母转换为小写,反之亦然(有问题)

我相信我的逻辑是正确的,但我不知道我错在哪里。

这是我的代码:

//
//  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.
    }


}

我收到一条错误消息:

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

此声明:for i=0; i < count(input1.text); i++

2 个答案:

答案 0 :(得分:2)

请注意!使用Swift 2,您必须使用新语法:

将您的代码更改为:

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

答案 1 :(得分:1)

更好的方法是:(在Swift 3.x中测试)

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