Quite new to Swift : can't get my classes to interact - swift

I have this code:
class Lion
{
var name:String = "Default"
var isAlive : Bool = false
func eat(cow:Cow)
{
cow.isAlive = false
print("Cow \(cow) was eaten by \(name)")
}
}
var lion1 = Lion()
lion1.name = "Mufasa"
lion1.isAlive = true
var lion2 = Lion()
lion1.name = "Simba"
lion1.isAlive = true
var lion3 = Lion()
lion1.name = "Scar"
lion1.isAlive = true
class Cow
{
var name:String = "Default"
var isAlive : Bool = false
func giveMilk ()
{
print("cow \(name) is now giving milk")
}
func die ()
{
print("Cow \(name) is now dead")
}
}
var cow1 = Cow()
cow1.name = "Moo1"
cow1.isAlive = true
var cow2 = Cow()
cow2.name = "Moo2"
cow2.isAlive = true
var cow3 = Cow()
cow3.name = "Moo3"
cow3.isAlive = true
var cow4 = Cow()
cow4.name = "Moo4"
cow4.isAlive = true
var cow5 = Cow()
cow5.name = "Moo5"
cow5.isAlive = true
var cow6 = Cow()
cow6.name = "Moo6"
cow6.isAlive = true
var cow7 = Cow()
cow7.name = "Moo7"
cow7.isAlive = true
var cow8 = Cow()
cow8.name = "Moo8"
cow8.isAlive = true
var cow9 = Cow()
cow9.name = "Moo9"
cow9.isAlive = true
var cow10 = Cow()
cow10.name = "Moo10"
cow10.isAlive = true
class Cat
{
var name:String = "Default"
func eatMouse (mouse : Mouse)
{
print("Mouse \(mouse) was eaten")
}
func getMilk (cow:Cow)
{
if cow.isAlive == true
{
cow.giveMilk()
}else{
print("A dead cow cannot provide milk")
}
}
}
var cat1 = Cat()
cat1.name = "Meow1"
var cat2 = Cat()
cat2.name = "Meow2"
class Mouse
{
var name:String = "Default"
func die ()
{
print("Mouse \(name) is dead")
}
}
var mouse1 = Mouse()
mouse1.name = "Micky"
var mouse2 = Mouse()
mouse2.name = "Mini"
var mouse3 = Mouse()
mouse3.name = "Rattata"
var mouse4 = Mouse()
mouse4.name = "Splinter"
When I run via Xcode , it tells me Cow, Mouse and Cat are "Use of undeclared type "class name" .
For the life of me, I can't figure it out ( Quite new so don't bash me).
After establishing the classes I am supposed to have the system run several different scenarios where mouse is dead, cat eats mouse, lion eats cow etc'.

This works. Try to move class definitions ahead of others.
class Mouse
{
var name:String = "Default"
func die ()
{
print("Mouse \(name) is dead")
}
}
class Cow
{
var name:String = "Default"
var isAlive : Bool = false
func giveMilk ()
{
print("cow \(name) is now giving milk")
}
func die ()
{
print("Cow \(name) is now dead")
}
}
class Lion
{
var name:String = "Default"
var isAlive : Bool = false
func eat(cow:Cow)
{
cow.isAlive = false
print("Cow \(cow) was eaten by \(name)")
}
}
var lion1 = Lion()
lion1.name = "Mufasa"
lion1.isAlive = true
var lion2 = Lion()
lion1.name = "Simba"
lion1.isAlive = true
var lion3 = Lion()
lion1.name = "Scar"
lion1.isAlive = true
var cow1 = Cow()
cow1.name = "Moo1"
cow1.isAlive = true
var cow2 = Cow()
cow2.name = "Moo2"
cow2.isAlive = true
var cow3 = Cow()
cow3.name = "Moo3"
cow3.isAlive = true
var cow4 = Cow()
cow4.name = "Moo4"
cow4.isAlive = true
var cow5 = Cow()
cow5.name = "Moo5"
cow5.isAlive = true
var cow6 = Cow()
cow6.name = "Moo6"
cow6.isAlive = true
var cow7 = Cow()
cow7.name = "Moo7"
cow7.isAlive = true
var cow8 = Cow()
cow8.name = "Moo8"
cow8.isAlive = true
var cow9 = Cow()
cow9.name = "Moo9"
cow9.isAlive = true
var cow10 = Cow()
cow10.name = "Moo10"
cow10.isAlive = true
class Cat
{
var name:String = "Default"
func eatMouse (mouse : Mouse)
{
print("Mouse \(mouse) was eaten")
}
func getMilk (cow:Cow)
{
if cow.isAlive == true
{
cow.giveMilk()
}else{
print("A dead cow cannot provide milk")
}
}
}
var cat1 = Cat()
cat1.name = "Meow1"
var cat2 = Cat()
cat2.name = "Meow2"
var mouse1 = Mouse()
mouse1.name = "Micky"
var mouse2 = Mouse()
mouse2.name = "Mini"
var mouse3 = Mouse()
mouse3.name = "Rattata"
var mouse4 = Mouse()
mouse4.name = "Splinter"

