简体   繁体   English

如何使用 Swift 上的 readLine() 比较两种不同类型的数据(String 和 Int)?

[英]How can I compare two different types of data (String and Int) using readLine() on Swift?

everyone, I'm a new member of Stack Overflow.大家好,我是 Stack Overflow 的新成员。 just like I'm beginner on swift programming: I'm making this post to find out a solution for the following case:就像我是 swift 编程的初学者一样:我写这篇文章是为了找出以下情况的解决方案:

I'm creating on Swift an app using the Command Line Tool for inputing data.我正在 Swift 创建一个使用命令行工具输入数据的应用程序。 The app basically works as an authenticator.该应用程序基本上用作身份验证器。 As an example, if someone types USA for the country name and the age is 17, so the program will return a message like "You can not apply to this position".例如,如果有人输入美国作为国家名称并且年龄是 17 岁,那么程序将返回一条消息,如“您不能申请这个职位”。 Otherwise, if the country name is USA and the age is equal or higher than 18, so the message returns is "You can forward to the next step".否则,如果国家名称是 USA 并且年龄等于或大于 18 岁,则返回的消息是“您可以转到下一步”。 I've tried many times to set this conditions, but it's not working.我已经多次尝试设置此条件,但它不起作用。 I'm already knows that the function readLine() is an Optional String, but how can I make my program work correctly?我已经知道 function readLine() 是一个可选字符串,但是我怎样才能让我的程序正常工作呢? It follows my code above to you understanding my thoughts.它遵循我上面的代码让你理解我的想法。

I really appreciate any help.我真的很感激任何帮助。 Again, I'm beginner and I'm already studying Swift languages, but I'm seeking some solution that handles Integers and Strings and comparing both data types.同样,我是初学者,我已经在学习 Swift 种语言,但我正在寻找一些处理整数和字符串并比较这两种数据类型的解决方案。 Thank you very much!非常感谢你!

My code is:我的代码是:

import Foundation

print("Enter your country: ")
var country = readLine()

print("Enter your age: ")
var age = readLine()

if var country, var age = readLine(){
    if country == "USA" && age < "18" {
        print("You're not allowed to apply to this position.")
    } else {
        print("You can forward to the next step.")
    }
    
}


PS: As you see, I'm using wrongly the variable age as an String, but I want to convert it to an Int type and then, check if the country name is the same than the value I assigned to or the age is equal or higher than 18. But not found a solution so far. PS:如您所见,我错误地将变量age用作String,但我想将其转换为Int类型,然后检查国家名称是否与我分配的值相同或年龄是否相等或高于18。但到目前为止还没有找到解决方案。

I'm trying to find a solution that compares two different types on Swift, using Command Line Tool and the readLine() function to check if a condition is true or not.我正在尝试找到一种解决方案来比较 Swift 上的两种不同类型,使用命令行工具和 readLine() function 来检查条件是否为真。 If it's true, an output message will show that the user can proceed to the next step, otherwise he will not be permitted to follow.如果为真,将显示 output 消息,提示用户可以进行下一步,否则不允许跟随。 I'm keeping for an explanation on inte.net since few days, but not found anything that might help me.几天以来我一直在 inte.net 上寻找解释,但没有找到任何可能对我有帮助的东西。 I hope to get some help using the Stack Overflow forum to some useful answer.我希望使用 Stack Overflow 论坛获得一些有用的答案。

First one, readline() means you read the current to the end of current line.第一个, readline()意味着你读到当前行的末尾。 As your code when you check condition you call readLine() again.作为您检查条件时的代码,您再次调用readLine() The wrong part is here.错误的部分在这里。

I recommend you to read first then do all your logic.我建议您先阅读,然后再执行所有逻辑。 You just need to read only one time at first一开始你只需要阅读一次

print("Enter your country: ")
var country = readLine()

print("Enter your age: ")
var ageString = readLine()

Next, check if it is nil or not ( because option value which is value can be nil)接下来,检查它是否为 nil(因为 value 的选项值可以为 nil)

if country == nil || ageString == nil {
    print("Error because one of them is nil")
    fatalError()
}

Then check if can convert to Int or not.然后检查是否可以转换为 Int。 Reach here you sure that the ageString is not nil because you have checked above.到达这里你确定ageString不为 nil 因为你已经在上面检查过了。 So you just simply convert所以你只需简单地转换

guard let ageString = ageString else {
    print("Error age nil")
    fatalError()
}

guard let age = Int(ageString) else {
    print("Error age not a number")
    fatalError()
}

Then after all, you just check your condition然后毕竟,你只是检查你的条件

Full code will be like this完整的代码将是这样的

print("Enter your country: ")
var country = readLine()

print("Enter your age: ")
var ageString = readLine()

// check nil first if nil return or do something first and not get to the rest
if country == nil || ageString == nil {
    print("Error because one of them is nil")
    fatalError()
}

guard let ageString = ageString else {
    print("Error age nil")
    fatalError()
}

guard let age = Int(ageString) else {
    print("Error age not a number")
    fatalError()
}

if country == "USA" && age < 18 {
    print("You're not allowed to apply to this position.")
} else {
    print("You can forward to the next step.")
}

Other methods is use if let to achieve so no force unwrap其他方法是使用if let来实现,所以没有强制解包

print("Enter your country: ")
var country = readLine()

print("Enter your age: ")
var ageString = readLine()

// check nil first if nil return or do something first and not get to the rest
if country == nil || ageString == nil {
    print("Error because one of them is nil")
    fatalError()
}

if let ageString = ageString {
    if let age = Int(ageString) {
        if country == "USA" && age < 18 {
            print("You're not allowed to apply to this position.")
        } else {
            print("You can forward to the next step.")
        }
    } else {
        print("Error age not a number")
        fatalError()
    }
}

SOLUTION SOLVED!解决方案已解决!

Hey, guys, first of all I want to thank you all for your helpful answers, which helped me a lot.嘿,伙计们,首先我要感谢你们所有有用的答案,这对我帮助很大。 I've got finally a solution, and am going to share it with you.我终于找到了解决方案,并将与您分享。

What did I done?我做了什么? I just created two variables, one String and another Integer. Then, using the if var to force unwrapping of the Int variable, I've made an if statement to check if the both conditions are true (in the case, if the person is from USA and has an age equals or higher than 18).我刚刚创建了两个变量,一个 String 和另一个 Integer。然后,使用 if var 强制展开 Int 变量,我做了一个 if 语句来检查两个条件是否为真(在这种情况下,如果这个人是来自美国且年龄等于或大于 18 岁)。 Now, the program is running on the same way I just wanted.现在,程序按照我想要的方式运行。 If you are from USA but has no 18 years, output returns a message that you can not apply.如果您来自美国但没有满 18 岁,output 将返回一条消息,您无法申请。 Otherwise, you're able to forward.否则,您可以转发。

I'll let the code above.我会让上面的代码。 If you want to make some comments or any suggestions, it'll be welcome.如果您想提出一些意见或任何建议,我们将不胜感激。

Again, thank you very much for all your answers.再次非常感谢您的所有回答。

var countryCheck = "USA"
var ageCheck: Int = 18

print("Enter your country: ")
var country = readLine()

print("Enter your age: ")
var age = readLine()

if var countryCheck = country, var ageCheck = Int(age!) {
    if countryCheck == "USA" && ageCheck >= 18 {
        print("You can apply.")
    } else {
        print("You can not apply to this position.")
    }
}

I hope this help you:)我希望这对你有帮助:)

import Foundation

print("Enter your country: ")
if let country = readLine() {
  if let num = Int(country) {
      print(num)
      }
    }
      let country = readLine()
let age = readLine()


if let USA = country, 
    let num1 = Int(USA), 
    let num2 = Int(USA) {
    print("The age of \(num1) and \(num2) is \(num1 + num2)")
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM