Git Product home page Git Product logo

learning-swift's Introduction

Learing swift

Try to make something everyday with swift.

iPhone Project with swift:

  • Removing Storyboard
  • Init with nib for view controller
  • Adding tableview
  • Registering class with classForCoder()
  • Adding tableview delegate

Trying Request

  • URL with string
  • Playground cannot make request
  • Block

Implementing PokemonKit a wrapper class of Pokeapi-v2 written in swift

  • Writing closeure, block in swift public func fetchBerryList(completion: (result: NSArray) -> Void, failure: (error: NSError) -> Void)
  • Define dictionary [NSLocalizedDescriptionKey: "Berry List Error"]
  • Tools for mapping objects Link

Trying PromiseKit

  • Write a promise
public func fetchBerryList() -> Promise<[PKMBaseObject]>{
    return Promise { fulfill, reject in
        let URL = baseURL + "/berry"
        
        Alamofire.request(.GET, URL).responseArray { (response: Response<[PKMBaseObject], NSError>) in
            if (response.result.isSuccess) {
                fulfill(response.result.value!)
            }else{
                reject(response.result.error!)
            }
        }
    };
}
  • Writing test case with swift
  • Testing asnc calls
let asyncExpectation = expectationWithDescription("Fetch berries")
        
PokemonKit.fetchBerryList()
    .then { response in
        
        asyncExpectation.fulfill()
    }
    .error{ err in
        XCTFail("Should not failed with \(err)")
    }

self.waitForExpectationsWithTimeout(30) { (err) -> Void in
    XCTAssertNil(err, "Something went wrong")
}
  • Fixing missing closure for AnyPromise
PokemonKit.fetchBerry("1")
    .then { response  -> Void in // this is the fix (-> Void in)
    
    ...continue...

Loading cocoapods library bundle resources

Add Resource path in podspec

  s.resource_bundles = {
    'CSSwift' => ['Pod/Assets/*.js']
  }

Load it with NSBundle

func loadCssJs() {
    cssJs = JSContext()
    let podBundle = NSBundle(forClass: self.classForCoder)
    
    if let bundleURL = podBundle.URLForResource("CSSwift", withExtension: "bundle") {
        
        if let bundle = NSBundle(URL: bundleURL) {
            
            let cssJsPath = bundle.pathForResource("css", ofType: "js")
            do{
                let content = try String(contentsOfFile: cssJsPath!)
                cssJs.evaluateScript(content)
            }
            catch {}
        }else {
            assertionFailure("Could not load the bundle")
        }
        
    }else {
        assertionFailure("Could not create a path to the bundle")
    }
}

For-in loop

for dict in jsResult{
    result.append(CSSModel(infoDict: dict as! [String : AnyObject]))
}

Init functions

convenience init(infoDict:[String: AnyObject]!) {
    self.init()
    
    rules = infoDict["rules"]! as? [AnyObject]
    selector = infoDict["selector"]! as? String
}

Adding variable in JavascriptCore

cssJs.setObject(cssString, forKeyedSubscript: "cssValue")
// don't use cssJs.evaluateScript("var cssString = '\(cssString)';"), line break will not work

Checking platform

#if os(iOS)
    import CSSwiftiOS
#else
    import CSSwift
#endif

isEquals in Swift

// Useful when compare arrays of objects

override public func isEqual(object: AnyObject?) -> Bool {
    guard let rhs = object as? CSSRuleModel else {
        return false
    }
    let lhs = self
    
    return (lhs.ruleName == rhs.ruleName &&
        lhs.ruleContent == rhs.ruleContent)
}

Assoicate Object

private struct AssociatedKeys {
    static var CSSisUrlAssociationKey :UInt8 = 0
}

public var isUrl: Bool! {
    get {
        guard let result = objc_getAssociatedObject(self, &AssociatedKeys.CSSisUrlAssociationKey) as? Bool else{
            return false
        }
        return result
    }
    
    set {
        if let newValue = newValue {
            objc_setAssociatedObject(
                self,
                &AssociatedKeys.CSSisUrlAssociationKey,
                newValue,
                .OBJC_ASSOCIATION_RETAIN_NONATOMIC
            )
        }
    }
}

Day X

Fuck Swift, I am going back to Objective-C

learning-swift's People

Contributors

darkcl avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.