Related

iOS - UI Label Not Updating

I am trying to build a weather app with AlamoFire and i am getting the JSON Response as expected but when i am trying to update the date to UI Label, my variable is returning a nil. if anyone get a chance to let me know where i am going wrong
import UIKit
class WeatherVC: UIViewController {
#IBOutlet weak var dateLbl: UILabel!
#IBOutlet weak var weatherType: UILabel!
#IBOutlet weak var cityname: UILabel!
#IBOutlet weak var currentTemp: UILabel!
var weatherConstants = WeatherConstant()
override func viewDidLoad() {
super.viewDidLoad()
// updateUI()
//
weatherConstants.downloadCurrentWeather {
self.updateUI()
}
weatherConstants = WeatherConstant()
print(Current_Weather_Url)
}
func updateUI() {
weatherType.text = weatherConstants.weatherType
cityname.text = weatherConstants.cityName
print("current city name is \(weatherConstants.weatherType)")
}
}
Weather Constants
import UIKit
import Alamofire
class WeatherConstant {
var _cityName :String!
var _currentTemp : Double!
var _weatherType : String!
var _highTemp : String!
var _date :String!
var cityName :String {
if _cityName == nil {
_cityName = ""
}
return _cityName
}
var currentTemp : Double{
if _currentTemp == nil {
_currentTemp = 0.0
}
return _currentTemp
}
var weatherType : String {
if _weatherType == nil {
_weatherType = ""
}
return _weatherType
}
var highTemp : String {
if _highTemp == nil {
_highTemp = ""
}
return _highTemp
}
var date : String {
if _date == nil {
_date = ""
}
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .none
let currentDate = dateFormatter.string(from: Date())
self._date = "Today, \(currentDate)"
return _date
}
//func downloadWeatherDetails(completed : DownloadComplete) ===> downloadWeatherDetails(completed : #escaping DownloadComplete)
func downloadCurrentWeather(completed: #escaping DownloadComplete) {
Alamofire.request(Current_Weather_Url).responseJSON{ response in
let result = response.result
// print(result)
debugPrint(result)
if let dict = result.value as? Dictionary<String, AnyObject>{
if let name = dict["name"] as? String {
self._cityName = name
print("current name is \(self._cityName)")
}
if let currentTemp = dict["weather"] as? [Dictionary<String, AnyObject>] {
if let main = currentTemp[0]["main"] as? String{
self._weatherType = main
print("Current Weather Type \(self._weatherType)")
}
}
}
completed()
}
}
}
JSON Response
https://samples.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=e9a34088739f38c517b4a45084f5ed82
SUCCESS: {
base = stations;
clouds = {
all = 0;
};
cod = 200;
coord = {
lat = "35.02";
lon = "139.01";
};
dt = 1485792967;
id = 1907296;
main = {
"grnd_level" = "1013.75";
humidity = 100;
pressure = "1013.75";
"sea_level" = "1023.22";
temp = "285.514";
"temp_max" = "285.514";
"temp_min" = "285.514";
};
name = Tawarano;
sys = {
country = JP;
message = "0.0025";
sunrise = 1485726240;
sunset = 1485763863;
};
weather = (
{
description = "clear sky";
icon = 01n;
id = 800;
main = Clear;
}
);
wind = {
deg = 311;
speed = "5.52";
};
}
Current Weather Type Optional("Clear")----> this the weather type i am trying to provide to UIlabel
current city name is Optional("") ------> Here i am trying to print what data is in UILabel but its returning empty string
2018-08-07 11:18:09.567868-0700 WeatherApp1.1[82321:3248301] [BoringSSL] Function boringssl_session_errorlog: line 2881 [boringssl_session_read] SSL_ERROR_ZERO_RETURN(6): operation failed because the connection was cleanly shut down with a close_notify alert
You're overwriting the weatherConstants value with a new object in viewDidLoad. Try removing that.
(Longer explanation: you're correctly creating a weatherConstants object, and asking it to fetch data. But while that's happening, you create a second instance of that object which overwrites the first. So while the first instance completes the network request and tells your UI to redraw, the UI is getting its data from the second instance of WeatherConstants)

