0

I defined a member instance frameCount which type is Int!, But when I reference it in block it's type become Int?. If I doesn't unwrap it Xcode will prompt complie error "Value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'?".

I can use it without unwrapping out of block.

//Without unwrapping
self.frameCount = self.frameCount + 1
optQueue.async { [weak self] in
    //frameCount become Int?.
    //If I doesn't unwrap it Xcode will prompt complie error "Value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'?"
    self?.frameCount = (self?.frameCount)! + 1;
}
4
  • 2
    not the frameCount is Int?, but self?.frameCount is. Commented Aug 30, 2018 at 14:10
  • It's not solves your problem, but you should read this and restrain from using IUO. Commented Aug 30, 2018 at 14:12
  • 1
    If async is a GCD API [weak self] is pointless. GCD dispatch queues don't cause retain cycles. And don't misuse IUO. Commented Aug 30, 2018 at 14:26
  • 1
    And why not self?.frameCount += 1 Commented Aug 30, 2018 at 14:27

3 Answers 3

3

Your variable is not optional! Your self is. Since you are doing an asynchronous call, by the time completion is executed self might cease to exist. That is why you are capturing it as weak. But if you want it run compulsorily, you could remove the [weak self], but it will hold a strong reference to self and prevent it form being deallocated. So if your completion is not called, it'll never get deallocated.

Sign up to request clarification or add additional context in comments.

Comments

2

Here self is optional not frameCount , you can use guard to avoid this as you may have a lot of stuff that need to access self instead of force-unwrapping them all

optQueue.async { [weak self] in
   guard let strongSelf = self else { return }
   strongSelf.frameCount += 1
}

Comments

1

Also you can replace weak self with unowned self, so you will still have a weak reference to self, but not optional one.
However, be careful with that approach, it could lead to a crash if self will be deallocated earlier than completion will be executed.

optQueue.async { [unowned self] in
    self.frameCount = self.frameCount + 1
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.