S. Eberl S. Eberl - 3 months ago 26
iOS Question

Expected declaration error in Swift.

import UIKit

class ViewController: UIViewController {

let time = NSDate();

@IBOutlet weak var DateLabel: UILabel!

func changeToActualDate() -> String {
NSDateFormatter().dateFormat = "dd-MM";
var formatteddate = NSDateFormatter().stringFromDate(time);
DateLabel.text = formatteddate;
}

changeToActualDate();
}


I'm trying to get the date and I want to use it in a label (iOS-Application). Whenever I try to use the function 'changeToActualDate();', I get the follow error:


Expected declaration


It's probably a dumb, beginner question. But what am I doing wrong?

Answer

Just call your function in viewWillAppear(animated:Bool)() or viewDidLoad()

import UIKit

class ViewController: UIViewController {

let time = NSDate();

@IBOutlet weak var DateLabel: UILabel!

override func viewWillAppear(animated:Bool)(){

      super.viewWillAppear(animated:Bool)
      changeToActualDate()
    }

func changeToActualDate() -> String {
    NSDateFormatter().dateFormat = "dd-MM";
    var formatteddate = NSDateFormatter().stringFromDate(time);
    DateLabel.text = formatteddate;
  }
}