GADInterstitial presented too often

I am having problems with my interstitial ads popping up too often. The full screen ads comes on after every game over screen, meaning each time the player loses the ad pops up which i feel will get annoying. Is there a way to stop this happening after each failure to maybe after every 2 or 3 gameovers?
I have attached my code below, any help would be greatly appreciated.
import UIKit
import AVFoundation
import GoogleMobileAds
import Social
class ViewController: UIViewController {
#IBOutlet var bannerView: GADBannerView!
var admobInterstitial : GADInterstitial?
var timerAds : NSTimer?
var player:AVAudioPlayer = AVAudioPlayer()
var score = 0
var timer = NSTimer()
var seconds = 8
var watch = true
var watch1 = true
var gameActive = true
var hiScore = 0
var counter = 1
var turn = 0
var timer_anim = NSTimer()
#IBOutlet var btn: UIButton!
#IBOutlet var scr: UILabel!
#IBOutlet var scoreLabel: UILabel!
#IBOutlet var again: UIButton!
#IBOutlet var highScore: UILabel!
#IBOutlet var gameTimer: UILabel!
#IBOutlet var startView: UIImageView!
#IBOutlet var startButton: UIButton!
#IBOutlet var game_over: UIImageView!
#IBOutlet var twBtn: UIButton!
#IBAction func twitterBtn(sender: AnyObject) {
if SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter)
{
var twShare:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
twShare.setInitialText("I dare you get a higher score than mine : ( \(score) ) GET it NOW on IOS : https://itunes.apple.com/us/app/oscar-cookie/id1099453391?mt=8")
twShare.addImage(UIImage(named: "start.png"))
self.presentViewController(twShare, animated: true, completion: nil)
}
else
{
var alert = UIAlertController(title: "Account", message: "Please login to Twitter to Tweet", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
#IBOutlet var fbBtn: UIButton!
#IBAction func facebookBtn(sender: AnyObject) {
if SLComposeViewController.isAvailableForServiceType(SLServiceTypeFacebook)
{
var fbShare:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
fbShare.setInitialText("I dare you get a higher score than mine : ( \(score) ) GET it NOW on IOS : https://itunes.apple.com/us/app/oscar-cookie/id1099453391?mt=8")
fbShare.addImage(UIImage(named: "start.png"))
self.presentViewController(fbShare, animated: true, completion: nil)
}
else
{
var alert = UIAlertController(title: "Account", message: "Please login to Facebook to share", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
#IBAction func startButtonFun(sender: AnyObject) {
startButton.hidden = true
startView.hidden = true
btn.hidden = false
player.pause()
}
#IBAction func playAgain(sender: AnyObject) {
player.pause()
//gameOverLbl.hidden = true
scoreLabel.hidden = true
again.hidden = true
btn.hidden = false
highScore.hidden = true
scr.hidden = false
game_over.hidden = true
fbBtn.hidden = true
twBtn.hidden = true
gameActive = true
watch = true
score = 0
scr.text = "0"
gameTimer.text = "8"
if watch1 == false
{
timer_anim.invalidate()
watch1 = true
}
}
#IBAction func button(sender: AnyObject) {
if score % 5 == 0
{
let audioPath = NSBundle.mainBundle().pathForResource("chew2", ofType: "mp3")!
do
{
try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath : audioPath))
player.play()
}
catch
{
}
}
else
{
let audioPath = NSBundle.mainBundle().pathForResource("chew1", ofType: "mp3")!
do
{
try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath : audioPath))
player.play()
}
catch
{
}
}
keepPlaying()
}
// func to locate the bottong randomly to all sizes
func randomLocating () {
var randomH = Int()
var randomW = Int()
if UIDevice().userInterfaceIdiom == .Phone {
switch UIScreen.mainScreen().nativeBounds.height {
case 480:
//print("iPhone Classic")
randomH = Int(arc4random_uniform(380))
randomW = Int(arc4random_uniform(260))
while randomH < 50 || randomW < 40
{
randomH = Int(arc4random_uniform(380))
randomW = Int(arc4random_uniform(260))
}
case 960:
//print("iPhone 4 or 4S")
randomH = Int(arc4random_uniform(380))
randomW = Int(arc4random_uniform(270))
while randomH < 50 || randomW < 40
{
randomH = Int(arc4random_uniform(380))
randomW = Int(arc4random_uniform(270))
}
case 1136:
// print("iPhone 5 or 5S or 5C")
randomH = Int(arc4random_uniform(520))
randomW = Int(arc4random_uniform(300))
while randomH < 40 || randomW < 40
{
randomH = Int(arc4random_uniform(520))
randomW = Int(arc4random_uniform(300))
}
case 1334:
// print("iPhone 6 or 6S")
randomH = Int(arc4random_uniform(550))
randomW = Int(arc4random_uniform(300))
while randomH < 35 || randomW < 40
{
randomH = Int(arc4random_uniform(550))
randomW = Int(arc4random_uniform(300))
}
case 2208:
// print("iPhone 6+ or 6S+")
randomH = Int(arc4random_uniform(700))
randomW = Int(arc4random_uniform(350))
while randomH < 40 || randomW < 40
{
randomH = Int(arc4random_uniform(700))
randomW = Int(arc4random_uniform(350))
}
default:
print("unknown")
}
}
else if UIDevice().userInterfaceIdiom == .Pad {
switch UIScreen.mainScreen().nativeBounds.height {
case 1024:
//print("iPad Classic")
randomH = Int(arc4random_uniform(950))
randomW = Int(arc4random_uniform(700))
while randomH < 50 || randomW < 40
{
randomH = Int(arc4random_uniform(950))
randomW = Int(arc4random_uniform(700))
}
case 2048:
//print("iPad Retina")
randomH = Int(arc4random_uniform(700))
randomW = Int(arc4random_uniform(350))
while randomH < 100 || randomW < 100
{
randomH = Int(arc4random_uniform(700))
randomW = Int(arc4random_uniform(350))
}
default:
print("unknown")
}
}
btn.frame.origin = CGPoint(x: randomW, y: randomH)
}
// func to end the game when someone loses
func endGame() {
btn.hidden = true
scoreLabel.text = "\(score)"
if hiScore < score
{
hiScore = score
highScore.text = "\(hiScore)"
}
else
{
highScore.text = "\(hiScore)"
}
NSUserDefaults.standardUserDefaults().setObject(hiScore, forKey: "high")
scoreLabel.hidden = false
again.hidden = false
highScore.hidden = false
scr.hidden = true
game_over.hidden = false
fbBtn.hidden = false
twBtn.hidden = false
let audioPath = NSBundle.mainBundle().pathForResource("end", ofType: "mp3")!
do
{
try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath : audioPath))
player.play()
}
catch
{
}
}
func animating()
{
if counter < 5
{
counter += 1
}
startView.image = UIImage(named: "start-\(counter).png")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//gameOverLbl.hidden = true
scoreLabel.hidden = true
again.hidden = true
highScore.hidden = true
btn.hidden = true
game_over.hidden = true
game_over.hidden = true
fbBtn.hidden = true
twBtn.hidden = true
if watch1 == true
{
timer_anim = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: Selector("animating"), userInfo: nil, repeats: true)
watch1 = false
}
if NSUserDefaults.standardUserDefaults().objectForKey("high") != nil
{
var returnHigh = NSUserDefaults.standardUserDefaults().objectForKey("high") as! Int
hiScore = returnHigh
}
else
{
}
let audioPath = NSBundle.mainBundle().pathForResource("start", ofType: "mp3")!
do
{
try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath : audioPath))
player.play()
}
catch
{
}
self.bannerView.adUnitID = "ca-app-pub-8964973200415729/4584433890"
self.bannerView.rootViewController = self
var request:GADRequest = GADRequest()
self.bannerView.loadRequest(request)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/// to make the screen not rotate
override func shouldAutorotate() -> Bool {
return false
}
func keepPlaying()
{
score += 1
scr.text = "\(score)"
randomLocating()
if score < 5
{
seconds = 8
}
else
{
seconds = 5
}
if watch == true
{
timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("click1"), userInfo: nil, repeats: true)
}
watch = false
gameTimer.text = "\(seconds)"
}
func click1 ()
{
gameTimer.text = "\(seconds)"
if seconds == 0 && gameActive == false
{
timer.invalidate()
endGame()
btn.hidden = true
turn += 1
if turn == 1
{
admobInterstitial = createAndLoadInterstitial()
timerAds = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector: Selector("presentInterstitial"), userInfo: nil, repeats: false)
turn = 0
}
}
else if seconds == 1
{
btn.hidden = true
gameActive = false
}
else
{
btn.hidden = false
}
seconds -= 1
}
func createAndLoadInterstitial()->GADInterstitial {
var interstitial = GADInterstitial(adUnitID: "ca-app-pub-8964973200415729/8720255492")
///interstitial.delegate = self
interstitial.loadRequest(GADRequest())
return interstitial
}
func presentInterstitial() {
if let isReady = admobInterstitial?.isReady {
admobInterstitial?.presentFromRootViewController(self)
}
}
func interstitial(ad: GADInterstitial!, didFailToReceiveAdWithError error: GADRequestError!) {
print("interstitialDidFailToReceiveAdWithError:\(error.localizedDescription)")
admobInterstitial = createAndLoadInterstitial()
}
}
Simply change your turn counter. Instead of if turn == 1 change it to something else. Want an ad every 3 gameovers? Change it to 3. For example:
turn = turn + 1
if turn == 3 {
admobInterstitial = createAndLoadInterstitial()
timerAds = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector: #selector(ViewController.presentInterstitial), userInfo: nil, repeats: false)
turn = 0
}

