Swift 4 - How to have a function set a variable outside that function












0















So I just started with Swift the other day. In messing around with some code, I tried to write a function that would have a target player attack and enemy and have that enemies HP reduced by the amount of attack power of the player. Everything works inside the function fine, but I can't seem to find a way to get it to effect the selected enemy outside the function. Maybe its something that will come in a later lesson, but in my head it should be something simple that I can't seem to figure out.



Here is the code that I am using.



struct Player {
var maxHP: Int
var currentHP: Int
var maxMP: Int
var currentMP: Int
var currentLVL: Int
var damageATT: Int
}

struct Enemy {
var maxHP: Int
var currentHP: Int
var damageAtt: Int
}

var alexRider = Player(maxHP: 100, currentHP: 100, maxMP: 100, currentMP: 100, currentLVL: 1, damageATT: 5)
var enemyOne = Enemy(maxHP: 20, currentHP: 20, damageAtt: 2)
var enemyTwo = Enemy(maxHP: 40, currentHP: 40, damageAtt: 4)

func attackTarget(attacker player: Player, enemy target: Enemy) {
var attackTAR = target
attackTAR.currentHP -= player.damageATT
print("Dealt (player.damageATT) damage!")
print("Enemy now has (attackTAR.currentHP) health remaining")
}

attackTarget(attacker: alexRider, enemy: enemyTwo)
print(enemyTwo.currentHP)


Obviously, when I print the currentHP at the end of the code, its the same as it started since the scope of the variables inside the function do not pass outside. The print commands inside the function work fine to show the damage amount and remaining HP of the instance inside.



Is there something simple I am missing here? Again I know this should be something simple, but just getting started with this I was hoping someone could point me in the right direction.



Thanks.










share|improve this question























  • Don't do var attackTar = target then using attackTar. Here, you create a new variable with new memory and allocate space as a different object. Simply do target.currentHP -= player.damageATT. Don't expect to create a new object and it reference an older object.

    – impression7vx
    Jan 19 at 2:55











  • I tried that initially and get an error message that the Left side of mutating operator isn't mutable: 'target' is a 'let' constant.

    – QuantamPulse
    Jan 19 at 3:00











  • This is something that will be covered later in the tutorial.

    – Josh Caswell
    Jan 19 at 3:15






  • 1





    Use classes instead of structs

    – Carpsen90
    Jan 19 at 10:28
















0















So I just started with Swift the other day. In messing around with some code, I tried to write a function that would have a target player attack and enemy and have that enemies HP reduced by the amount of attack power of the player. Everything works inside the function fine, but I can't seem to find a way to get it to effect the selected enemy outside the function. Maybe its something that will come in a later lesson, but in my head it should be something simple that I can't seem to figure out.



Here is the code that I am using.



struct Player {
var maxHP: Int
var currentHP: Int
var maxMP: Int
var currentMP: Int
var currentLVL: Int
var damageATT: Int
}

struct Enemy {
var maxHP: Int
var currentHP: Int
var damageAtt: Int
}

var alexRider = Player(maxHP: 100, currentHP: 100, maxMP: 100, currentMP: 100, currentLVL: 1, damageATT: 5)
var enemyOne = Enemy(maxHP: 20, currentHP: 20, damageAtt: 2)
var enemyTwo = Enemy(maxHP: 40, currentHP: 40, damageAtt: 4)

func attackTarget(attacker player: Player, enemy target: Enemy) {
var attackTAR = target
attackTAR.currentHP -= player.damageATT
print("Dealt (player.damageATT) damage!")
print("Enemy now has (attackTAR.currentHP) health remaining")
}

attackTarget(attacker: alexRider, enemy: enemyTwo)
print(enemyTwo.currentHP)


Obviously, when I print the currentHP at the end of the code, its the same as it started since the scope of the variables inside the function do not pass outside. The print commands inside the function work fine to show the damage amount and remaining HP of the instance inside.



Is there something simple I am missing here? Again I know this should be something simple, but just getting started with this I was hoping someone could point me in the right direction.



Thanks.










share|improve this question























  • Don't do var attackTar = target then using attackTar. Here, you create a new variable with new memory and allocate space as a different object. Simply do target.currentHP -= player.damageATT. Don't expect to create a new object and it reference an older object.

    – impression7vx
    Jan 19 at 2:55











  • I tried that initially and get an error message that the Left side of mutating operator isn't mutable: 'target' is a 'let' constant.

    – QuantamPulse
    Jan 19 at 3:00











  • This is something that will be covered later in the tutorial.

    – Josh Caswell
    Jan 19 at 3:15






  • 1





    Use classes instead of structs

    – Carpsen90
    Jan 19 at 10:28














