How do I check if UIImage is empty in swift? - ios

This is my code but it seems the conditional "if" check for UIImage being empty is not executing. Is it the wrong way of checking if UIImage is empty? I have also tried
if allStyleArrays[i][ii][iii] as UIImage? == nil {
...
}
And not working, please if none of those methods checks, what is the correct way?
Thanks.
Code:
for var i = 0; i <= allStyleArrays.count; i++ {
if i == allStyleArrays.count {
self.performSegueWithIdentifier("toStylistReviewAndConfirm", sender: self)
} else {
for var ii = 0; ii < allStyleArrays[i].count; ii++ {
for var iii = 0; iii < allStyleArrays[i][ii].count; iii++ {
if allStyleArrays[i][ii][iii] as UIImage? == UIImage(named: "") {
} else {
switch i {
case 0:
styleN[0].append(allStyleArrays[i][ii][iii])
//print("style 1 \(style1.count)")
break
case 1:
styleN[1].append(allStyleArrays[i][ii][iii])
//print("style 2 \(style2.count)")
break
default:
styleN[2].append(allStyleArrays[i][ii][iii])
//print("style 3 \(style3.count)")
break
}
}
}
}
}
}

try
if allStyleArrays[i][ii][iii].imageAsset == nil

Related

Swift equivalent of this ActionScript function

I translated this tutorial on BSP into swift. In the tutorial there's this ActionScript function.
public function getRoom():Rectangle
{
// iterate all the way through these leafs to find a room, if one exists.
if (room != null)
return room;
else
{
var lRoom:Rectangle;
var rRoom:Rectangle;
if (leftChild != null)
{
lRoom = leftChild.getRoom();
}
if (rightChild != null)
{
rRoom = rightChild.getRoom();
}
if (lRoom == null && rRoom == null)
return null;
else if (rRoom == null)
return lRoom;
else if (lRoom == null)
return rRoom;
else if (FlxG.random() > .5)
return lRoom;
else
return rRoom;
}
}
I translated this function into Swift (to the best of my ability) I must have written it wrong because the function is returning a nil value when it shouldn't be.
My version in Swift:
// left/right child are initialized as follows:
// leftChild:Room?
// rightChild:Room?
public func getRoom() -> Room? {
if room != nil {
return room
} else {
var lRoom:Room?
var rRoom:Room?
if leftChild != nil {
lRoom = leftChild!.getRoom()!
}
if rightChild != nil {
rRoom = rightChild!.getRoom()!
}
if lRoom == nil && rRoom == nil {
return nil
} else if rRoom == nil {
return lRoom
} else if lRoom == nil {
return rRoom
} else if Double.random(in: 0..<1.0) > 0.5 {
return lRoom
} else {
return rRoom
}
}
}
Where Room is a basic class I made to help me handle the rooms.
class Room {
var x1:Int
var x2:Int
var y1:Int
var y2:Int
var center:CGPoint
init(X: Int, Y: Int, W: Int, H: Int) {
x1 = X
x2 = X + W
y1 = Y
y2 = Y + H
center = CGPoint(x: (x1 + x2) / 2, y: (y1 + y2) / 2)
}
}
I'm getting a nil value when I shouldn't be. I think I translated the function wrong. Rectangle would be CGRect in Swift but I replaced it with my Room class in other places in the code, so I know it'll work with the Room class here.
How would this function be written in Swift?
Your problem is that you are force unwrapping the result of getRoom - This function returns an optional and can legitimately return nil when your traversal hits a leaf node. Force unwrapping nil results in a crash
By using conditional unwrapping correctly you can not only make your code more readable, you can eliminate the crash.
public func getRoom() -> Room? {
if let _ = room {
return room
}
let lRoom = leftChild?.getRoom()
let rRoom = rightChild?.getRoom()
switch (lRoom != nil, rRoom != nil) {
case (false,false):
return nil
case (true,false):
return lRoom
case (false,true):
return rRoom
case (true,true):
return arc4random_uniform(2) == 1 ? lRoom: rRoom
}
}

UISegmentedControl and .selectedSegmentIndex wrong values?

