Skip to content

Instantly share code, notes, and snippets.

@seanhess
Created August 10, 2016 19:49
Show Gist options
  • Save seanhess/fbf641285da38dd14f432d330bdf63b6 to your computer and use it in GitHub Desktop.
Save seanhess/fbf641285da38dd14f432d330bdf63b6 to your computer and use it in GitHub Desktop.
Simple data objects.
//
// Post.swift
//
//
// Created by Greg Rosich on 7/14/16.
//
//
import Foundation
class Post: NSObject {
// Does your program ever need to change these?
// if not use let, if so use var
let text: String
let time: String
let id: Int
let numLikes: Int
let numReplies: Int
let hasLiked: Bool
// Pass in all required variables at once. Don't use var just because it's hard to set them all at the same time
// we want to make the strongest guarantees we can. Once it's been parsed, this object is rock solid. It's immutable
// and guaranteed not to be missing values
init(id:Int, text:String, time:String, numLikes:Int, numReplies: Int, hasLiked:Bool) {
self.id = id
self.text = text
self.time = time
self.numLikes = numLikes
self.numReplies = numReplies
self.hasLiked = hasLiked
super.init()
}
// This function only returns a Post if it parses successfully. Don't allow fields to be null! That sweeps
// complexity further under the rug. It will resurface later and slow you down
// This function requires whoever calls it to decide what to do if a post doesn't parse
// See flatMap: itemDictionaries.flatMap(Post.fromDictionary) will return a list of only those that parse.
static func fromDictionary(item: [String : AnyObject]) -> Post? {
guard let
text = item["text"] as? String,
time = item["time"] as? String,
id = item["postid"] as? Int,
numLikes = item["liked"] as? Int,
numReplies = item["replynum"] as? Int
else {
return nil
}
// I don't understand what this is doing so I left it as an exercise :)
// post.hasLiked = (item["hasliked"] as? Int == userID) as Bool
return Post(id: id, text: text, time: time, numLikes: numLikes, numReplies: numReplies, hasLiked: false)
}
// Put more functions in this class that deal with manipulating Post objects. Anything that derives its information from one.
// These should be primarily data / business logic things.
// You also need to put your server calls somewhere (fetchData, and functions like it). You can put them in here for now, at least until your app gets bigger. Eventually you will likely want to separate "Services" or "API" folder that contains all the functions that deal with IO, and this one can contain only pure data logic. Try to make the fetch / services functions static (stateless). This makes them really easy to move around. You can pass in a Post as an argument when needed.
// they'll look something like this when you use them.
// Post.fetchComments(postId) { comments in ... }
// Post.fetchAllForUser(userId) { posts in ... }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment