Q: Creating an Instance only if the Condition Satisfies I am creating a program in Swift 4 which has two Classes StockHolding(Parent) and ForeignStockHolding(Child). I need to create some objects of these classes and add them to an array which I did manually like this:
var stocksInArray: [StockHolding] = [] //creating array of type StockHolding
var newSIA = StockHolding()

//=========New StockHolding Object===========
    **newSIA = StockHolding()**
    newSIA.purchaseSharePrice = 2
    newSIA.currentSharePrice = 3
    newSIA.numberOfShares = 5
    newSIA.companyName = "A"

    //Appending the Array
    stocksInArray.append(newSIA)

//=========New ForeignStockHolding Object===========
    **newSIA = ForeignStockHolding()**
    newSIA.purchaseSharePrice = 6.10
    newSIA.currentSharePrice = 99.51
    newSIA.numberOfShares = 310
    newSIA.companyName = "D"

    //Appending the Array
    stocksInArray.append(newSIA)

The next part is to ask the user how many stocks he wants and of which type (StockHolding or ForeignStockHolding) and according to the choice I need to create the object and append that to an array. I was trying to do the following but it is not working as the objects are not yet created because they are within the condition and I am getting errors.
for stocks in 1...maxVal {
        print("Type of stock \(stocks): 1.Local  2.Foreign " )

        input = readLine()!
        let s1 = Int(input)!

        if(s1 == 1){  var newSIA = StockHolding()
            runOnCondition()
        }
        else if (s1 == 2){ var newSIA = ForeignStockHolding()
            print("Enter Conversion Rate")
            input = readLine()!
            let cr = Float(input)!
            newSIA.conversionRate = cr
            runOnCondition()
        }
    }

I don't even know if I am doing it all wrong

A: I think it should work if you declare the variable outside the conditions using the parent class, like this:
for stocks in 1...maxVal {
    print("Type of stock \(stocks): 1.Local  2.Foreign " )

    input = readLine()!
    let s1 = Int(input)!
    var newSIA: StockHolding

    if(s1 == 1){  newSIA = StockHolding()
        runOnCondition()
    }
    else if (s1 == 2){ newSIA = ForeignStockHolding()
        print("Enter Conversion Rate")
        input = readLine()!
        let cr = Float(input)!
        newObj.conversionRate = cr
        runOnCondition()
    }
}