I have a simple Segment in my code with 3 elements. For testing purposes I also do have a variable that increments based on which of the segments I press (3). The value of that variable is printed in a UITextView. This is the code:
import UIKit
class ViewController: UIViewController
{
#IBOutlet weak var segment: UISegmentedControl!
#IBOutlet weak var prwtoView: UIView!
#IBOutlet weak var prwtoText: UITextField!
var i : Int = 0
override func viewWillAppear(animated: Bool)
{
prwtoText.backgroundColor = UIColor.purpleColor()
prwtoText.textColor = UIColor.whiteColor()
segment.setTitle("Zero", forSegmentAtIndex: 0)
segment.addTarget(self, action: "action", forControlEvents: .ValueChanged)
segment.insertSegmentWithTitle("random", atIndex: 2, animated: false)
}
func action()
{
let argumentForSegment = segment.selectedSegmentIndex
if argumentForSegment == 0
{
i = 0
}
if argumentForSegment == 1
{
i += 2
}
else
{
i += Int(arc4random_uniform(100))
}
print(argumentForSegment)
prwtoText.text = "\(i)"
}
}
While I know that it starts with value -1 i don't want my app to do anything if not pressed. The thing is that even when I press the first segment (0) and it is supposed to make i = 0 it doesn't do that, although if I print argumentForSegment in my terminal it does show the 0 as value. Concluding, every time I press the zero segment (0), my i value won't become 0. Perhaps I am using the wrong method from UISegmentedControl?
edit: Got it fixed by changing the following code:
func action()
{
let argumentForSegment = segment.selectedSegmentIndex
if argumentForSegment == 0
{
i = 0
}
if argumentForSegment == 1
{
i += 2
}
else
{
i += Int(arc4random_uniform(100))
}
print(argumentForSegment)
prwtoText.text = "\(i)"
}
to:
func action()
{
let argumentForSegment = segment.selectedSegmentIndex
if argumentForSegment == 0
{
i = 0
}
if argumentForSegment == 1
{
i += 2
}
else if argumentForSegment == 2 // <==== here
{
i += Int(arc4random_uniform(100))
}
print(argumentForSegment)
prwtoText.text = "\(i)"
}
Could someone explain why it used the priority of else although the value was zero when printing argumentForSegment? In other words why when I had an else alone for the value of argumentForSegment == 0 it chose the else instead of the first statement?
Could someone explain why it used the priority of else although the
value was zero when printing argumentForSegment? In other words why
when I had an else alone for the value of argumentForSegment == 0 it
chose the else instead of the first statement?
When you have a situation where the code is not behaving as you expect, it is helpful to step through it in the debugger, or add some diagnostic print statements.
For example:
func action()
{
let argumentForSegment = segment.selectedSegmentIndex
if argumentForSegment == 0
{
print("In first block")
i = 0
}
if argumentForSegment == 1
{
print("In second block")
i += 2
}
else
{
print("In third block")
i += Int(arc4random_uniform(100))
}
print(argumentForSegment)
prwtoText.text = "\(i)"
}
If you do this, you will notice that when argumentForSegment is 0, the output will be:
In first block
In third block
So, the problem is not that it is choosing the third block over the first. The problem is that it is doing both. You want it to stop after it has detected that argumentForSegment is 0, so add an else to the second conditional statement so that it only does that when the first conditional statement failed:
func action()
{
let argumentForSegment = segment.selectedSegmentIndex
if argumentForSegment == 0
{
i = 0
}
else if argumentForSegment == 1 // added "else" here
{
i += 2
}
else
{
i += Int(arc4random_uniform(100))
}
print(argumentForSegment)
prwtoText.text = "\(i)"
}
To improve on Vacawama's answer, you can format this much easier by using a switch statement:
func action() {
let argumentForSegment = segment.selectedSegmentIndex
switch argumentForSegment {
case 0:
i = 0
case 1:
i += 1
case 2:
i += Int(arc4random_uniform(100))
default:
break
}
print(argumentForSegment)
prwtoText.text = "\(i)"
}
it's much more clean for this type of thing.
(thanks, vacawama)

Stuck in a loop. Very strange because the code sometimes work and sometimes just freezes

I am writing a puzzle game for an IOS. In my code I need to fill an array with some random (and non-random numbers) that will represent the main data structure.
func Random(r : Range<Int>) -> Int {
return Int(arc4random_uniform(UInt32(r.endIndex - r.startIndex))) + r.startIndex
} // function to generate random number
var arrWithColors = [Int]() // array that will hold the numbers
//function to that check if an array contains a number in a range already
func checkForNumberInArrayWithRange(r: Range <Int>, n: Int ) -> Bool {
for i in r.startIndex..<r.endIndex {
if arrWithColors[i] == n { return true }
}
return false
}
// here is the main function where i keep getting stuck. Out of let's say five times it would only work 3 or even less.
func randHexWithTag() {
var rNumber : Int = Random(0...5)
for i in 0...5 {
while (true) {
rNumber = Random(0...5)
if !checkForNumberInArrayWithRange(0...5, n: rNumber) {
break
}
}
arrWithColors[i] = rNumber
}
arrWithColors[10] = arrWithColors[1]
for i in 6...11 {
while(true) {
rNumber = Random(0...5)
if ((rNumber == arrWithColors[0] && i == 9) || (rNumber == arrWithColors[2] && i == 11)) {
continue
}
if !checkForNumberInArrayWithRange(6...11, n: rNumber) {
break
}
}
if (i != 10) {
arrWithColors[i] = rNumber
}
}
arrWithColors[13] = arrWithColors[4]
for i in 12...17 {
while(true) {
rNumber = Random(0...5)
if (rNumber == arrWithColors[3] && i == 12) || (rNumber == arrWithColors[5] && i == 14) {
continue
}
if !checkForNumberInArrayWithRange(12...17, n: rNumber) {
break
}
}
if (i != 13) {
arrWithColors[i] = rNumber
}
}
}
The above code will ALWAYS fail during the first call to checkForNumberInArrayWithRange on this line:
if arrWithColors[i] == n { return true }
That is because arrWithColors is empty, and index i is out of range

