Why does the code print an optional value?












-1















var myString = "7"
var possibleInt = Int(myString)
print(possibleInt)


The above code prints out:




Optional(7)




Why does it do this even though I did not use an optional. The string was converted to a number so shouldn't the out be:




7




?



myString = "banana"
possibleInt = Int(myString)
print(possibleInt)


This code will print out nil because type conversion did not work but I don't see how 7 could be an optional.










share|improve this question


















  • 1





    If it can be nil, it has to be an Optional.

    – matt
    Sep 27 '15 at 0:17











  • @matt Why can it be a nil?

    – Nocturnal
    Sep 27 '15 at 0:18






  • 1





    As you yourself said. It might fail because the string is not a number.

    – matt
    Sep 27 '15 at 0:19






  • 1





    The Int(string:) constructor can only return 1 type. It doesn't get to decide that it is going to return a regular Int if the conversion succeeds and a nil if it doesn't. It is not possible to return both nil and an Int. If you're going to return nil, you have to return an Int? which is what Int(string:) returns. The return type of a function is determined at compile time, but the value you are passing to be be converted can be determined at run time.

    – vacawama
    Sep 27 '15 at 0:29








  • 1





    If you don't want it to be an optional you have to provide a default value. You can use ?? nil coalescing operator. let num = Int("string") ?? 0

    – Leo Dabus
    Sep 27 '15 at 0:31
















-1















var myString = "7"
var possibleInt = Int(myString)
print(possibleInt)


The above code prints out:




Optional(7)




Why does it do this even though I did not use an optional. The string was converted to a number so shouldn't the out be:




7




?



myString = "banana"
possibleInt = Int(myString)
print(possibleInt)


This code will print out nil because type conversion did not work but I don't see how 7 could be an optional.










share|improve this question


















  • 1





    If it can be nil, it has to be an Optional.

    – matt
    Sep 27 '15 at 0:17











  • @matt Why can it be a nil?

    – Nocturnal
    Sep 27 '15 at 0:18






  • 1





    As you yourself said. It might fail because the string is not a number.

    – matt
    Sep 27 '15 at 0:19






  • 1





    The Int(string:) constructor can only return 1 type. It doesn't get to decide that it is going to return a regular Int if the conversion succeeds and a nil if it doesn't. It is not possible to return both nil and an Int. If you're going to return nil, you have to return an Int? which is what Int(string:) returns. The return type of a function is determined at compile time, but the value you are passing to be be converted can be determined at run time.

    – vacawama
    Sep 27 '15 at 0:29








  • 1





    If you don't want it to be an optional you have to provide a default value. You can use ?? nil coalescing operator. let num = Int("string") ?? 0

    – Leo Dabus
    Sep 27 '15 at 0:31














-1












-1








-1








var myString = "7"
var possibleInt = Int(myString)
print(possibleInt)


The above code prints out:




Optional(7)




Why does it do this even though I did not use an optional. The string was converted to a number so shouldn't the out be:




7




?



myString = "banana"
possibleInt = Int(myString)
print(possibleInt)


This code will print out nil because type conversion did not work but I don't see how 7 could be an optional.










share|improve this question














var myString = "7"
var possibleInt = Int(myString)
print(possibleInt)


The above code prints out:




Optional(7)




Why does it do this even though I did not use an optional. The string was converted to a number so shouldn't the out be:




7




?



myString = "banana"
possibleInt = Int(myString)
print(possibleInt)


This code will print out nil because type conversion did not work but I don't see how 7 could be an optional.







xcode swift optional






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Sep 27 '15 at 0:15









NocturnalNocturnal

16010




16010








  • 1





    If it can be nil, it has to be an Optional.

    – matt
    Sep 27 '15 at 0:17











  • @matt Why can it be a nil?

    – Nocturnal
    Sep 27 '15 at 0:18






  • 1





    As you yourself said. It might fail because the string is not a number.

    – matt
    Sep 27 '15 at 0:19






  • 1





    The Int(string:) constructor can only return 1 type. It doesn't get to decide that it is going to return a regular Int if the conversion succeeds and a nil if it doesn't. It is not possible to return both nil and an Int. If you're going to return nil, you have to return an Int? which is what Int(string:) returns. The return type of a function is determined at compile time, but the value you are passing to be be converted can be determined at run time.

    – vacawama
    Sep 27 '15 at 0:29








  • 1





    If you don't want it to be an optional you have to provide a default value. You can use ?? nil coalescing operator. let num = Int("string") ?? 0

    – Leo Dabus
    Sep 27 '15 at 0:31














  • 1





    If it can be nil, it has to be an Optional.

    – matt
    Sep 27 '15 at 0:17











  • @matt Why can it be a nil?

    – Nocturnal
    Sep 27 '15 at 0:18






  • 1





    As you yourself said. It might fail because the string is not a number.

    – matt
    Sep 27 '15 at 0:19






  • 1





    The Int(string:) constructor can only return 1 type. It doesn't get to decide that it is going to return a regular Int if the conversion succeeds and a nil if it doesn't. It is not possible to return both nil and an Int. If you're going to return nil, you have to return an Int? which is what Int(string:) returns. The return type of a function is determined at compile time, but the value you are passing to be be converted can be determined at run time.

    – vacawama
    Sep 27 '15 at 0:29








  • 1





    If you don't want it to be an optional you have to provide a default value. You can use ?? nil coalescing operator. let num = Int("string") ?? 0

    – Leo Dabus
    Sep 27 '15 at 0:31








1




1





If it can be nil, it has to be an Optional.

– matt
Sep 27 '15 at 0:17





If it can be nil, it has to be an Optional.

– matt
Sep 27 '15 at 0:17













@matt Why can it be a nil?

– Nocturnal
Sep 27 '15 at 0:18





@matt Why can it be a nil?

– Nocturnal
Sep 27 '15 at 0:18




1




1





As you yourself said. It might fail because the string is not a number.

– matt
Sep 27 '15 at 0:19





As you yourself said. It might fail because the string is not a number.

– matt
Sep 27 '15 at 0:19




1




1





The Int(string:) constructor can only return 1 type. It doesn't get to decide that it is going to return a regular Int if the conversion succeeds and a nil if it doesn't. It is not possible to return both nil and an Int. If you're going to return nil, you have to return an Int? which is what Int(string:) returns. The return type of a function is determined at compile time, but the value you are passing to be be converted can be determined at run time.

– vacawama
Sep 27 '15 at 0:29







The Int(string:) constructor can only return 1 type. It doesn't get to decide that it is going to return a regular Int if the conversion succeeds and a nil if it doesn't. It is not possible to return both nil and an Int. If you're going to return nil, you have to return an Int? which is what Int(string:) returns. The return type of a function is determined at compile time, but the value you are passing to be be converted can be determined at run time.

– vacawama
Sep 27 '15 at 0:29






1




1





If you don't want it to be an optional you have to provide a default value. You can use ?? nil coalescing operator. let num = Int("string") ?? 0

– Leo Dabus
Sep 27 '15 at 0:31





If you don't want it to be an optional you have to provide a default value. You can use ?? nil coalescing operator. let num = Int("string") ?? 0

– Leo Dabus
Sep 27 '15 at 0:31












4 Answers
4






active

oldest

votes


















2














When you convert a value (i.e. a String to an Int) it will be an optional - if you tried to run:



let num = Int("things")
// num is Optional(nil)


This couldn't possibly be a number, so it returns an 'empty' optional.



If you know that the string will always be a valid number you can unwrap it unsafely:



let num = Int("5")!
// num is 5, not Optional(5)


Or if you don't know if the string will be a valid int, you can safely unwrap it:



if let num = Int(myString) {
// Do something with the number
} else {
// Catch some error
}





share|improve this answer





















  • 1





    The catch with that is that if you do let num = Int("Hello")! then the app will crash at runtime. It would be better to add some optional binding rather than explicit unwrapping.

    – Fogmeister
    Sep 27 '15 at 15:18



















1














The beauty about optionals is that they create a safety net in your code. If you take another language and try to parse "example123" as an Int, it will crash and the program will terminate. However in Swift, most functions which may otherwise lead to a crash return an optional, so that the program keeps running.



There are two ways you can avoid getting an optional value at the end of your program.



If you are absolutely sure that the input in Int() will be an integer, you can use



var possibleInt = Int(myString)!


And of course, if myString isn't an integer, your app will crash. However you can securely unwrap it by doing



if let possibleInt = Int(myString) {
// use possibleInt as an int and not an optional
}
// otherwise, the program won't do anything with possibleInt


Hope this helps.