0












0








0








So I just started with Swift the other day. In messing around with some code, I tried to write a function that would have a target player attack and enemy and have that enemies HP reduced by the amount of attack power of the player. Everything works inside the function fine, but I can't seem to find a way to get it to effect the selected enemy outside the function. Maybe its something that will come in a later lesson, but in my head it should be something simple that I can't seem to figure out.



Here is the code that I am using.



struct Player {
var maxHP: Int
var currentHP: Int
var maxMP: Int
var currentMP: Int
var currentLVL: Int
var damageATT: Int
}

struct Enemy {
var maxHP: Int
var currentHP: Int
var damageAtt: Int
}

var alexRider = Player(maxHP: 100, currentHP: 100, maxMP: 100, currentMP: 100, currentLVL: 1, damageATT: 5)
var enemyOne = Enemy(maxHP: 20, currentHP: 20, damageAtt: 2)
var enemyTwo = Enemy(maxHP: 40, currentHP: 40, damageAtt: 4)

func attackTarget(attacker player: Player, enemy target: Enemy) {
var attackTAR = target
attackTAR.currentHP -= player.damageATT
print("Dealt (player.damageATT) damage!")
print("Enemy now has (attackTAR.currentHP) health remaining")
}

attackTarget(attacker: alexRider, enemy: enemyTwo)
print(enemyTwo.currentHP)


Obviously, when I print the currentHP at the end of the code, its the same as it started since the scope of the variables inside the function do not pass outside. The print commands inside the function work fine to show the damage amount and remaining HP of the instance inside.



Is there something simple I am missing here? Again I know this should be something simple, but just getting started with this I was hoping someone could point me in the right direction.



Thanks.










share|improve this question














So I just started with Swift the other day. In messing around with some code, I tried to write a function that would have a target player attack and enemy and have that enemies HP reduced by the amount of attack power of the player. Everything works inside the function fine, but I can't seem to find a way to get it to effect the selected enemy outside the function. Maybe its something that will come in a later lesson, but in my head it should be something simple that I can't seem to figure out.



Here is the code that I am using.



struct Player {
var maxHP: Int
var currentHP: Int
var maxMP: Int
var currentMP: Int
var currentLVL: Int
var damageATT: Int
}

struct Enemy {
var maxHP: Int
var currentHP: Int
var damageAtt: Int
}

var alexRider = Player(maxHP: 100, currentHP: 100, maxMP: 100, currentMP: 100, currentLVL: 1, damageATT: 5)
var enemyOne = Enemy(maxHP: 20, currentHP: 20, damageAtt: 2)
var enemyTwo = Enemy(maxHP: 40, currentHP: 40, damageAtt: 4)

func attackTarget(attacker player: Player, enemy target: Enemy) {
var attackTAR = target
attackTAR.currentHP -= player.damageATT
print("Dealt (player.damageATT) damage!")
print("Enemy now has (attackTAR.currentHP) health remaining")
}

attackTarget(attacker: alexRider, enemy: enemyTwo)
print(enemyTwo.currentHP)


Obviously, when I print the currentHP at the end of the code, its the same as it started since the scope of the variables inside the function do not pass outside. The print commands inside the function work fine to show the damage amount and remaining HP of the instance inside.



Is there something simple I am missing here? Again I know this should be something simple, but just getting started with this I was hoping someone could point me in the right direction.



Thanks.







swift function variables






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 19 at 2:52









QuantamPulseQuantamPulse

1




1













  • Don't do var attackTar = target then using attackTar. Here, you create a new variable with new memory and allocate space as a different object. Simply do target.currentHP -= player.damageATT. Don't expect to create a new object and it reference an older object.

    – impression7vx
    Jan 19 at 2:55











  • I tried that initially and get an error message that the Left side of mutating operator isn't mutable: 'target' is a 'let' constant.

    – QuantamPulse
    Jan 19 at 3:00











  • This is something that will be covered later in the tutorial.

    – Josh Caswell
    Jan 19 at 3:15






  • 1





    Use classes instead of structs

    – Carpsen90
    Jan 19 at 10:28



















  • Don't do var attackTar = target then using attackTar. Here, you create a new variable with new memory and allocate space as a different object. Simply do target.currentHP -= player.damageATT. Don't expect to create a new object and it reference an older object.

    – impression7vx
    Jan 19 at 2:55











  • I tried that initially and get an error message that the Left side of mutating operator isn't mutable: 'target' is a 'let' constant.

    – QuantamPulse
    Jan 19 at 3:00











  • This is something that will be covered later in the tutorial.

    – Josh Caswell
    Jan 19 at 3:15






  • 1





    Use classes instead of structs

    – Carpsen90
    Jan 19 at 10:28

















Don't do var attackTar = target then using attackTar. Here, you create a new variable with new memory and allocate space as a different object. Simply do target.currentHP -= player.damageATT. Don't expect to create a new object and it reference an older object.

– impression7vx
Jan 19 at 2:55





Don't do var attackTar = target then using attackTar. Here, you create a new variable with new memory and allocate space as a different object. Simply do target.currentHP -= player.damageATT. Don't expect to create a new object and it reference an older object.

– impression7vx
Jan 19 at 2:55













I tried that initially and get an error message that the Left side of mutating operator isn't mutable: 'target' is a 'let' constant.

– QuantamPulse
Jan 19 at 3:00





I tried that initially and get an error message that the Left side of mutating operator isn't mutable: 'target' is a 'let' constant.

– QuantamPulse
Jan 19 at 3:00













This is something that will be covered later in the tutorial.

– Josh Caswell
Jan 19 at 3:15





This is something that will be covered later in the tutorial.

– Josh Caswell
Jan 19 at 3:15




1




1





Use classes instead of structs

– Carpsen90
Jan 19 at 10:28





Use classes instead of structs

– Carpsen90
Jan 19 at 10:28












1 Answer
1






active

oldest

votes


















1














So, in Swift we can still pass by reference. This allows it to where our parameters are changeable because in the default case, such as yours, they are let variables and not mutable.



What we can do is,



attackTarget(attacker: alexRider, enemy: &enemyTwo)


as well as,



func attackTarget(attacker player: Player, enemy target: inout Enemy) {


You can see here, inout is similar to that of pass by reference variable in C, we just have to make it known to the Swift compiler. This will allow your variable to have variables of its own changed.






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%2f54263692%2fswift-4-how-to-have-a-function-set-a-variable-outside-that-function%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    So, in Swift we can still pass by reference. This allows it to where our parameters are changeable because in the default case, such as yours, they are let variables and not mutable.



    What we can do is,



    attackTarget(attacker: alexRider, enemy: &enemyTwo)


    as well as,



    func attackTarget(attacker player: Player, enemy target: inout Enemy) {


    You can see here, inout is similar to that of pass by reference variable in C, we just have to make it known to the Swift compiler. This will allow your variable to have variables of its own changed.






    share|improve this answer




























      1














      So, in Swift we can still pass by reference. This allows it to where our parameters are changeable because in the default case, such as yours, they are let variables and not mutable.



      What we can do is,



      attackTarget(attacker: alexRider, enemy: &enemyTwo)


      as well as,



      func attackTarget(attacker player: Player, enemy target: inout Enemy) {


      You can see here, inout is similar to that of pass by reference variable in C, we just have to make it known to the Swift compiler. This will allow your variable to have variables of its own changed.






      share|improve this answer


























        1












        1








        1







        So, in Swift we can still pass by reference. This allows it to where our parameters are changeable because in the default case, such as yours, they are let variables and not mutable.



        What we can do is,



        attackTarget(attacker: alexRider, enemy: &enemyTwo)


        as well as,



        func attackTarget(attacker player: Player, enemy target: inout Enemy) {


        You can see here, inout is similar to that of pass by reference variable in C, we just have to make it known to the Swift compiler. This will allow your variable to have variables of its own changed.






        share|improve this answer













        So, in Swift we can still pass by reference. This allows it to where our parameters are changeable because in the default case, such as yours, they are let variables and not mutable.



        What we can do is,



        attackTarget(attacker: alexRider, enemy: &enemyTwo)


        as well as,



        func attackTarget(attacker player: Player, enemy target: inout Enemy) {


        You can see here, inout is similar to that of pass by reference variable in C, we just have to make it known to the Swift compiler. This will allow your variable to have variables of its own changed.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 19 at 3:10









        impression7vximpression7vx

        4501936




        4501936






























            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%2f54263692%2fswift-4-how-to-have-a-function-set-a-variable-outside-that-function%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

            Liquibase includeAll doesn't find base path

            How to use setInterval in EJS file?

            Petrus Granier-Deferre