仅在条件满足时创建实例

时间:2018-06-29 09:00:32

标签: arrays object swift4 instance

我正在Swift 4中创建一个程序,该程序具有两个类StockHolding(Parent)和ForeignStockHolding(Child)。我需要创建这些类的一些对象,并将它们添加到我手动执行的数组中,如下所示:

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)

下一部分是询问用户他想要多少股票以及哪种类型(StockHolding或ForeignStockHolding),并且根据选择,我需要创建对象并将其附加到数组中。我正在尝试执行以下操作,但由于对象尚未处于创建状态而无法创建对象,因此无法正常工作。

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()
        }
    }

我什至不知道我做错了什么

1 个答案:

答案 0 :(得分:0)

我认为,如果您使用父类在条件之外声明变量,它应该会起作用,

void rtree_within() {

  typedef bgm::point< double, 2, bg::cs::cartesian > point;
  typedef bgm::box<point> box;
  typedef bgm::linestring<point> line;
  typedef bgm::polygon<point> polygon;

  typedef std::pair<box, unsigned> value;

  bgi::rtree<value, bgi::quadratic<16> > rtree;
  std::vector<value> result_s;

  polygon poly1;
  polygon poly2;
  line line1;

  bg::read_wkt("POLYGON((0 0,0 1,1 1,1 0,0 0))", poly1);
  bg::read_wkt("POLYGON((0 0,0 3,3 3,3 0,0 0))", poly2);
  bg::read_wkt("LINESTRING(1 1, 2 2)", line1);

  std::cout << "line2 in poly1: " << bg::within(line1, poly1) << std::endl;
  std::cout << "line2 in poly3: " << bg::within(line1, poly2) << std::endl;

  // boxes to insert into rtree
  box poly_box1 = bg::return_envelope<box>( poly1 );
  rtree.insert(std::make_pair(poly_box1, 0));

  box poly_box2 = bg::return_envelope<box>( poly2 );
  rtree.insert(std::make_pair(poly_box2, 2));

  // box around the line
  box line_box1 = bg::return_envelope<box>( line1 );

  std::cout << "poly_box1: " << bg::wkt( poly_box1 ) << std::endl; // returns 0
  std::cout << "poly_box2: " << bg::wkt( poly_box2 ) << std::endl; // returns 1
  std::cout << "line_box1: " << bg::wkt( line_box1 ) << std::endl;

  rtree.query(bgi::within( line_box1 ), std::back_inserter( result_s ));
  std::cout << "line_box1 within rtree - size: " << result_s.size() << std::endl;
  // result_s is empty (size == 0)

}