How would I write this typedef enum from objective c to swift?

Below, I have the objective-c code which is used for tinder style animation effect , inspired by - https://github.com/ngutman/TinderLikeAnimations/tree/master/TinderLikeAnimations .
Objective-c
typedef NS_ENUM(NSUInteger , GGOverlayViewMode) {
GGOverlayViewModeLeft,
GGOverlayViewModeRight
};
- (void)setMode:(GGOverlayViewMode)mode
{
if (_mode == mode) return;
_mode = mode;
if (mode == GGOverlayViewModeLeft) {
self.imageView.image = [UIImage imageNamed:#"button1"];
} else {
self.imageView.image = [UIImage imageNamed:#"button2"];
}
}
I am trying to replicate the same in swift. This is what I have in swift -
enum GGOverlayViewMode : Int {
case GGOverlayViewModeLeft
case GGOverlayViewModeRight
}
func setMode(mode: GGOverlayViewMode){
// if (_ mode == mode) {
// return
// }
//
// _mode = mode;
if(mode == GGOverlayViewMode.GGOverlayViewModeLeft) {
imageView.image = UIImage(named: "button1")
} else {
imageView.image = UIImage(named: "button2")
}
}
But somehow its not making sense to how would I be handling the typdefs here.
Any help is appreciated.
Thanks
In Swift each enumeration has its own member values, so you don't have to give
them a unique prefix as in (Objective-)C. A typical definition would be
enum GGOverlayViewMode {
case Left
case Right
}
Also you don't have to specify an underlying "raw type" (such as Int), unless
you have other reasons to do so.
Instead of a custom setter method you would implement a property observer.
didSet is called immediately after the new value is stored, and has an implicit
parameter oldValue containing the old property value:
var mode : GGOverlayViewMode = .Right {
didSet {
if mode != oldValue {
switch mode {
case .Left :
imageView.image = UIImage(named: "button1")
case .Right:
imageView.image = UIImage(named: "button2")
}
}
}
}
I think in swift, your function will look like this.
enum GGOverlayViewMode : Int
{
case GGOverlayViewModeLeft
case GGOverlayViewModeRight
}
func setMode(mode: GGOverlayViewMode){
switch mode
{
case .GGOverlayViewModeLeft:
imageView.image = UIImage(named: "button1")
case .GGOverlayViewModeRight:
imageView.image = UIImage(named: "button2")
}
}

'SKNode?' does not have a member named 'position'

What am I doing wrong? I can't seem to figure this out. I have tried putting an exclamation mark behind: var thisBlock = self.childNodeWithName(block),
this gives me a new error saying. type () does not confirm to protocol 'BooleanType'.
func blockRunner() {
for(block, blockStatus) in self.blockStatuses {
var thisBlock = self.childNodeWithName(block)
if blockStatus.shouldRunBlock() {
blockStatus.timeGapForNextRun = random()
blockStatus.currentInterval = 0
blockStatus.isRunning = true
}
if blockStatus.isRunning {
if thisBlock.position.x = blockMaxX{
thisBlock.position.x -= CGFloat(self.groundSpeed)
} else {
thisBlock.position.x = self.origBlockPositionX
blockStatus.isRunning = false
self.score++
if ((self.score % 5) == 0) {
self.groundSpeed++
}
self.scoreText.text = String(self.score)
}
} else {
blockStatus.currentInterval++
}
}
}
childNodeWithName() does return an optional SKNode? which you have to unwrap to use. I don't know why var thisBlock = self.childNodeWithName(block)! didn't solve your issue. I would recommend using optional binding (if let) syntax:
if let thisBlock = self.childNodeWithName(block) {
if blockStatus.shouldRunBlock() {
blockStatus.timeGapForNextRun = random()
blockStatus.currentInterval = 0
blockStatus.isRunning = true
}
if blockStatus.isRunning {
... rest of your code
}
This has the added advantage of not crashing if there are no children nodes. It just won't enter the block.

Resources