If statements and strings error

I Have
if rockNamesArray == "rock2" {
let firstPos: CGFloat = 300.0
UIView.animateWithDuration(3.0, animations: { () -> Void in
self.mrock.frame = CGRectMake(167, 600, CGFloat(self.mrock.bounds.size.width), CGFloat(self.mrock.bounds.size.height))
})}
as well as
var rockNamesArray:[String ] = ["bird", "rock2", "rock3"]
var rockpos = Int(arc4random_uniform(UInt32(3)))
var firstrockString:String = rockNamesArray[rockpos]
But its telling me I can't use "==" for the if statement. What would I use in place for it. "rock2" is a string
If you want to check if "rock2" is inside the array:
if contains(rockNamesArray, "rock2") {
// Do your stuff
}
Or if you want to check a certain index of the array and compare it to "rock2" with n being the index:
var rockNamesArray:[String ] = ["bird", "rock2", "rock3"]
var rockpos = Int(arc4random_uniform(UInt32(3)))
if rockNamesArray[rockpos] == "rock2" {
let firstPos: CGFloat = 300.0
UIView.animateWithDuration(3.0) {
self.mrock.frame = CGRectMake(167, 600, CGFloat(self.mrock.bounds.size.width), CGFloat(self.mrock.bounds.size.height))
}
}

How to list all Variables of a class in swift

Is there a way to list all Variables of a class in Swift?
For example:
class foo {
var a:Int? = 1
var b:String? = "John"
}
I want to list it like this: [a:1, b:"John"]
How you can do it in Swift 3.0 recursively:
import Foundation
class FirstClass {
var name = ""
var last_name = ""
var age = 0
var other = "abc"
func listPropertiesWithValues(reflect: Mirror? = nil) {
let mirror = reflect ?? Mirror(reflecting: self)
if mirror.superclassMirror != nil {
self.listPropertiesWithValues(reflect: mirror.superclassMirror)
}
for (index, attr) in mirror.children.enumerated() {
if let property_name = attr.label {
//You can represent the results however you want here!!!
print("\(mirror.description) \(index): \(property_name) = \(attr.value)")
}
}
}
}
class SecondClass: FirstClass {
var yetAnother = "YetAnother"
}
var second = SecondClass()
second.name = "Name"
second.last_name = "Last Name"
second.age = 20
second.listPropertiesWithValues()
results:
Mirror for FirstClass 0: name = Name
Mirror for FirstClass 1: last_name = Last Name
Mirror for FirstClass 2: age = 20
Mirror for FirstClass 3: other = abc
Mirror for SecondClass 0: yetAnother = YetAnother
The following should use reflection to generate the list of members and values. See fiddle at http://swiftstub.com/836291913/
class foo {
var a:Int? = 1
var b:String? = "John"
}
let obj = foo()
let reflected = reflect(obj)
var members = [String: String]()
for index in 0..<reflected.count {
members[reflected[index].0] = reflected[index].1.summary
}
println(members)
Output:
[b: John, a: 1]
Maybe a bit late for the party, but this solution using reflection and Mirror is 100% working:
class YourClass : NSObject {
var title:String
var url:String
...something other...
func properties() -> [[String: Any]] {
let mirror = Mirror(reflecting: self)
var retValue = [[String:Any]]()
for (_, attr) in mirror.children.enumerated() {
if let property_name = attr.label as String! {
retValue.append([property_name:attr.value])
}
}
return retValue
}
}
and somewhere in your code...
var example = MoreRow(json: ["title":"aTitle","url":"anURL"])
print(example.listPropertiesWithValues())
I got clue from here. https://medium.com/#YogevSitton/use-auto-describing-objects-with-customstringconvertible-49528b55f446
This is a demo above Swift 4.0.
import Foundation
extension CustomStringConvertible {
var description : String {
var description: String = ""
if self is AnyObject { // unsafeAddressOf((self as! AnyObject))
description = "***** \(type(of: self)) - <\(Unmanaged.passUnretained(self as AnyObject).toOpaque())>***** \n"
} else {
description = "***** \(type(of: self)) *****\n"
}
let selfMirror = Mirror(reflecting: self)
for child in selfMirror.children {
if let propertyName = child.label {
description += "\(propertyName): \(child.value)\n"
}
}
return description
}
}
extension NSObject {
var description: String {
var description: String = ""
if self is AnyObject { // unsafeAddressOf((self as! AnyObject))
description = "***** \(type(of: self)) - <\(Unmanaged.passUnretained(self as AnyObject).toOpaque())>***** \n"
} else {
description = "***** \(type(of: self)) *****\n"
}
let selfMirror = Mirror(reflecting: self)
for child in selfMirror.children {
if let propertyName = child.label {
description += "\(propertyName): \(child.value)\n"
}
}
return description
}
}
class AA: CustomStringConvertible {
var a: String = "aaa"
}
class BB: NSObject {
var b: String = "bbb"
}
let aa = AA()
print(aa)
let bb = BB()
print(bb.description)
Output --
***** AA - <0x00000001001038e0>*****
a: aaa
***** BB - <0x0000000100103310>*****
b: bbb