share|improve this answer































    0














    Int() method return a optional value, because if your string contain something that is not a number, such as "abc123", Int("abc123") will return nil,
    and also, a method return a optional value has not any relationship with what is the method's argument is.






    share|improve this answer































      0














      You can see you did not declare a "myString" to any type first declare as string/integer and then try to print that variable. you will get the exact result that you want.



      var myString = "7"



      var possibleInt: Int;



      var possibleInt = Int(myString)



      print(possibleInt)






      share|improve this answer

























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f32803313%2fwhy-does-the-code-print-an-optional-value%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        2














        When you convert a value (i.e. a String to an Int) it will be an optional - if you tried to run:



        let num = Int("things")
        // num is Optional(nil)


        This couldn't possibly be a number, so it returns an 'empty' optional.



        If you know that the string will always be a valid number you can unwrap it unsafely:



        let num = Int("5")!
        // num is 5, not Optional(5)


        Or if you don't know if the string will be a valid int, you can safely unwrap it:



        if let num = Int(myString) {
        // Do something with the number
        } else {
        // Catch some error
        }





        share|improve this answer





















        • 1





          The catch with that is that if you do let num = Int("Hello")! then the app will crash at runtime. It would be better to add some optional binding rather than explicit unwrapping.

          – Fogmeister
          Sep 27 '15 at 15:18
















        2














        When you convert a value (i.e. a String to an Int) it will be an optional - if you tried to run:



        let num = Int("things")
        // num is Optional(nil)


        This couldn't possibly be a number, so it returns an 'empty' optional.



        If you know that the string will always be a valid number you can unwrap it unsafely:



        let num = Int("5")!
        // num is 5, not Optional(5)


        Or if you don't know if the string will be a valid int, you can safely unwrap it:



        if let num = Int(myString) {
        // Do something with the number
        } else {
        // Catch some error
        }





        share|improve this answer





















        • 1





          The catch with that is that if you do let num = Int("Hello")! then the app will crash at runtime. It would be better to add some optional binding rather than explicit unwrapping.

          – Fogmeister
          Sep 27 '15 at 15:18














        2












        2








        2







        When you convert a value (i.e. a String to an Int) it will be an optional - if you tried to run:



        let num = Int("things")
        // num is Optional(nil)


        This couldn't possibly be a number, so it returns an 'empty' optional.



        If you know that the string will always be a valid number you can unwrap it unsafely:



        let num = Int("5")!
        // num is 5, not Optional(5)


        Or if you don't know if the string will be a valid int, you can safely unwrap it:



        if let num = Int(myString) {
        // Do something with the number
        } else {
        // Catch some error
        }





        share|improve this answer















        When you convert a value (i.e. a String to an Int) it will be an optional - if you tried to run:



        let num = Int("things")
        // num is Optional(nil)


        This couldn't possibly be a number, so it returns an 'empty' optional.



        If you know that the string will always be a valid number you can unwrap it unsafely:



        let num = Int("5")!
        // num is 5, not Optional(5)


        Or if you don't know if the string will be a valid int, you can safely unwrap it:



        if let num = Int(myString) {
        // Do something with the number
        } else {
        // Catch some error
        }






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Sep 27 '15 at 19:23

























        answered Sep 27 '15 at 0:19









        Will RichardsonWill Richardson

        4,95953343




        4,95953343








        • 1





          The catch with that is that if you do let num = Int("Hello")! then the app will crash at runtime. It would be better to add some optional binding rather than explicit unwrapping.

          – Fogmeister
          Sep 27 '15 at 15:18














        • 1





          The catch with that is that if you do let num = Int("Hello")! then the app will crash at runtime. It would be better to add some optional binding rather than explicit unwrapping.

          – Fogmeister
          Sep 27 '15 at 15:18








        1




        1





        The catch with that is that if you do let num = Int("Hello")! then the app will crash at runtime. It would be better to add some optional binding rather than explicit unwrapping.

        – Fogmeister
        Sep 27 '15 at 15:18





        The catch with that is that if you do let num = Int("Hello")! then the app will crash at runtime. It would be better to add some optional binding rather than explicit unwrapping.

        – Fogmeister
        Sep 27 '15 at 15:18













        1














        The beauty about optionals is that they create a safety net in your code. If you take another language and try to parse "example123" as an Int, it will crash and the program will terminate. However in Swift, most functions which may otherwise lead to a crash return an optional, so that the program keeps running.



        There are two ways you can avoid getting an optional value at the end of your program.



        If you are absolutely sure that the input in Int() will be an integer, you can use



        var possibleInt = Int(myString)!


        And of course, if myString isn't an integer, your app will crash. However you can securely unwrap it by doing



        if let possibleInt = Int(myString) {
        // use possibleInt as an int and not an optional
        }
        // otherwise, the program won't do anything with possibleInt


        Hope this helps.






        share|improve this answer




























          1














          The beauty about optionals is that they create a safety net in your code. If you take another language and try to parse "example123" as an Int, it will crash and the program will terminate. However in Swift, most functions which may otherwise lead to a crash return an optional, so that the program keeps running.



          There are two ways you can avoid getting an optional value at the end of your program.



          If you are absolutely sure that the input in Int() will be an integer, you can use



          var possibleInt = Int(myString)!


          And of course, if myString isn't an integer, your app will crash. However you can securely unwrap it by doing



          if let possibleInt = Int(myString) {
          // use possibleInt as an int and not an optional
          }
          // otherwise, the program won't do anything with possibleInt


          Hope this helps.






          share|improve this answer


























            1












            1








            1







            The beauty about optionals is that they create a safety net in your code. If you take another language and try to parse "example123" as an Int, it will crash and the program will terminate. However in Swift, most functions which may otherwise lead to a crash return an optional, so that the program keeps running.



            There are two ways you can avoid getting an optional value at the end of your program.



            If you are absolutely sure that the input in Int() will be an integer, you can use



            var possibleInt = Int(myString)!


            And of course, if myString isn't an integer, your app will crash. However you can securely unwrap it by doing



            if let possibleInt = Int(myString) {
            // use possibleInt as an int and not an optional
            }
            // otherwise, the program won't do anything with possibleInt


            Hope this helps.






            share|improve this answer













            The beauty about optionals is that they create a safety net in your code. If you take another language and try to parse "example123" as an Int, it will crash and the program will terminate. However in Swift, most functions which may otherwise lead to a crash return an optional, so that the program keeps running.



            There are two ways you can avoid getting an optional value at the end of your program.



            If you are absolutely sure that the input in Int() will be an integer, you can use



            var possibleInt = Int(myString)!


            And of course, if myString isn't an integer, your app will crash. However you can securely unwrap it by doing



            if let possibleInt = Int(myString) {
            // use possibleInt as an int and not an optional
            }
            // otherwise, the program won't do anything with possibleInt


            Hope this helps.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Sep 27 '15 at 15:08







            user5381742






























                0














                Int() method return a optional value, because if your string contain something that is not a number, such as "abc123", Int("abc123") will return nil,
                and also, a method return a optional value has not any relationship with what is the method's argument is.






                share|improve this answer




























                  0














                  Int() method return a optional value, because if your string contain something that is not a number, such as "abc123", Int("abc123") will return nil,
                  and also, a method return a optional value has not any relationship with what is the method's argument is.






                  share|improve this answer


























                    0












                    0








                    0







                    Int() method return a optional value, because if your string contain something that is not a number, such as "abc123", Int("abc123") will return nil,
                    and also, a method return a optional value has not any relationship with what is the method's argument is.






                    share|improve this answer













                    Int() method return a optional value, because if your string contain something that is not a number, such as "abc123", Int("abc123") will return nil,
                    and also, a method return a optional value has not any relationship with what is the method's argument is.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Sep 27 '15 at 2:35









                    A BLUEA BLUE

                    184




                    184























                        0














                        You can see you did not declare a "myString" to any type first declare as string/integer and then try to print that variable. you will get the exact result that you want.



                        var myString = "7"



                        var possibleInt: Int;



                        var possibleInt = Int(myString)



                        print(possibleInt)






                        share|improve this answer






























                          0














                          You can see you did not declare a "myString" to any type first declare as string/integer and then try to print that variable. you will get the exact result that you want.



                          var myString = "7"



                          var possibleInt: Int;



                          var possibleInt = Int(myString)



                          print(possibleInt)






                          share|improve this answer




























                            0












                            0








                            0







                            You can see you did not declare a "myString" to any type first declare as string/integer and then try to print that variable. you will get the exact result that you want.



                            var myString = "7"



                            var possibleInt: Int;



                            var possibleInt = Int(myString)



                            print(possibleInt)






                            share|improve this answer















                            You can see you did not declare a "myString" to any type first declare as string/integer and then try to print that variable. you will get the exact result that you want.



                            var myString = "7"



                            var possibleInt: Int;



                            var possibleInt = Int(myString)



                            print(possibleInt)







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Nov 15 '18 at 5:21

























                            answered Nov 14 '18 at 12:44









                            TatsatTatsat

                            11




                            11






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f32803313%2fwhy-does-the-code-print-an-optional-value%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Bressuire

                                Vorschmack

                                Quarantine