简体   繁体   English

如何在Xcode中对键入到TextField中的Integer值进行排序?

[英]How do I sort Integer values typed into a TextField in Xcode?

I've just started to do some simple programming with Swift, things like building a simple calculator and stuff like that. 我刚刚开始使用Swift进行一些简单的编程,例如构建一个简单的计算器之类的东西。 Now I would like to create an app that allows me to sort a bunch of integer values which the user is typing into the TextField. 现在,我想创建一个应用程序,使我可以对用户在TextField中键入的一堆整数值进行排序。 Down here is what I've got so far. 这是我到目前为止所掌握的。 Could you please tell me where my mistake is? 你能告诉我我的错误在哪里吗?

class ViewController2: UIViewController {
    @IBOutlet var randomNumbers: UITextField!
    @IBOutlet var finalResult: UITextView!

    @IBAction func SortNumbers(_ sender: UIButton) {
        let sortedNumbers = Int[randomNumbers.text]
        let sortedNubers = sortedNumbers.sort{$1>$2}
        finalResult.text = String(sortedNumbers)
    }

it's not the best answer you could get, but it might solves your problem: 这不是您可以获得的最佳答案,但可以解决您的问题:

@IBAction func sortNumbers(_ sender: UIButton) {
    let stringWithNumbers = "1 23 12 4 5 12"
    let sortedNumbers = stringWithNumbers.components(separatedBy: " ").flatMap { Int($0) }
    let sortedNubers = sortedNumbers.sorted { $0 > $1 }
    print(sortedNubers.description)
}

You're not converting it into an Int array properly. 您没有将其正确转换为Int数组。 If we can assume that the input string is a comma-separated list with no spaces: 如果我们可以假设输入字符串是一个逗号分隔的列表,没有空格:

let sortedNumbers = randomNumbers.text.components(separatedBy: ",").map{ Int($0) ?? 0 }

components splits it into a string array using commas as a reference, and then map converts each element into an Int (and ?? 0 catches any invalid input and prevents it from being an array of optionals). components使用逗号作为参考将其拆分为一个字符串数组,然后map将每个元素转换为一个Int(并且?? 0捕获任何无效输入,并防止其成为可选数组)。

Also, for the sake of your sanity and that of anyone who might have to read your code later, avoid using nearly-identical variable names like sortedNumbers and sortedNubers . 另外,为了您的头脑清楚,以及以后可能需要阅读代码的所有人的头脑,避免使用几乎相同的变量名,例如sortedNumberssortedNubers If you need to use multiple variables for the same data, make their differences more descriptive (for instance, the first one should probably be unsortedNumbers in this case). 如果您需要对同一数据使用多个变量,请使它们的区别更具描述性(例如,在这种情况下,第一个变量可能应该是unsortedNumbers )。

Your mistake is in trying to treat a single string as if it were an array of numbers. 您的错误在于尝试将单个字符串视为数字数组。 You're missing two steps in there: 您在其中缺少两个步骤:

  • Parsing: Take the string that the user has typed and turn it into numbers 解析:将用户键入的字符串转换为数字
  • Formatting: Take the stored numbers and turn them back into a string to display 格式:取出存储的数字并将其变回字符串以显示

Lurking in that first step is the possibility that the user has not actually typed in integers. 在第一步中潜伏着用户没有实际输入整数的可能性。 An approach that just ignores non-integer input would look like: 只会忽略非整数输入的方法如下所示:

@IBAction func sortTextAction(_ sender: UIButton) {
  guard let text = randomNumbers.text else {
    finalResult.text = ""  // clear out - no result on empty input
    return
  }

  // Parse String -> [Int]:
  // Split into words, then turn words into Ints,
  // while discarding non-Int words
  let words = text.components(separatedBy: CharacterSet.whitespacesAndNewlines)
  let numbers = words
    .map({ Int($0) })  // String -> Int?
    .flatMap({ $0 })  // discard any nil values

  let sorted = numbers.sort()

  // Format [Int] -> String: glue the sorted Ints together with a space between each
  finalResult.text = sorted
    .map({ String(describing: $0 })  // Int -> String: turn 1 into "1"
    .joined(separator: " ")  // [String] -> String: turn [1, 2, 3] into "1 2 3"
}

} }

Lurking behind both of these is localization: What one locale writes as "1,000" might be "1 000" or "1.000" elsewhere. 潜伏在这两个背后的是本地化:在一个区域设置中写为“ 1,000”的内容在其他地方可能是“ 1 000”或“ 1.000”。 For that, you'd pull in NumberFormatter to handle the conversions in a locale-aware way. 为此,您需要使用NumberFormatter来以语言环境感知的方式处理转换。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何按整数值对NSDictionary排序? - How do I sort an NSDictionary by integer value? 如果textField为空,如何禁用Xcode中的Alert Add按钮? - How do I disable the Alert Add button in Xcode if the textField is empty? 使用`textField:shouldChangeCharactersInRange:`,如何获取包含当前输入字符的文本? - Using `textField:shouldChangeCharactersInRange:`, how do I get the text including the current typed character? 如何使用Xcode UI Automation测试在警报文本字段中输入文本 - How do I enter text in an alert textfield using Xcode UI Automation testing 在Xcode中进行调试时如何打印整数值? - How to print integer values while debugging in Xcode? 如何在不将文本转换为整数或数字的情况下将两个文本字段值相乘 - How to Multiply Two textfield values Without converting the text into integer or Number 在UITableview中,键入的文本字段值在不同的单元格中重复出现,如何使用目标c纠正该问题 - In UITableview the typed textfield values is getting repeated in different cells ,how to rectify that using objective c 如何根据打字文本增加文本字段的宽度? - How to increase width of textfield according to typed text? 如何根据编辑textfield1更新textfield2? - How do I update textfield2 based on editing textfield1? 如何使用 Xcode 11 在情节提要中创建单个文本 URL? 如果在代码中完成,除编码文本字段外,我的所有界面都将被删除 - How do I create a single text URL in storyboard using Xcode 11? If done in code, all of my interface is erased except for the coded textfield
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM