i ask how corret issue. append "portals" depending country. each "portal" comes more once, dont want append.
i have following class definitions:
class cls_main{ var countries:[cls_country]! init() { countries = [cls_country]() } // "add country" func addcountry(icountry:cls_country) { countries.append(icountry) } } class cls_country{ var countryname:string! var portals:[cls_portal]! init() { portals = [cls_portal]() } // "add portal" func addportal(portname:string) { var tmpportal = cls_portal() tmpportal.portalname = portname println("-->input portal: \(tmpportal.portalname)") if portals.count == 0 { portals.append(tmpportal) } else { port in portals { if port.portalname == portname { println("same input, dont save") } else { portals.append(tmpportal) } } } } func arraycount(){ println("portals : \(portals.count)") } } class cls_portal{ var portalname:string! }
and call it:
var main = cls_main() var country = cls_country() country.countryname = "usa" country.addportal("dance") country.addportal("dance") // should not appended... country.addportal("hike") country.addportal("swim") country.addportal("play") main.addcountry(country) country = cls_country()
after adding values im looping on values , print them. result this:
loop:
for country in main.countries { println("country: \(country.countryname)") if country.countryname == "usa" { portal in country.portals { println(" -> portal : \(portal.portalname)") } country.arraycount() } }
result:
-->input portal: dance -->input portal: dance same input, dont save -->input portal: hike -->input portal: swim -->input portal: play country: usa -> portal : dance -> portal : hike -> portal : swim -> portal : swim -> portal : play -> portal : play -> portal : play -> portal : play portals : 8
so why every , each portal multiplying @ end? thank much.
in search loop, deciding after looking @ each element whether tmpportal
in portals
or not. need potentially @ of items before can make decision. add variable found
note has been found. can break
out of loop once you've found item.
if portals.count == 0 { portals.append(tmpportal) } else { var found = false port in portals { if port.portalname == portname { println("same input, dont save") found = true // found it, stop searching break } } if !found { portals.append(tmpportal) } }
Comments
Post a Comment