How do I make a group of functions loop swift SpriteKit

My problem is I am trying to make all the bar6s to move down to the bottom of the screen, similar to flappy bird. I've done most of it, what I've done is make the bars go
down but I want to make it go on forever but only 5 bars go down how can I make it go on forever like regenerate or can you make a completion block in the function while you declare it.
Here is my code:
//
// PlaysScene.swift
// Pocket Rocket3
//
// Created by Lucas Farleigh on 27/11/2014.
// Copyright (c) 2014 Lucas Farleigh. All rights reserved.
//
import spriteKit
class PlayScene:SKScene {
//declaring the node in this scene!
let background = SKSpriteNode(imageNamed: "background")
let bar1 = SKSpriteNode(imageNamed:"bar1")
let bar2 = SKSpriteNode(imageNamed:"bar2")
let bar3 = SKSpriteNode(imageNamed:"bar3")
let bar4 = SKSpriteNode(imageNamed:"bar4")
let bar5 = SKSpriteNode(imageNamed:"bar5")
let bar6a = SKSpriteNode(imageNamed: "bar6")
let bar6b = SKSpriteNode(imageNamed: "bar6")
let bar6c = SKSpriteNode(imageNamed: "bar6")
let bar6d = SKSpriteNode(imageNamed: "bar6")
let bar6e = SKSpriteNode(imageNamed: "bar6")
let bar6f = SKSpriteNode(imageNamed: "bar6")
let bar6g = SKSpriteNode(imageNamed: "bar6")
let bar6h = SKSpriteNode(imageNamed: "bar6")
let bar6i = SKSpriteNode(imageNamed: "bar6")
let bar6j = SKSpriteNode(imageNamed: "bar6")
//making actions
override func didMoveToView(view: SKView) {
var check1 = false
var check2 = false
var check3 = false
var check4 = false
var check5 = false
var delayA = SKAction.waitForDuration(NSTimeInterval(1.5))
var delayB = SKAction.waitForDuration(NSTimeInterval(2))
var delayC = SKAction.waitForDuration(NSTimeInterval(4))
var delayD = SKAction.waitForDuration(NSTimeInterval(6))
var delayE = SKAction.waitForDuration(NSTimeInterval(8))
var actionmove = SKAction.moveToY(0, duration: 15)
var delay = SKAction.waitForDuration(NSTimeInterval(1.5))
var sequence = SKAction.sequence([ delay , actionmove])
var delchild = SKAction.removeFromParent()
func f1 () {
bar6a.position = CGPointMake(800 ,CGRectGetMaxY(self.frame))
bar6b.position = CGPointMake(1600,CGRectGetMaxY(self.frame))
check1 = false
bar6a.runAction(actionmove)
bar6b.runAction(actionmove,completion: {
self.bar6a.position = CGPointMake(800 ,CGRectGetMaxY(self.frame))
self.bar6b.position = CGPointMake(1600,CGRectGetMaxY(self.frame))
check1 = true
self.bar6a.runAction(actionmove)
self.bar6b.runAction(actionmove,completion: {
self.bar6a.removeFromParent()
self.bar6b.removeFromParent()
check1 = true
})
})
actionmove.timingMode = SKActionTimingMode.EaseOut
}
var sequence2 = SKAction.sequence([ delayB ,actionmove])
var sequence3 = SKAction.sequence([ delayC ,actionmove])
var sequence4 = SKAction.sequence([ delayD ,actionmove])
var sequence5 = SKAction.sequence([delayE , actionmove])
bar6a.xScale = 2.5
bar6b.xScale = 2.5
bar6c.xScale = 2.5
bar6d.xScale = 2.5
bar6e.xScale = 2.5
bar6f.xScale = 2.5
bar6g.xScale = 2.5
bar6h.xScale = 2.5
bar6i.xScale = 2.5
bar6j.xScale = 2.5
//making the actions
var num1 = 1
//making different delays
//sequence actions
addChild(bar6a)
addChild(bar6b)
addChild(bar6c)
addChild(bar6d)
addChild(bar6e)
addChild(bar6f)
addChild(bar6g)
addChild(bar6h)
addChild(bar6i)
addChild(bar6j)
//making the functions
func f2 () {
check2 = false
bar6c.position = CGPointMake(400 ,CGRectGetMaxY(self.frame))
bar6d.position = CGPointMake(1200,CGRectGetMaxY(self.frame))
bar6d.runAction(sequence2)
bar6c.runAction(sequence2, completion:{
self.bar6c.removeFromParent()
self.bar6d.removeFromParent()
check2 = true
})
bar6d.runAction(sequence2)
}
func f3 () {
check3 = false
bar6e.position = CGPointMake(600 ,CGRectGetMaxY(self.frame))
bar6f.position = CGPointMake(1400,CGRectGetMaxY(self.frame))
bar6e.runAction(sequence3,completion:{
self.bar6e.removeFromParent()
self.bar6f.removeFromParent()
check3 = true
})
bar6f.runAction(sequence3)
}
func f4 () {
check4 = false
bar6g.position = CGPointMake(700 ,CGRectGetMaxY(self.frame))
bar6h.position = CGPointMake( 1500,CGRectGetMaxY(self.frame))
bar6h.runAction(sequence4)
bar6g.runAction(sequence4,completion:{
self.bar6g.removeFromParent()
self.bar6h.removeFromParent()
check4 = true
})
}
func f5 () {
check5 = false
bar6i.position = CGPointMake(700 ,CGRectGetMaxY(self.frame))
bar6j.position = CGPointMake(1500 ,CGRectGetMaxY(self.frame))
bar6j.runAction(sequence5)
bar6i.runAction(sequence5,completion:{
check5 = true
self.bar6i.removeFromParent()
self.bar6j.removeFromParent()
})
}
f1()
f2()
f3()
f4()
f5()
//making the action repeat forever
var num2 = 1
bar1.position = CGPointMake(CGRectGetMidX(self.frame),CGRectGetMaxY (self.frame))
bar2.position = CGPointMake(CGRectGetMidX(self.frame),CGRectGetMaxY (self.frame))
bar3.position = CGPointMake(CGRectGetMidX(self.frame),CGRectGetMaxY (self.frame))
bar4.position = CGPointMake(CGRectGetMidX(self.frame),CGRectGetMaxY (self.frame))
bar5.position = CGPointMake(CGRectGetMidX(self.frame),CGRectGetMaxY (self.frame))
bar1.xScale = 2.5
bar2.xScale = 2.5
bar3.xScale = 2.5
bar4.xScale = 2.5
bar5.xScale = 1.7
/*
bar1.runAction(sequence, completion: {
self.bar2.runAction(sequence, completion: {
self.bar3.runAction(sequence, completion:{
self.bar4.runAction(sequence, completion:{
self.bar5.runAction(sequence)
})
})
})
})*/
background.position = CGPointMake(CGRectGetMidX(self.frame),CGRectGetMidY(self.frame))
//doing the background stuff
background.yScale = 2.0
background.xScale = 3.0
addChild(background)
//doing the the bar stuff
if check1 == true{
f1()
}
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
}
}
EDIT: I see that you are trying to do this similar to flappy bird now. I would suggest doing either an SKPhysicsNode with spritekit or attempting to use Cocos2d http://www.cocos2d-x.org/wiki/Physics