【问题标题】:Swift count string size in for loop快速计算for循环中的字符串大小
【发布时间】:2015-12-27 12:33:03
【问题描述】:

对于我的家庭作业,我必须转换用户以 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 &lt; count(input1.text); i++

【问题讨论】:

  • 尝试 input1.text.count 并删除 count()
  • 请看下面彼得的回答:Swift2 有新语法:characters.count。您需要使用它来正确解释 Unicode 字符。
  • for i in 0..

标签: arrays string swift for-loop


【解决方案1】:

注意!使用 Swift 2 你必须使用新的语法:

将您的代码更改为:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-06-26
      • 2012-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-10
      • 1970-01-01
      • 2022-01-03
      • 2021-07-14
      相关资源
      最近更新 更多