Adding multiple arrays to form one final array. Debug swift xcode
I think you may have problem problem if you using List model regarding to playing sound of clicked Card one could be better is to modify the Card model with following way
import Foundation; import UIKit; import AVFoundation
var player: AVAudioPlayer?
class Card: NSObject
{
var image: UIImage
var soundUrl: String
var isActive: Bool
init(image: UIImage, soundUrl: String, isActive:Bool = true) {
self.image = image
self.soundUrl = soundUrl
self.isActive = isActive
}
func playSound()
{
guard let url = Bundle.main.url(forResource: self.soundUrl, withExtension: "m4a") else { return }
do
{
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
player = try AVAudioPlayer(contentsOf: url)
guard let player = player else { return }
player.prepareToPlay()
player.play()
print("play")
} catch let error {
print(error.localizedDescription)
}
}
}
Usage
Replace your viewController code with this
import UIKit
class SecondViewController: UIViewController , UIGestureRecognizerDelegate {
var imageIndex: Int = 0
var itemList:[Card] = []
func addlist(list:[String], flag:Bool)
{
for word in list
{
itemList.append(Card(image: UIImage(named: word)!, soundUrl: word,isActive:flag))
}
}
override func viewDidLoad() {
super.viewDidLoad()
let list1 = ["lake", "lamb", "lamp", "lark", "leaf", "leash", "left", "leg", "lime", "lion", "lips", "list", "lock", "log", "look", "love", "lunch"]
let list2 = ["ladder", "ladybug", "laughing", "lawnmower", "lemon", "leopard", "leprechaun", "letters", "licking", "lifesaver", "lifting", "lightbulb", "lightning",
"listen", "llama"]
let list3 = ["alligator", "balance", "ballerina", "balloon", "bowling", "cello", "colors", "curlyhair", "dollar", "dolphin", "elephant", "eyelashes", "gasoline",
"goalie", "hula", "jellyfish", "olive", "pillow", "pilot", "polarbear", "rollerskate", "ruler", "silly", "telephone", "television", "tulip", "umbrella", "valentine",
"violin", "xylophone", "yellow"]
let list4 = ["apple", "ball", "bell", "bubble", "castle", "fall", "fishbowl", "girl", "owl", "pail", "peel", "pool", "smile", "whale", "wheel"]
let list5 = ["planet", "plank", "plant", "plate", "play", "plum", "plumber", "plus"]
let list6 = ["black", "blanket", "blender", "blocks", "blond", "blood", "blow", "blue"]
let list7 = ["flag", "flipflop", "float", "floor", "flower", "fluffy", "flute", "fly"]
let list8 = ["glacier", "glad", "glasses", "glide", "glitter", "globe", "glove", "glue"]
let list9 = ["clam", "clamp", "clap", "claw", "clean", "climb", "clip", "cloud"]
let list10 = ["sled", "sleep", "sleeves", "slice", "slide", "slime", "slip", "slow"]
let list11 = ["belt", "cold", "dolphin", "elf", "golf", "melt", "milk", "shelf"]
addlist(list:list1,flag:true);
addlist(list:list2,flag:true);
addlist(list:list3,flag:true);
addlist(list:list4,flag:true);
addlist(list:list5,flag:true);
addlist(list:list6,flag:true);
addlist(list:list7,flag:true);
addlist(list:list8,flag:true);
addlist(list:list9,flag:true);
addlist(list:list10,flag:true);
addlist(list:list11,flag:true);
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
imgPhoto.isUserInteractionEnabled = true
imgPhoto.addGestureRecognizer(tapGestureRecognizer)
imgPhoto.image = itemList[0].image
// Do any additional setup after loading the view.
imgPhoto.isUserInteractionEnabled = true
let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(Swiped(gesture:)))
leftSwipe.cancelsTouchesInView = false
let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(Swiped(gesture:)))
rightSwipe.cancelsTouchesInView = false
leftSwipe.direction = .left
rightSwipe.direction = .right
view.addGestureRecognizer(leftSwipe)
view.addGestureRecognizer(rightSwipe)
}
@IBAction func home(_ sender: Any) {
performSegue(withIdentifier: "home", sender: self)
}
@IBOutlet weak var imgPhoto: UIImageView!
func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
itemList[imageIndex].playSound()
// Your action
}
func Swiped(gesture: UIGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.right :
print("User swiped right")
// decrease index first
imageIndex -= 1
// check if index is in range
if imageIndex < 0 {
imageIndex = itemList.count - 1
}
imgPhoto.image = itemList[imageIndex].image
case UISwipeGestureRecognizerDirection.left:
print("User swiped Left")
// increase index first
imageIndex += 1
// check if index is in range
if imageIndex > itemList.count - 1 {
imageIndex = 0
}
imgPhoto.image = itemList[imageIndex].image
default:
break //stops the code/codes nothing.
}
}
}
}
Creating multiple arrays which will add up to one final array. Debugging issue. Swift and Xcode
You're very close; there are a few fixes needed:
Move the
imageList
computed variable to the class level, instead of insideviewDidLoad
.The
imageIndex
variable can be anInt
instead of anNSInteger
. This is not a breaking change, but will make things easier and is better Swift style.Where you previously used the
maxImages
variable, you can replace them withimageList.count
, which is the total number of elements in the array.
Here is the final, edited code. It compiles; let me know if it works!
class SecondViewController: UIViewController , UIGestureRecognizerDelegate {
@IBAction func home(_ sender: Any) {
performSegue(withIdentifier: "home", sender: self)
}
@IBOutlet weak var imgPhoto: UIImageView!
struct List {
let words: [String]
var active: Bool
}
let list1 = List(words:["lake", "lamb", "lamp", "lark", "leaf", "leash", "left", "leg", "lime", "lion", "lips", "list", "lock", "log", "look", "love", "lunch"], active: true)
let list2 = List(words: ["ladder", "ladybug", "laughing", "lawnmower", "lemon", "leopard", "leprechaun", "letters", "licking", "lifesaver", "lifting", "lightbulb", "lightning", "listen", "llama"], active: true)
let list3 = List(words: ["alligator", "balance", "ballerina", "balloon", "bowling", "cello", "colors", "curlyhair", "dollar", "dolphin", "elephant", "eyelashes", "gasoline", "goalie", "hula", "jellyfish", "olive", "pillow", "pilot", "polarbear", "rollerskate", "ruler", "silly", "telephone", "television", "tulip", "umbrella", "valentine", "violin", "xylophone", "yellow"], active: true)
let list4 = List(words: ["apple", "ball", "bell", "bubble", "castle", "fall", "fishbowl", "girl", "owl", "pail", "peel", "pool", "smile", "whale", "wheel"], active: true)
let list5 = List(words: ["planet", "plank", "plant", "plate", "play", "plum", "plumber", "plus"], active: true)
let list6 = List(words: ["black", "blanket", "blender", "blocks", "blond", "blood", "blow", "blue"], active: true)
let list7 = List(words: ["flag", "flipflop", "float", "floor", "flower", "fluffy", "flute", "fly"], active: true)
let list8 = List(words: ["glacier", "glad", "glasses", "glide", "glitter", "globe", "glove", "glue"], active: true)
let list9 = List(words: ["clam", "clamp", "clap", "claw", "clean", "climb", "clip", "cloud"], active: true)
let list10 = List(words:["sled", "sleep", "sleeves", "slice", "slide", "slime", "slip", "slow"], active: true)
let list11 = List(words: ["belt", "cold", "dolphin", "elf", "golf", "melt", "milk", "shelf"], active: true)
var imageIndex: Int = 0
var imageList: [String] {
let wordLists = [list1, list2, list3, list4, list5, list6, list7, list8, list9, list10, list11]
let active = wordLists.reduce([]) { (result:[String], list:List) in
if list.active {
return result + list.words
} else {
return result
}
}
return active
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
imgPhoto.isUserInteractionEnabled = true
let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(Swiped(gesture:)))
leftSwipe.cancelsTouchesInView = false
let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(Swiped(gesture:)))
rightSwipe.cancelsTouchesInView = false
leftSwipe.direction = .left
rightSwipe.direction = .right
view.addGestureRecognizer(leftSwipe)
view.addGestureRecognizer(rightSwipe)
}
func Swiped(gesture: UIGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.right :
print("User swiped right")
// decrease index first
imageIndex -= 1
// check if index is in range
if imageIndex < 0 {
imageIndex = imageList.count - 1
}
imgPhoto.image = UIImage(named: imageList[imageIndex])
case UISwipeGestureRecognizerDirection.left:
print("User swiped Left")
// increase index first
imageIndex += 1
// check if index is in range
if imageIndex > imageList.count - 1 {
imageIndex = 0
}
imgPhoto.image = UIImage(named: imageList[imageIndex])
default:
break //stops the code/codes nothing.
}
}
}
}
Global array not appending
Singletons in swift should have a private initializer so no one can create an instance other than the single shared instance. The single instance is usually called shared
. If you want the value to print every time you append an item then you should use a didSet
:
struct Interventions {
static var shared: [String] = [] {
didSet {
shared.forEach{print($0)}
}
}
private init() { }
}
How to show all the elements of an array in swift?
You can simply iterate through the array like this and print out all elements on a new line:
for element in array {
println(element)
}
UPDATE
For Swift 2 and Swift 3:
for element in array {
print(element)
}
Or if you want it on the same line:
for element in array {
print(element, terminator: " ")
}
Detect array with issue (Debug mode)
To handle All exceptions, From Xcode click on Show the Breakpoint Navigator
Click +
button at bottom side and from pop up click on Add Exception Breakpoint.
This will add exception break points for application, try to run again and execution will stop if any runtime exception raised.
If this will not help, enable zombie environment for project, check out from this thread -
How to set exception breakpoint from Xcode
Breaking up one array into multiple arrays in Postman
What is being returned is a list of objects. There is no need of converting that into arrays. you can map inside that one array and access the object.
Related Topics
Randomly Choosing an Item from a Swift Array Without Repeating
Modify Pull to Refresh in Swift
How to Pretty Print Swift Dictionaries to the Console
Change Bundle Identifier in Xcode When Submitting My First App in iOS
Xcode - Error Itms-90635 - Invalid MACh-O in Bundle - Submitting to App Store
How to Find a Specification in Cocoapods
How to Turn Flashlight on and Off in Swift
Using Global Variables in Objective-C
How to Import Private Framework Headers in a Swift Framework
Sectionindextitles for a Uicollectionview
Bridge Google Drive API to Swift
Please Clear Some Confusions Regarding Uiviewcontroller
Copy Text to Clipboard with iOS
Uitableview Disable Swipe to Delete, But Still Have Delete in Edit Mode
Programmatically Linking Uipagecontrol to Uiscrollview
iOS App Crashing Every Other Launch, Can't Find Error
How to Add Text Input in Alertview of iOS 8
What Does Warning "Mapping Architecture Arm64 to X86_64" Mean