Skip to content

Instantly share code, notes, and snippets.

@pakirby1
Last active May 14, 2019 19:19
Show Gist options
  • Save pakirby1/bee85c34b60df5bb564c441c18ed84c9 to your computer and use it in GitHub Desktop.
Save pakirby1/bee85c34b60df5bb564c441c18ed84c9 to your computer and use it in GitHub Desktop.
//: A UIKit based Playground for presenting user interface
import UIKit
import PlaygroundSupport
import Foundation
class MyViewController : UIViewController {
override func loadView() {
let view = UIView()
view.backgroundColor = .white
let label = UILabel()
label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
label.text = "Hello World!"
let json = readDamageCards()
label.text = json
label.textColor = .black
let cards = serializeJSON(jsonString: json)
for card in cards.cards {
print(card.title)
}
view.addSubview(label)
self.view = view
}
func readDamageCards() -> String {
var contents: String = ""
if let fileURL = Bundle.main.url(forResource:"core", withExtension: "json")
{
do {
contents = try String(contentsOf: fileURL,
encoding: String.Encoding.utf8)
print(contents)
} catch {
print("Error: \(error.localizedDescription)")
}
} else {
print("No such file URL")
}
return contents
}
func serializeJSON(jsonString: String) -> DamageCardList {
let jsonData = jsonString.data(using: .utf8)!
let decoder = JSONDecoder()
let cards: DamageCardList = try! decoder.decode(DamageCardList.self, from: jsonData)
return cards
}
}
enum DamageCardType: String, Codable {
case Ship
case Pilot
}
struct DamageCard: Codable {
let title: String
let amount: Int
let type: DamageCardType
let text: String
}
struct DamageCardList : Codable {
let cards: [DamageCard]
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment