nainsi gupta
nainsi gupta

Reputation: 163

Bool Value not work in Swift

I want to animated my button up and down. When I am using Objective-C it works, but, when I am using Swift the bool value shows nil instead of false or true. I am new to Swift. Please help.

class ViewController: UIViewController,ABPeoplePickerNavigationControllerDelegate {
    @IBOutlet var dd:UIButton!
    var isShown:Bool?
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
@IBAction func touch()
{
println(self.isShown)
    if (self.isShown==false)
    {
    UIView.animateWithDuration(0.5, animations: { () -> Void in
        self.dd.frame=CGRectMake(35.0, 60, self.dd.frame.size.width, self.dd.frame.size.height)
       self.isShown=true
    })
    }
        else
        {
            UIView.animateWithDuration(0.5, animations: { () -> Void in
                self.dd.frame=CGRectMake(55.0, 130, self.dd.frame.size.width, self.dd.frame.size.height)
                self.isShown=false
            })
        }

    }

Upvotes: 2

Views: 5773

Answers (4)

whyceewhite
whyceewhite

Reputation: 6425

You wrote:

var isShown:Bool?

As a result of the statement above, the isShown variable is an optional Bool because there is an ? following the Bool. This means that your isShown property may be nil or it may have a value.

However, in your code, the isShown property is not initialized to any value. Realize that Swift does not default the Bool to false like some other languages. As a result, you have to explicitly set the value of your isShown property to avoid it from being nil.

For example, you can do the following to initialize your property when it is declared:

class ViewController: UIViewController,ABPeoplePickerNavigationControllerDelegate {
    @IBOutlet var dd:UIButton!
    var isShown:Bool = false
    ...
}

You may also handle the initialization in other ways (for example, by assigning the value in the viewDidLoad function).

Read about Swift Optionals since the concept does not exist in Objective C and it will help you understand how to handle your property.

Upvotes: 5

Bharat Nakum
Bharat Nakum

Reputation: 647

You should directly initialized bool with value false.

Like this :-

var isShown : Bool = false

Hope this helps.

Upvotes: 0

Pradumna Patil
Pradumna Patil

Reputation: 2220

You haven't set bool value set bool value before using it.

Upvotes: 0

Memon Irshad
Memon Irshad

Reputation: 972

Initialize bool variable in viewDidLoad

isShown = true

Upvotes: 0

Related Questions