repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
joeytat/JWStarRating
refs/heads/master
Classes/JWStarRatingView.swift
mit
1
// // JWStarRatingView.swift // WapaKit // // Created by Joey on 1/21/15. // Copyright (c) 2015 Joeytat. All rights reserved. // import UIKit @IBDesignable class JWStarRatingView: UIView { @IBInspectable var starColor: UIColor = UIColor(red: 200.0/255.0, green: 200.0/255.0, blue: 200.0/255.0, alpha: 1) @IBInspectable var starHighlightColor: UIColor = UIColor(red: 88.0/255.0, green: 88.0/255.0, blue: 88.0/255.0, alpha: 1) @IBInspectable var starCount:Int = 5 @IBInspectable var spaceBetweenStar:CGFloat = 10.0 #if TARGET_INTERFACE_BUILDER override func willMoveToSuperview(newSuperview: UIView?) { let starRating = JWStarRating(frame: self.bounds, starCount: self.starCount, starColor: self.starColor, starHighlightColor: self.starHighlightColor, spaceBetweenStar: self.spaceBetweenStar) addSubview(starRating) } #else override func awakeFromNib() { super.awakeFromNib() let starRating = JWStarRating(frame: self.bounds, starCount: self.starCount, starColor: self.starColor, starHighlightColor: self.starHighlightColor, spaceBetweenStar: self.spaceBetweenStar) starRating.addTarget(self, action: #selector(JWStarRatingView.valueChanged(_:)), forControlEvents: UIControlEvents.ValueChanged) addSubview(starRating) } #endif func valueChanged(starRating:JWStarRating){ // Do something with the value... print("Value changed \(starRating.ratedStarIndex)") } }
b8575ecaee10c7bc98f54d45634cf95a
38.051282
197
0.701248
false
false
false
false
objecthub/swift-lispkit
refs/heads/master
Sources/LispKit/Primitives/ControlFlowLibrary.swift
apache-2.0
1
// // ControlFlowLibrary.swift // LispKit // // Created by Matthias Zenger on 22/01/2016. // Copyright © 2016 ObjectHub. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // public final class ControlFlowLibrary: NativeLibrary { /// Name of the library. public override class var name: [String] { return ["lispkit", "control"] } /// Declarations of the library. public override func declarations() { self.define(SpecialForm("begin", self.compileBegin)) self.define(SpecialForm("let", self.compileLet)) self.define(SpecialForm("let*", self.compileLetStar)) self.define(SpecialForm("letrec", self.compileLetRec)) self.define(SpecialForm("letrec*", self.compileLetRecStar)) self.define(SpecialForm("let-values", self.compileLetValues)) self.define(SpecialForm("let*-values", self.compileLetStarValues)) self.define(SpecialForm("letrec-values", self.compileLetRecValues)) self.define(SpecialForm("let-optionals", self.compileLetOptionals)) self.define(SpecialForm("let*-optionals", self.compileLetStarOptionals)) self.define(SpecialForm("let-keywords", self.compileLetKeywords)) self.define(SpecialForm("let*-keywords", self.compileLetStarKeywords)) self.define(SpecialForm("let-syntax", self.compileLetSyntax)) self.define(SpecialForm("letrec-syntax", self.compileLetRecSyntax)) self.define(SpecialForm("do", self.compileDo)) self.define(SpecialForm("if", self.compileIf)) self.define(SpecialForm("when", self.compileWhen)) self.define(SpecialForm("unless", self.compileUnless)) self.define(SpecialForm("cond", self.compileCond)) self.define(SpecialForm("case", self.compileCase)) } private func splitBindings(_ bindingList: Expr) throws -> (Expr, Expr) { var symbols = Exprs() var exprs = Exprs() var bindings = bindingList while case .pair(let binding, let rest) = bindings { guard case .pair(.symbol(let sym), .pair(let expr, .null)) = binding else { throw RuntimeError.eval(.malformedBinding, binding, bindingList) } symbols.append(.symbol(sym)) exprs.append(expr) bindings = rest } guard bindings.isNull else { throw RuntimeError.eval(.malformedBindings, bindingList) } return (Expr.makeList(symbols), Expr.makeList(exprs)) } private func compileBegin(_ compiler: Compiler, expr: Expr, env: Env, tail: Bool) throws -> Bool { guard case .pair(_, let exprs) = expr else { preconditionFailure("malformed begin") } return try compiler.compileSeq(exprs, in: env, inTailPos: tail, localDefine: false) } private func compileLet(_ compiler: Compiler, expr: Expr, env: Env, tail: Bool) throws -> Bool { guard case .pair(_, .pair(let first, let body)) = expr else { throw RuntimeError.argumentCount(of: "let", min: 1, expr: expr) } let initialLocals = compiler.numLocals var res = false switch first { case .null: return try compiler.compileSeq(body, in: env, inTailPos: tail) case .pair(_, _): let group = try compiler.compileBindings(first, in: env, atomic: true, predef: false) res = try compiler.compileSeq(body, in: Env(group), inTailPos: tail) group.finalize() case .symbol(let sym): guard case .pair(let bindings, let rest) = body else { throw RuntimeError.argumentCount(of: "let", min: 2, expr: expr) } let (params, exprs) = try splitBindings(bindings) let group = BindingGroup(owner: compiler, parent: env) let index = group.allocBindingFor(sym).index compiler.emit(.pushUndef) compiler.emit(.makeLocalVariable(index)) let nameIdx = compiler.registerConstant(first) try compiler.compileLambda(nameIdx, params, rest, Env(group)) compiler.emit(.setLocalValue(index)) // res = try compiler.compile(.pair(first, exprs), // in: Env(group), // inTailPos: tail) // Make frame for closure invocation let pushFrameIp = compiler.emit(.makeFrame) compiler.emit(.pushLocalValue(index)) // Push arguments and call function if compiler.call(try compiler.compileExprs(exprs, in: env), inTailPos: tail) { // Remove make_frame if this was a tail call compiler.patch(.noOp, at: pushFrameIp) res = true } else { res = false } default: throw RuntimeError.type(first, expected: [.listType, .symbolType]) } if !res && compiler.numLocals > initialLocals { compiler.emit(.reset(initialLocals, compiler.numLocals - initialLocals)) } compiler.numLocals = initialLocals return res } private func compileLetStar(_ compiler: Compiler, expr: Expr, env: Env, tail: Bool) throws -> Bool { guard case .pair(_, .pair(let first, let body)) = expr else { throw RuntimeError.argumentCount(of: "let*", min: 1, expr: expr) } let initialLocals = compiler.numLocals switch first { case .null: return try compiler.compileSeq(body, in: env, inTailPos: tail) case .pair(_, _): let group = try compiler.compileBindings(first, in: env, atomic: false, predef: false) let res = try compiler.compileSeq(body, in: Env(group), inTailPos: tail) return compiler.finalizeBindings(group, exit: res, initialLocals: initialLocals) default: throw RuntimeError.type(first, expected: [.listType]) } } private func compileLetRec(_ compiler: Compiler, expr: Expr, env: Env, tail: Bool) throws -> Bool { guard case .pair(_, .pair(let first, let body)) = expr else { throw RuntimeError.argumentCount(of: "letrec", min: 1, expr: expr) } let initialLocals = compiler.numLocals switch first { case .null: return try compiler.compileSeq(body, in: env, inTailPos: tail) case .pair(_, _): let group = try compiler.compileBindings(first, in: env, atomic: true, predef: true, postset: true) let res = try compiler.compileSeq(body, in: Env(group), inTailPos: tail) return compiler.finalizeBindings(group, exit: res, initialLocals: initialLocals) default: throw RuntimeError.type(first, expected: [.listType]) } } private func compileLetRecStar(_ compiler: Compiler, expr: Expr, env: Env, tail: Bool) throws -> Bool { guard case .pair(_, .pair(let first, let body)) = expr else { throw RuntimeError.argumentCount(of: "letrec*", min: 1, expr: expr) } let initialLocals = compiler.numLocals switch first { case .null: return try compiler.compileSeq(body, in: env, inTailPos: tail) case .pair(_, _): let group = try compiler.compileBindings(first, in: env, atomic: true, predef: true) let res = try compiler.compileSeq(body, in: Env(group), inTailPos: tail) return compiler.finalizeBindings(group, exit: res, initialLocals: initialLocals) default: throw RuntimeError.type(first, expected: [.listType]) } } private func compileLetValues(_ compiler: Compiler, expr: Expr, env: Env, tail: Bool) throws -> Bool { guard case .pair(_, .pair(let first, let body)) = expr else { throw RuntimeError.argumentCount(of: "let-values", min: 1, expr: expr) } let initialLocals = compiler.numLocals switch first { case .null: return try compiler.compileSeq(body, in: env, inTailPos: tail) case .pair(_, _): let group = try compiler.compileMultiBindings(first, in: env, atomic: true) let res = try compiler.compileSeq(body, in: Env(group), inTailPos: tail) return compiler.finalizeBindings(group, exit: res, initialLocals: initialLocals) default: throw RuntimeError.type(first, expected: [.listType]) } } private func compileLetStarValues(_ compiler: Compiler, expr: Expr, env: Env, tail: Bool) throws -> Bool { guard case .pair(_, .pair(let first, let body)) = expr else { throw RuntimeError.argumentCount(of: "let*-values", min: 1, expr: expr) } let initialLocals = compiler.numLocals switch first { case .null: return try compiler.compileSeq(body, in: env, inTailPos: tail) case .pair(_, _): let group = try compiler.compileMultiBindings(first, in: env, atomic: false, predef: false) let res = try compiler.compileSeq(body, in: Env(group), inTailPos: tail) return compiler.finalizeBindings(group, exit: res, initialLocals: initialLocals) default: throw RuntimeError.type(first, expected: [.listType]) } } private func compileLetRecValues(_ compiler: Compiler, expr: Expr, env: Env, tail: Bool) throws -> Bool { guard case .pair(_, .pair(let first, let body)) = expr else { throw RuntimeError.argumentCount(of: "letrec-values", min: 1, expr: expr) } let initialLocals = compiler.numLocals switch first { case .null: return try compiler.compileSeq(body, in: env, inTailPos: tail) case .pair(_, _): let group = try compiler.compileMultiBindings(first, in: env, atomic: false, predef: true) let res = try compiler.compileSeq(body, in: Env(group), inTailPos: tail) return compiler.finalizeBindings(group, exit: res, initialLocals: initialLocals) default: throw RuntimeError.type(first, expected: [.listType]) } } private func compileLetOptionals(_ compiler: Compiler, expr: Expr, env: Env, tail: Bool) throws -> Bool { guard case .pair(_, .pair(let optlist, .pair(let first, let body))) = expr else { throw RuntimeError.argumentCount(of: "let-optionals", min: 2, expr: expr) } let initialLocals = compiler.numLocals switch first { case .null: return try compiler.compileSeq(.pair(optlist, body), in: env, inTailPos: tail) case .pair(_, _): try compiler.compile(optlist, in: env, inTailPos: false) let group = try compiler.compileOptionalBindings(first, in: env, optenv: env) let res = try compiler.compileSeq(body, in: Env(group), inTailPos: tail) return compiler.finalizeBindings(group, exit: res, initialLocals: initialLocals) default: throw RuntimeError.type(first, expected: [.listType]) } } private func compileLetStarOptionals(_ compiler: Compiler, expr: Expr, env: Env, tail: Bool) throws -> Bool { guard case .pair(_, .pair(let optlist, .pair(let first, let body))) = expr else { throw RuntimeError.argumentCount(of: "let*-optionals", min: 2, expr: expr) } let initialLocals = compiler.numLocals switch first { case .null: return try compiler.compileSeq(.pair(optlist, body), in: env, inTailPos: tail) case .pair(_, _): try compiler.compile(optlist, in: env, inTailPos: false) let group = try compiler.compileOptionalBindings(first, in: env, optenv: nil) let res = try compiler.compileSeq(body, in: Env(group), inTailPos: tail) return compiler.finalizeBindings(group, exit: res, initialLocals: initialLocals) default: throw RuntimeError.type(first, expected: [.listType]) } } private func compileLetKeywords(_ compiler: Compiler, expr: Expr, env: Env, tail: Bool) throws -> Bool { guard case .pair(_, .pair(let optlist, .pair(let first, let body))) = expr else { throw RuntimeError.argumentCount(of: "let-keywords", min: 2, expr: expr) } let initialLocals = compiler.numLocals switch first { case .null: return try compiler.compileSeq(.pair(optlist, body), in: env, inTailPos: tail) case .pair(_, _): try compiler.compile(optlist, in: env, inTailPos: false) let group = try self.compileKeywordBindings(compiler, first, in: env, atomic: true) compiler.emit(.pop) let res = try compiler.compileSeq(body, in: Env(group), inTailPos: tail) return compiler.finalizeBindings(group, exit: res, initialLocals: initialLocals) default: throw RuntimeError.type(first, expected: [.listType]) } } private func compileLetStarKeywords(_ compiler: Compiler, expr: Expr, env: Env, tail: Bool) throws -> Bool { guard case .pair(_, .pair(let optlist, .pair(let first, let body))) = expr else { throw RuntimeError.argumentCount(of: "let*-keywords", min: 2, expr: expr) } let initialLocals = compiler.numLocals switch first { case .null: return try compiler.compileSeq(.pair(optlist, body), in: env, inTailPos: tail) case .pair(_, _): try compiler.compile(optlist, in: env, inTailPos: false) let group = try self.compileKeywordBindings(compiler, first, in: env, atomic: false) compiler.emit(.pop) let res = try compiler.compileSeq(body, in: Env(group), inTailPos: tail) return compiler.finalizeBindings(group, exit: res, initialLocals: initialLocals) default: throw RuntimeError.type(first, expected: [.listType]) } } private func compileKeywordBindings(_ compiler: Compiler, _ bindingList: Expr, in lenv: Env, atomic: Bool) throws -> BindingGroup { let group = BindingGroup(owner: compiler, parent: lenv) let env = atomic ? lenv : .local(group) var bindings = bindingList var prevIndex = -1 let initialIp = compiler.emitPlaceholder() let backfillIp = compiler.offsetToNext(0) var keywords = [Symbol : Symbol]() // Backfill keyword bindings with defaults while case .pair(let binding, let rest) = bindings { let sym: Symbol let expr: Expr switch binding { case .pair(.symbol(let s), .pair(let def, .null)): sym = s expr = def case .pair(.symbol(let s), .pair(.symbol(let key), .pair(let def, .null))): keywords[s] = key sym = s expr = def default: throw RuntimeError.eval(.malformedBinding, binding, bindingList) } compiler.emit(.pushUndef) let pushValueIp = compiler.emitPlaceholder() compiler.emit(.eq) let alreadySetIp = compiler.emitPlaceholder() try compiler.compile(expr, in: env, inTailPos: false) let binding = group.allocBindingFor(sym) guard binding.index > prevIndex else { throw RuntimeError.eval(.duplicateBinding, .symbol(sym), bindingList) } compiler.emit(binding.isValue ? .setLocal(binding.index) : .setLocalValue(binding.index)) compiler.patch(binding.isValue ? .pushLocal(binding.index) : .pushLocalValue(binding.index), at: pushValueIp) compiler.patch(.branchIfNot(compiler.offsetToNext(alreadySetIp)), at: alreadySetIp) prevIndex = binding.index bindings = rest } guard bindings.isNull else { throw RuntimeError.eval(.malformedBindings, bindingList) } let finalIp = compiler.emitPlaceholder() compiler.patch(.branch(compiler.offsetToNext(initialIp)), at: initialIp) // Allocate space for all the bindings bindings = bindingList while case .pair(.pair(.symbol(let sym), _), let rest) = bindings { let binding = group.allocBindingFor(sym) compiler.emit(.pushUndef) compiler.emit(binding.isValue ? .setLocal(binding.index) : .makeLocalVariable(binding.index)) bindings = rest } // Process keyword list bindings = bindingList let loopIp = compiler.emit(.dup) compiler.emit(.isNull) let listEmptyIp = compiler.emitPlaceholder() compiler.emit(.deconsKeyword) while case .pair(.pair(.symbol(let sym), _), let rest) = bindings { let binding = group.allocBindingFor(sym) compiler.emit(.dup) if let key = keywords[sym] { compiler.pushConstant(.symbol(key)) } else { compiler.pushConstant(.symbol(compiler.context.symbols.intern(sym.identifier + ":"))) } compiler.emit(.eq) let keywordCompIp = compiler.emitPlaceholder() compiler.emit(.pop) compiler.emit(binding.isValue ? .setLocal(binding.index) : .makeLocalVariable(binding.index)) compiler.emit(.branch(-compiler.offsetToNext(loopIp))) compiler.patch(.branchIfNot(compiler.offsetToNext(keywordCompIp)), at: keywordCompIp) bindings = rest } compiler.emit(.raiseError(EvalError.unknownKeyword.rawValue, 2)) compiler.patch(.branchIf(compiler.offsetToNext(listEmptyIp)), at: listEmptyIp) // Jumop to the default backfill compiler.emit(.branch(-compiler.offsetToNext(backfillIp))) // Patch instructions jumping to the end compiler.patch(.branch(compiler.offsetToNext(finalIp)), at: finalIp) return group } private func compileLetSyntax(_ compiler: Compiler, expr: Expr, env: Env, tail: Bool) throws -> Bool { guard case .pair(_, .pair(let first, let body)) = expr else { throw RuntimeError.argumentCount(of: "let-syntax", min: 1, expr: expr) } switch first { case .null: return try compiler.compileSeq(body, in: env, inTailPos: tail) case .pair(_, _): let group = try compiler.compileMacros(first, in: env, recursive: false) return try compiler.compileSeq(body, in: Env(group), inTailPos: tail) default: throw RuntimeError.type(first, expected: [.listType]) } } private func compileLetRecSyntax(_ compiler: Compiler, expr: Expr, env: Env, tail: Bool) throws -> Bool { guard case .pair(_, .pair(let first, let body)) = expr else { throw RuntimeError.argumentCount(of: "letrec-syntax", min: 1, expr: expr) } switch first { case .null: return try compiler.compileSeq(body, in: env, inTailPos: tail) case .pair(_, _): let group = try compiler.compileMacros(first, in: env, recursive: true) return try compiler.compileSeq(body, in: Env(group), inTailPos: tail) default: throw RuntimeError.type(first, expected: [.listType]) } } private func compileDo(_ compiler: Compiler, expr: Expr, env: Env, tail: Bool) throws -> Bool { // Decompose expression into bindings, exit, and body guard case .pair(_, .pair(let bindingList, .pair(let exit, let body))) = expr else { throw RuntimeError.argumentCount(of: "do", min: 2, expr: expr) } // Extract test and terminal expressions guard case .pair(let test, let terminal) = exit else { throw RuntimeError.eval(.malformedTest, exit) } let initialLocals = compiler.numLocals // Setup bindings let group = BindingGroup(owner: compiler, parent: env) var bindings = bindingList var prevIndex = -1 var doBindings = [Int]() var stepExprs = Exprs() // Compile initial bindings while case .pair(let binding, let rest) = bindings { guard case .pair(.symbol(let sym), .pair(let start, let optStep)) = binding else { throw RuntimeError.eval(.malformedBinding, binding, bindingList) } try compiler.compile(start, in: env, inTailPos: false) let index = group.allocBindingFor(sym).index guard index > prevIndex else { throw RuntimeError.eval(.duplicateBinding, .symbol(sym), bindingList) } compiler.emit(.makeLocalVariable(index)) switch optStep { case .pair(let step, .null): doBindings.append(index) stepExprs.append(step) case .null: break; default: throw RuntimeError.eval(.malformedBinding, binding, bindingList) } prevIndex = index bindings = rest } guard bindings.isNull else { throw RuntimeError.eval(.malformedBindings, bindingList) } // Compile test expression let testIp = compiler.offsetToNext(0) try compiler.compile(test, in: Env(group), inTailPos: false) let exitJumpIp = compiler.emitPlaceholder() // Compile body try compiler.compileSeq(body, in: Env(group), inTailPos: false) compiler.emit(.pop) // Compile step expressions and update bindings for step in stepExprs { try compiler.compile(step, in: Env(group), inTailPos: false) } for index in doBindings.reversed() { compiler.emit(.setLocalValue(index)) } // Loop compiler.emit(.branch(-compiler.offsetToNext(testIp))) // Exit if the test expression evaluates to true compiler.patch(.branchIf(compiler.offsetToNext(exitJumpIp)), at: exitJumpIp) // Compile terminal expressions let res = try compiler.compileSeq(terminal, in: Env(group), inTailPos: tail) // Remove bindings from stack if !res && compiler.numLocals > initialLocals { compiler.emit(.reset(initialLocals, compiler.numLocals - initialLocals)) } compiler.numLocals = initialLocals return res } private func compileIf(_ compiler: Compiler, expr: Expr, env: Env, tail: Bool) throws -> Bool { guard case .pair(_, .pair(let cond, .pair(let thenp, let alternative))) = expr else { throw RuntimeError.argumentCount(of: "if", min: 2, expr: expr) } var elsep = Expr.void if case .pair(let ep, .null) = alternative { elsep = ep } try compiler.compile(cond, in: env, inTailPos: false) let elseJumpIp = compiler.emitPlaceholder() // Compile if in tail position if try compiler.compile(elsep, in: env, inTailPos: tail) { compiler.patch(.branchIf(compiler.offsetToNext(elseJumpIp)), at: elseJumpIp) return try compiler.compile(thenp, in: env, inTailPos: true) } // Compile if in non-tail position let exitJumpIp = compiler.emitPlaceholder() compiler.patch(.branchIf(compiler.offsetToNext(elseJumpIp)), at: elseJumpIp) if try compiler.compile(thenp, in: env, inTailPos: tail) { compiler.patch(.return, at: exitJumpIp) return true } compiler.patch(.branch(compiler.offsetToNext(exitJumpIp)), at: exitJumpIp) return false } private func compileWhen(_ compiler: Compiler, expr: Expr, env: Env, tail: Bool) throws -> Bool { guard case .pair(_, .pair(let cond, let exprs)) = expr else { throw RuntimeError.argumentCount(of: "when", min: 1, expr: expr) } try compiler.compile(cond, in: env, inTailPos: false) let elseJumpIp = compiler.emitPlaceholder() compiler.emit(.pushVoid) let exitJumpIp = compiler.emitPlaceholder() compiler.patch(.branchIf(compiler.offsetToNext(elseJumpIp)), at: elseJumpIp) if try compiler.compileSeq(exprs, in: env, inTailPos: tail) { compiler.patch(.return, at: exitJumpIp) return true } compiler.patch(.branch(compiler.offsetToNext(exitJumpIp)), at: exitJumpIp) return false } private func compileUnless(_ compiler: Compiler, expr: Expr, env: Env, tail: Bool) throws -> Bool { guard case .pair(_, .pair(let cond, let exprs)) = expr else { throw RuntimeError.argumentCount(of: "unless", min: 1, expr: expr) } try compiler.compile(cond, in: env, inTailPos: false) let elseJumpIp = compiler.emitPlaceholder() compiler.emit(.pushVoid) let exitJumpIp = compiler.emitPlaceholder() compiler.patch(.branchIfNot(compiler.offsetToNext(elseJumpIp)), at: elseJumpIp) if try compiler.compileSeq(exprs, in: env, inTailPos: tail) { compiler.patch(.return, at: exitJumpIp) return true } compiler.patch(.branch(compiler.offsetToNext(exitJumpIp)), at: exitJumpIp) return false } private func compileCond(_ compiler: Compiler, expr: Expr, env: Env, tail: Bool) throws -> Bool { // Extract case list guard case .pair(_, let caseList) = expr else { preconditionFailure() } // Keep track of jumps for successful cases var exitJumps = [Int]() var exitOrJumps = [Int]() var cases = caseList // Track if there was an else case and whether there was a tail call in the else case var elseCaseTailCall: Bool? = nil // Iterate through all cases while case .pair(let cas, let rest) = cases { switch cas { case .pair(.symbol(let s), let exprs) where s.root == compiler.context.symbols.else: guard rest == .null else { throw RuntimeError.eval(.malformedCondClause, cases) } elseCaseTailCall = try compiler.compileSeq(exprs, in: env, inTailPos: tail) case .pair(let test, .null): try compiler.compile(test, in: env, inTailPos: false) exitOrJumps.append(compiler.emitPlaceholder()) case .pair(let test, .pair(.symbol(let s), .pair(let proc, .null))) where s.root == compiler.context.symbols.doubleArrow: // Compile condition try compiler.compile(test, in: env, inTailPos: false) // Jump if it's false or inject stack frame let escapeIp = compiler.emitPlaceholder() // Inject stack frame let pushFrameIp = compiler.emit(.injectFrame) // Compile procedure try compiler.compile(proc, in: env, inTailPos: false) // Swap procedure with argument (= condition) compiler.emit(.swap) // Call procedure if compiler.call(1, inTailPos: tail) { // Remove InjectFrame if this was a tail call compiler.patch(.noOp, at: pushFrameIp) } else { exitJumps.append(compiler.emitPlaceholder()) } compiler.patch(.keepOrBranchIfNot(compiler.offsetToNext(escapeIp)), at: escapeIp) case .pair(let test, let exprs): try compiler.compile(test, in: env, inTailPos: false) let escapeIp = compiler.emitPlaceholder() if !(try compiler.compileSeq(exprs, in: env, inTailPos: tail)) { exitJumps.append(compiler.emitPlaceholder()) } compiler.patch(.branchIfNot(compiler.offsetToNext(escapeIp)), at: escapeIp) default: throw RuntimeError.eval(.malformedCondClause, cas) } cases = rest } // Was there an else case? if let wasTailCall = elseCaseTailCall { // Did the else case and all other cases have tail calls? if wasTailCall && exitJumps.count == 0 && exitOrJumps.count == 0 { return true } } else { // There was no else case: return false compiler.emit(.pushFalse) } // Resolve jumps to current instruction for ip in exitJumps { compiler.patch(.branch(compiler.offsetToNext(ip)), at: ip) } for ip in exitOrJumps { compiler.patch(.or(compiler.offsetToNext(ip)), at: ip) } return false } private func compileCase(_ compiler: Compiler, expr: Expr, env: Env, tail: Bool) throws -> Bool { guard case .pair(_, .pair(let key, let caseList)) = expr else { throw RuntimeError.argumentCount(of: "case", min: 3, expr: expr) } // Keep track of jumps for successful cases var exitJumps = [Int]() var cases = caseList // Track if there was an else case and whether there was a tail call in the else case var elseCaseTailCall: Bool? = nil // Compile key try compiler.compile(key, in: env, inTailPos: false) // Compile cases while case .pair(let cas, let rest) = cases { switch cas { case .pair(.symbol(let s), .pair(.symbol(let t), .pair(let proc, .null))) where s.root == compiler.context.symbols.else && t.root == compiler.context.symbols.doubleArrow: guard rest == .null else { throw RuntimeError.eval(.malformedCaseClause, cases) } // Inject stack frame let pushFrameIp = compiler.emit(.injectFrame) // Compile procedure try compiler.compile(proc, in: env, inTailPos: false) // Swap procedure with argument (= condition) compiler.emit(.swap) // Call procedure if compiler.call(1, inTailPos: tail) { // Remove InjectFrame if this was a tail call compiler.patch(.noOp, at: pushFrameIp) elseCaseTailCall = true } else { elseCaseTailCall = false } case .pair(.symbol(let s), let exprs) where s.root == compiler.context.symbols.else: guard rest == .null else { throw RuntimeError.eval(.malformedCaseClause, cases) } compiler.emit(.pop) elseCaseTailCall = try compiler.compileSeq(exprs, in: env, inTailPos: tail) case .pair(var keys, .pair(.symbol(let s), .pair(let proc, .null))) where s.root == compiler.context.symbols.doubleArrow: // Check keys var positiveJumps = [Int]() while case .pair(let value, let next) = keys { compiler.emit(.dup) try compiler.pushValue(value) compiler.emit(.eqv) positiveJumps.append(compiler.emitPlaceholder()) keys = next } guard keys.isNull else { throw RuntimeError.eval(.malformedCaseClause, cas) } let jumpToNextCase = compiler.emitPlaceholder() for ip in positiveJumps { compiler.patch(.branchIf(compiler.offsetToNext(ip)), at: ip) } // Inject stack frame let pushFrameIp = compiler.emit(.injectFrame) // Compile procedure try compiler.compile(proc, in: env, inTailPos: false) // Swap procedure with argument (= condition) compiler.emit(.swap) // Call procedure if compiler.call(1, inTailPos: tail) { // Remove InjectFrame if this was a tail call compiler.patch(.noOp, at: pushFrameIp) } else { exitJumps.append(compiler.emitPlaceholder()) } compiler.patch(.branch(compiler.offsetToNext(jumpToNextCase)), at: jumpToNextCase) case .pair(var keys, let exprs): var positiveJumps = [Int]() while case .pair(let value, let next) = keys { compiler.emit(.dup) try compiler.pushValue(value) compiler.emit(.eqv) positiveJumps.append(compiler.emitPlaceholder()) keys = next } guard keys.isNull else { throw RuntimeError.eval(.malformedCaseClause, cas) } let jumpToNextCase = compiler.emitPlaceholder() for ip in positiveJumps { compiler.patch(.branchIf(compiler.offsetToNext(ip)), at: ip) } compiler.emit(.pop) if !(try compiler.compileSeq(exprs, in: env, inTailPos: tail)) { exitJumps.append(compiler.emitPlaceholder()) } compiler.patch(.branch(compiler.offsetToNext(jumpToNextCase)), at: jumpToNextCase) default: throw RuntimeError.eval(.malformedCaseClause, cas) } cases = rest } // Was there an else case? if let wasTailCall = elseCaseTailCall { // Did the else case and all other cases have tail calls? if wasTailCall && exitJumps.count == 0 { return true } } else { // There was no else case: drop key and return false compiler.emit(.pop) compiler.emit(.pushFalse) } // Resolve jumps to current instruction for ip in exitJumps { compiler.patch(.branch(compiler.offsetToNext(ip)), at: ip) } return false } }
373d44cbd621b54dad020fa5469c142b
41.594692
100
0.583416
false
false
false
false
brentsimmons/Evergreen
refs/heads/ios-candidate
Shared/Images/ImageDownloader.swift
mit
1
// // ImageDownloader.swift // NetNewsWire // // Created by Brent Simmons on 11/25/17. // Copyright © 2017 Ranchero Software. All rights reserved. // import Foundation import os.log import RSCore import RSWeb extension Notification.Name { static let ImageDidBecomeAvailable = Notification.Name("ImageDidBecomeAvailableNotification") // UserInfoKey.url } final class ImageDownloader { private var log = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "ImageDownloader") private let folder: String private var diskCache: BinaryDiskCache private let queue: DispatchQueue private var imageCache = [String: Data]() // url: image private var urlsInProgress = Set<String>() private var badURLs = Set<String>() // That return a 404 or whatever. Just skip them in the future. init(folder: String) { self.folder = folder self.diskCache = BinaryDiskCache(folder: folder) self.queue = DispatchQueue(label: "ImageDownloader serial queue - \(folder)") } @discardableResult func image(for url: String) -> Data? { if let data = imageCache[url] { return data } findImage(url) return nil } } private extension ImageDownloader { func cacheImage(_ url: String, _ image: Data) { imageCache[url] = image postImageDidBecomeAvailableNotification(url) } func findImage(_ url: String) { guard !urlsInProgress.contains(url) && !badURLs.contains(url) else { return } urlsInProgress.insert(url) readFromDisk(url) { (image) in if let image = image { self.cacheImage(url, image) self.urlsInProgress.remove(url) return } self.downloadImage(url) { (image) in if let image = image { self.cacheImage(url, image) } self.urlsInProgress.remove(url) } } } func readFromDisk(_ url: String, _ completion: @escaping (Data?) -> Void) { queue.async { if let data = self.diskCache[self.diskKey(url)], !data.isEmpty { DispatchQueue.main.async { completion(data) } return } DispatchQueue.main.async { completion(nil) } } } func downloadImage(_ url: String, _ completion: @escaping (Data?) -> Void) { guard let imageURL = URL(string: url) else { completion(nil) return } downloadUsingCache(imageURL) { (data, response, error) in if let data = data, !data.isEmpty, let response = response, response.statusIsOK, error == nil { self.saveToDisk(url, data) completion(data) return } if let response = response as? HTTPURLResponse, response.statusCode >= HTTPResponseCode.badRequest && response.statusCode <= HTTPResponseCode.notAcceptable { self.badURLs.insert(url) } if let error = error { os_log(.info, log: self.log, "Error downloading image at %@: %@.", url, error.localizedDescription) } completion(nil) } } func saveToDisk(_ url: String, _ data: Data) { queue.async { self.diskCache[self.diskKey(url)] = data } } func diskKey(_ url: String) -> String { return url.md5String } func postImageDidBecomeAvailableNotification(_ url: String) { DispatchQueue.main.async { NotificationCenter.default.post(name: .ImageDidBecomeAvailable, object: self, userInfo: [UserInfoKey.url: url]) } } }
a479912f557c1c284c6a4dee5f0e27e2
21.34965
160
0.692428
false
false
false
false
gizmosachin/VolumeBar
refs/heads/master
Sources/Internal/SystemVolumeManager.swift
mit
1
// // SystemVolumeManager.swift // // Copyright (c) 2016-Present Sachin Patel (http://gizmosachin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit import AVFoundation @objc internal protocol SystemVolumeObserver { func volumeChanged(to volume: Float) } internal final class SystemVolumeManager: NSObject { fileprivate let observers: NSHashTable<SystemVolumeObserver> fileprivate var isObservingSystemVolumeChanges: Bool = false internal override init() { observers = NSHashTable<SystemVolumeObserver>.weakObjects() super.init() startObservingSystemVolumeChanges() startObservingApplicationStateChanges() } deinit { observers.removeAllObjects() stopObservingSystemVolumeChanges() stopObservingApplicationStateChanges() } public func volumeChanged(to volume: Float) { for case let observer as SystemVolumeObserver in observers.objectEnumerator() { observer.volumeChanged(to: volume) } } } // System Volume Changes internal extension SystemVolumeManager { func startObservingSystemVolumeChanges() { try? AVAudioSession.sharedInstance().setActive(true) if !isObservingSystemVolumeChanges { // Observe system volume changes AVAudioSession.sharedInstance().addObserver(self, forKeyPath: #keyPath(AVAudioSession.outputVolume), options: [.old, .new], context: nil) // We need to manually set this to avoid adding ourselves as an observer twice. // This can happen if VolumeBar is started and the app has just launched. // Without this, KVO retains us and we crash when system volume changes after stop() is called. :( isObservingSystemVolumeChanges = true } } func stopObservingSystemVolumeChanges() { // Stop observing system volume changes if isObservingSystemVolumeChanges { AVAudioSession.sharedInstance().removeObserver(self, forKeyPath: #keyPath(AVAudioSession.outputVolume)) isObservingSystemVolumeChanges = false } } /// Observe changes in volume. /// /// This method is called when the user presses either of the volume buttons. override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { let volume = AVAudioSession.sharedInstance().outputVolume volumeChanged(to: volume) } } // Application State Changes internal extension SystemVolumeManager { func startObservingApplicationStateChanges() { // Add application state observers NotificationCenter.default.addObserver(self, selector: #selector(SystemVolumeManager.applicationWillResignActive(notification:)), name: UIApplication.willResignActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(SystemVolumeManager.applicationDidBecomeActive(notification:)), name: UIApplication.didBecomeActiveNotification, object: nil) } func stopObservingApplicationStateChanges() { // Remove application state observers NotificationCenter.default.removeObserver(self, name: UIApplication.willResignActiveNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil) } /// Observe when the application background state changes. @objc func applicationWillResignActive(notification: Notification) { // Stop observing volume while in the background stopObservingSystemVolumeChanges() } @objc func applicationDidBecomeActive(notification: Notification) { // Restart session after becoming active startObservingSystemVolumeChanges() } } // Volume Manager Observers internal extension SystemVolumeManager { func addObserver(_ observer: SystemVolumeObserver) { observers.add(observer) } func removeObserver(_ observer: SystemVolumeObserver) { observers.remove(observer) } }
324667827273704d88c880c8ebe72517
37.062992
194
0.779892
false
false
false
false
Camvergence/AssetFlow
refs/heads/master
PhotosPlus/PhotosPlus/UIImageView_PHAsset.swift
mit
3
// // Photos Plus, https://github.com/LibraryLoupe/PhotosPlus // // Copyright (c) 2016-2017 Matt Klosterman and contributors. All rights reserved. // #if os(iOS) || os(tvOS) import Foundation import UIKit import Photos extension UIImageView { public func loadAsset(_ asset: PHAsset?, version: PHImageRequestOptionsVersion = .current, options: PHImageRequestOptions, imageManager: PHImageManager? = nil, completion: @escaping () -> Void) -> PHImageRequestID { guard let asset = asset else { return PHInvalidImageRequestID } let manager = imageManager ?? PHImageManager.default() return manager.requestImage(for: asset, targetSize: bounds.size.screenScaled(), contentMode: .aspectFit, options: options) { [weak self] (image, _) in self?.image = image completion() } } } #endif
0eb9b44633197c3245a9a0d9f0b51852
28.054054
82
0.546047
false
false
false
false
bhajian/raspi-remote
refs/heads/master
Carthage/Checkouts/ios-sdk/Source/AlchemyLanguageV1/Models/ConceptResponse.swift
mit
1
/** * Copyright IBM Corporation 2015 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation import Freddy /** **ConceptResponse** Response object for Concept related calls */ public struct ConceptResponse: JSONDecodable { /** extracted language */ public let language: String? /** the URL information was requested for */ public let url: String? /** number of transactions made by the call */ public let totalTransactions: Int? /** see **Concept** */ public let concepts: [Concept]? /// Used internally to initialize a ConceptResponse object public init(json: JSON) throws { language = try? json.string("language") url = try? json.string("url") if let totalTransactionsString = try? json.string("totalTransactions") { totalTransactions = Int(totalTransactionsString) } else { totalTransactions = 1 } concepts = try? json.arrayOf("concepts", type: Concept.self) } }
f808d79951a348c8fb96ac0dc3e71dec
27.054545
80
0.671419
false
false
false
false
ric2b/Vivaldi-browser
refs/heads/main
chromium/ios/chrome/browser/widget_kit/user_defaults_widget_store.swift
bsd-3-clause
2
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import Foundation /// An object that stores and retrieves the widget configurations from user defaults. public struct UserDefaultsWidgetStore { /// The key that the current widget configurations are stored under in the user defaults. private let widgetInfoKey = "com.google.chrome.ios.widgets.widget-info" // Use UserDefaults.standard because this information only needs to be stored and retrieved from // the main app. private let userDefaults = UserDefaults.standard public func storeWidgetInfo(_ info: [String]) throws { let encoder = JSONEncoder() let data = try encoder.encode(info) userDefaults.set(data, forKey: widgetInfoKey) } public func retrieveStoredWidgetInfo() -> Result<[String], Error> { guard let data = userDefaults.data(forKey: widgetInfoKey) else { // If there is no stored data, return an empty array. return .success([]) } let decoder = JSONDecoder() return Result { return try decoder.decode(Array<String>.self, from: data) } } }
2791b9274972541922822be2ad3ba748
33.114286
98
0.725063
false
true
false
false
rustedivan/tapmap
refs/heads/master
tapmap/Rendering/BorderRenderer.swift
mit
1
// // BorderRenderer.swift // tapmap // // Created by Ivan Milles on 2020-04-13. // Copyright © 2019 Wildbrain. All rights reserved. // import Metal import simd fileprivate struct FrameUniforms { let mvpMatrix: simd_float4x4 let width: simd_float1 var color: simd_float4 } struct BorderContour { let contours: [VertexRing] } class BorderRenderer<RegionType> { typealias LoddedBorderHash = Int let rendererLabel: String let device: MTLDevice let pipeline: MTLRenderPipelineState let maxVisibleLineSegments: Int var lineSegmentsHighwaterMark: Int = 0 var borderContours: [LoddedBorderHash : BorderContour] var frameSelectSemaphore = DispatchSemaphore(value: 1) let lineSegmentPrimitive: LineSegmentPrimitive let instanceUniforms: [MTLBuffer] var frameLineSegmentCount: [Int] = [] var borderScale: Float var width: Float = 1.0 var color: simd_float4 = simd_float4(0.0, 0.0, 0.0, 1.0) var actualBorderLod: Int = 10 var wantedBorderLod: Int init(withDevice device: MTLDevice, pixelFormat: MTLPixelFormat, bufferCount: Int, maxSegments: Int, label: String) { borderScale = 0.0 let shaderLib = device.makeDefaultLibrary()! let pipelineDescriptor = MTLRenderPipelineDescriptor() pipelineDescriptor.sampleCount = 4 pipelineDescriptor.vertexFunction = shaderLib.makeFunction(name: "lineVertex") pipelineDescriptor.fragmentFunction = shaderLib.makeFunction(name: "lineFragment") pipelineDescriptor.colorAttachments[0].pixelFormat = pixelFormat; pipelineDescriptor.vertexBuffers[0].mutability = .immutable do { try pipeline = device.makeRenderPipelineState(descriptor: pipelineDescriptor) self.rendererLabel = label self.device = device self.frameLineSegmentCount = Array(repeating: 0, count: bufferCount) self.maxVisibleLineSegments = maxSegments // Determined experimentally and rounded up a lot self.instanceUniforms = (0..<bufferCount).map { bufferIndex in device.makeBuffer(length: maxSegments * MemoryLayout<LineInstanceUniforms>.stride, options: .storageModeShared)! } self.lineSegmentPrimitive = makeLineSegmentPrimitive(in: device, inside: -0.05, outside: 0.95) } catch let error { fatalError(error.localizedDescription) } borderContours = [:] wantedBorderLod = GeometryStreamer.shared.wantedLodLevel } func setStyle(innerWidth: Float, outerWidth: Float, color: simd_float4) { self.width = innerWidth self.color = color } func prepareFrame(borderedRegions: [Int : RegionType], zoom: Float, zoomRate: Float, inside renderBox: Aabb, bufferIndex: Int) { let streamer = GeometryStreamer.shared let lodLevel = streamer.wantedLodLevel var borderLodMiss = false // Stream in any missing geometries at the wanted LOD level for borderHash in borderedRegions.keys { let loddedBorderHash = borderHashLodKey(borderHash, atLod: lodLevel) if borderContours[loddedBorderHash] == nil { borderLodMiss = true if let tessellation = streamer.tessellation(for: borderHash, atLod: lodLevel, streamIfMissing: true) { borderContours[loddedBorderHash] = BorderContour(contours: tessellation.contours) } } } // Update the LOD level if we have all its geometries if !borderLodMiss && actualBorderLod != streamer.wantedLodLevel { actualBorderLod = streamer.wantedLodLevel } // Collect the vertex rings for the visible set of borders let frameRenderList: [BorderContour] = borderedRegions.compactMap { let loddedKey = borderHashLodKey($0.key, atLod: actualBorderLod) return borderContours[loddedKey] } // Generate all the vertices in all the outlines let regionContours = frameRenderList.flatMap { $0.contours } var borderBuffer = generateContourLineGeometry(contours: regionContours, inside: renderBox) guard borderBuffer.count < maxVisibleLineSegments else { assert(false, "line segment buffer blew out at \(borderBuffer.count) vertices (max \(maxVisibleLineSegments))") borderBuffer = Array(borderBuffer[0..<maxVisibleLineSegments]) } let borderZoom = zoom / (1.0 - zoomRate + zoomRate * Stylesheet.shared.borderZoomBias.value) // Borders become wider at closer zoom levels frameSelectSemaphore.wait() self.borderScale = 1.0 / borderZoom self.frameLineSegmentCount[bufferIndex] = borderBuffer.count self.instanceUniforms[bufferIndex].contents().copyMemory(from: borderBuffer, byteCount: MemoryLayout<LineInstanceUniforms>.stride * borderBuffer.count) if borderBuffer.count > lineSegmentsHighwaterMark { lineSegmentsHighwaterMark = borderBuffer.count print("\(rendererLabel) used a max of \(lineSegmentsHighwaterMark) line segments.") } frameSelectSemaphore.signal() } func renderBorders(inProjection projection: simd_float4x4, inEncoder encoder: MTLRenderCommandEncoder, bufferIndex: Int) { encoder.pushDebugGroup("Render \(rendererLabel)'s borders") defer { encoder.popDebugGroup() } frameSelectSemaphore.wait() var uniforms = FrameUniforms(mvpMatrix: projection, width: width * borderScale, color: color) let instances = instanceUniforms[bufferIndex] let count = frameLineSegmentCount[bufferIndex] frameSelectSemaphore.signal() if count == 0 { return } encoder.setRenderPipelineState(pipeline) encoder.setVertexBytes(&uniforms, length: MemoryLayout.stride(ofValue: uniforms), index: 1) encoder.setVertexBuffer(instances, offset: 0, index: 2) renderInstanced(primitive: lineSegmentPrimitive, count: count, into: encoder) } func borderHashLodKey(_ regionHash: RegionHash, atLod lod: Int) -> LoddedBorderHash { return "\(regionHash)-\(lod)".hashValue } }
b0cd0ed59901fbe096c287386b7bbdf9
34.886076
154
0.755908
false
false
false
false
seivan/SpriteKitComposition
refs/heads/develop
TestsAndSample/Tests/SampleComponent.swift
mit
1
// // SampleComponent.swift // TestsAndSample // // Created by Seivan Heidari on 26/11/14. // Copyright (c) 2014 Seivan Heidari. All rights reserved. // import UIKit import SpriteKit class SampleComponent: Component { var assertionDidAddToNode:SKNode! = nil var assertionDidAddNodeToScene:SKScene! = nil var assertionDidRemoveFromNode:SKNode! = nil var assertionDidRemoveNodeFromScene:SKScene! = nil var assertionDidChangeSceneSizedFrom:CGSize! = nil var assertionDidMoveToView:SKView! = nil var assertionWillMoveFromView:SKView! = nil var assertionDidUpdate:NSTimeInterval! = nil var assertionDidEvaluateActions = false var assertionDidSimulatePhysics = false var assertionDidApplyConstraints = false var assertionDidFinishUpdate = false var assertionDidContactSceneStarted:(contact:SKPhysicsContact, state:ComponentState)! = nil var assertionDidContactSceneCompleted:(contact:SKPhysicsContact, state:ComponentState)! = nil var assertionDidContactNodeStarted:(node:SKNode, contact:SKPhysicsContact, state:ComponentState)! = nil var assertionDidContactNodeCompleted:(node:SKNode, contact:SKPhysicsContact, state:ComponentState)! = nil var assertionDidTouchSceneStarted:(touches:[UITouch], state:ComponentState)! = nil var assertionDidTouchSceneChanged:(touches:[UITouch], state:ComponentState)! = nil var assertionDidTouchSceneCompleted:(touches:[UITouch], state:ComponentState)! = nil var assertionDidTouchSceneCancelled:(touches:[UITouch], state:ComponentState)! = nil var assertionDidTouchNodeStarted:(touches:[UITouch], state:ComponentState)! = nil var assertionDidTouchNodeChanged:(touches:[UITouch], state:ComponentState)! = nil var assertionDidTouchNodeCompleted:(touches:[UITouch], state:ComponentState)! = nil var assertionDidTouchNodeCancelled:(touches:[UITouch], state:ComponentState)! = nil // var assertionDidBeginContactWithNode:(node:SKNode, contact:SKPhysicsContact)! = nil // var assertionDidEndContactWithNode:(node:SKNode, contact:SKPhysicsContact)! = nil // var assertionDidBeginContact:SKPhysicsContact! = nil // var assertionDidEndContact:SKPhysicsContact! = nil // // var assertionDidBeginNodeTouches:[UITouch]! = nil // var assertionDidMoveNodeTouches:[UITouch]! = nil // var assertionDidEndNodeTouches:[UITouch]! = nil // var assertionDidCancelNodeTouches:[UITouch]! = nil // var assertionDidBeginSceneTouches:[UITouch]! = nil // var assertionDidMoveSceneTouches:[UITouch]! = nil // var assertionDidEndSceneTouches:[UITouch]! = nil // var assertionDidCancelSceneTouches:[UITouch]! = nil func didAddToNode(node:SKNode) { self.assertionDidAddToNode = node } func didAddNodeToScene(scene:SKScene) { self.assertionDidAddNodeToScene = scene } func didRemoveFromNode(node:SKNode) { self.assertionDidRemoveFromNode = node } func didRemoveNodeFromScene(scene:SKScene) { self.assertionDidRemoveNodeFromScene = scene } func didChangeSceneSizedFrom(previousSize:CGSize) { self.assertionDidChangeSceneSizedFrom = previousSize } func didMoveToView(view: SKView) { self.assertionDidMoveToView = view } func willMoveFromView(view: SKView) { self.assertionWillMoveFromView = view } func didUpdate(time:NSTimeInterval) { self.assertionDidUpdate = time } func didEvaluateActions() { self.assertionDidEvaluateActions = true } func didSimulatePhysics() { self.assertionDidSimulatePhysics = true } func didApplyConstraints() { self.assertionDidApplyConstraints = true } func didFinishUpdate() { self.assertionDidFinishUpdate = true } func didContactScene(contact:SKPhysicsContact, state:ComponentState) { switch state.value { case ComponentState.Started.value: self.assertionDidContactSceneStarted = (contact:contact, state:state) case ComponentState.Completed.value: self.assertionDidContactSceneCompleted = (contact:contact, state:state) default: self.assertionDidContactSceneCompleted = nil self.assertionDidContactSceneStarted = nil } } func didContactNode(node:SKNode, contact:SKPhysicsContact, state:ComponentState) { switch state.value { case ComponentState.Started.value: self.assertionDidContactNodeStarted = (node:node, contact:contact, state:state) case ComponentState.Completed.value: self.assertionDidContactNodeCompleted = (node:node, contact:contact, state:state) default: self.assertionDidContactNodeStarted = (node:node, contact:contact, state:state) self.assertionDidContactNodeCompleted = (node:node, contact:contact, state:state) } } func didTouchScene(touches:[UITouch], state:ComponentState) { switch state.value { case ComponentState.Started.value: self.assertionDidTouchSceneStarted = (touches:touches, state:state) case ComponentState.Changed.value: self.assertionDidTouchSceneChanged = (touches:touches, state:state) case ComponentState.Completed.value: self.assertionDidTouchSceneCompleted = (touches:touches, state:state) case ComponentState.Cancelled.value: self.assertionDidTouchSceneCancelled = (touches:touches, state:state) default: self.assertionDidTouchSceneStarted = nil self.assertionDidTouchSceneChanged = nil self.assertionDidTouchSceneCompleted = nil self.assertionDidTouchSceneCancelled = nil } } func didTouchNode(touches:[UITouch], state:ComponentState) { switch state.value { case ComponentState.Started.value: self.assertionDidTouchNodeStarted = (touches:touches, state:state) case ComponentState.Changed.value: self.assertionDidTouchNodeChanged = (touches:touches, state:state) case ComponentState.Completed.value: self.assertionDidTouchNodeCompleted = (touches:touches, state:state) case ComponentState.Cancelled.value: self.assertionDidTouchNodeCancelled = (touches:touches, state:state) default: self.assertionDidTouchNodeStarted = nil self.assertionDidTouchNodeChanged = nil self.assertionDidTouchNodeCompleted = nil self.assertionDidTouchNodeCancelled = nil } } }
5cd511d01d072994be273e4ac01ba096
37.918239
107
0.763413
false
false
false
false
noppoMan/Prorsum
refs/heads/master
Sources/Prorsum/Go/Channel.swift
mit
1
// // Channel.swift // Prorsum // // Created by Yuki Takei on 2016/11/23. // // import Foundation #if os(Linux) import func CoreFoundation._CFIsMainThread // avoid unimplemented error private extension Thread { static var isMainThread: Bool { return _CFIsMainThread() } } #endif class IDGenerator { static let shared = IDGenerator() private var _currentId = 0 private let mutex = Mutex() init(){} func currentId() -> Int { mutex.lock() _currentId+=1 mutex.unlock() return _currentId } } public enum ChannelError: Error { case receivedOnClosedChannel case sendOnClosedChannel case bufferSizeLimitExceeded(Int) } public class Channel<T> { let id : Int var messageQ = Queue<T>() public private(set) var capacity: Int let cond = Cond() public fileprivate(set) var isClosed = false // have to use Channel<T>.make() to initialize the Channel init(capacity: Int){ self.capacity = capacity self.id = IDGenerator.shared.currentId() } public func count() -> Int { if capacity == 0 { return 0 } return messageQ.count } public func send(_ message: T) throws { cond.mutex.lock() defer { cond.mutex.unlock() } if isClosed { throw ChannelError.sendOnClosedChannel } messageQ.push(message) cond.broadcast() if Thread.isMainThread, messageQ.count > capacity { throw ChannelError.bufferSizeLimitExceeded(capacity) } } public func nonBlockingReceive() throws -> T? { cond.mutex.lock() defer { cond.mutex.unlock() } if let f = messageQ.front { messageQ.pop() cond.broadcast() return f.value } if isClosed { throw ChannelError.receivedOnClosedChannel } return nil } public func receive() throws -> T { cond.mutex.lock() defer { cond.mutex.unlock() } while true { if let f = messageQ.front { messageQ.pop() cond.broadcast() return f.value } if isClosed { throw ChannelError.receivedOnClosedChannel } cond.wait() } } public func close(){ cond.mutex.lock() cond.broadcast() isClosed = true cond.mutex.unlock() } } extension Channel { public static func make(capacity: Int = 0) -> Channel<T> { return Channel<T>(capacity: capacity) } }
adc9de2bdd659f05ed64c157c4339771
19.435714
64
0.520098
false
false
false
false
AlexanderMazaletskiy/SAHistoryNavigationViewController
refs/heads/master
SAHistoryNavigationViewController/SAHistoryNavigationTransitionController.swift
mit
2
// // SAHistoryNavigationTransitionController.swift // SAHistoryNavigationViewController // // Created by 鈴木大貴 on 2015/05/26. // Copyright (c) 2015年 鈴木大貴. All rights reserved. // import UIKit class SAHistoryNavigationTransitionController: NSObject, UIViewControllerAnimatedTransitioning { private static let kDefaultDuration: NSTimeInterval = 0.3 private(set) var navigationControllerOperation: UINavigationControllerOperation private var currentTransitionContext: UIViewControllerContextTransitioning? private var backgroundView: UIView? private var alphaView: UIView? required init(operation: UINavigationControllerOperation) { navigationControllerOperation = operation super.init() } func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return SAHistoryNavigationTransitionController.kDefaultDuration } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { guard let containerView = transitionContext.containerView(), fromView = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)?.view, toView = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)?.view else { return } currentTransitionContext = transitionContext switch navigationControllerOperation { case .Push: pushAnimation(transitionContext, toView: toView, fromView: fromView, containerView: containerView) case .Pop: popAnimation(transitionContext, toView: toView, fromView: fromView, containerView: containerView) case .None: let cancelled = transitionContext.transitionWasCancelled() transitionContext.completeTransition(!cancelled) } } } //MARK: - Internal Methods extension SAHistoryNavigationTransitionController { func forceFinish() { let navigationControllerOperation = self.navigationControllerOperation if let backgroundView = backgroundView, alphaView = alphaView { let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64((SAHistoryNavigationTransitionController.kDefaultDuration + 0.1) * Double(NSEC_PER_SEC))) dispatch_after(dispatchTime, dispatch_get_main_queue()) { [weak self] in if let currentTransitionContext = self?.currentTransitionContext { let toViewContoller = currentTransitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) let fromViewContoller = currentTransitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) if let fromView = fromViewContoller?.view, toView = toViewContoller?.view { switch navigationControllerOperation { case .Push: self?.pushAniamtionCompletion(currentTransitionContext, toView: toView, fromView: fromView, backgroundView: backgroundView, alphaView: alphaView) case .Pop: self?.popAniamtionCompletion(currentTransitionContext, toView: toView, fromView: fromView, backgroundView: backgroundView, alphaView: alphaView) case .None: let cancelled = currentTransitionContext.transitionWasCancelled() currentTransitionContext.completeTransition(!cancelled) } self?.currentTransitionContext = nil self?.backgroundView = nil self?.alphaView = nil } } } } } } //MARK: - Private Methods extension SAHistoryNavigationTransitionController { private func popAnimation(transitionContext: UIViewControllerContextTransitioning, toView: UIView, fromView: UIView, containerView: UIView) { let backgroundView = UIView(frame: containerView.bounds) backgroundView.backgroundColor = .blackColor() containerView.addSubview(backgroundView) self.backgroundView = backgroundView toView.frame = containerView.bounds containerView.addSubview(toView) let alphaView = UIView(frame: containerView.bounds) alphaView.backgroundColor = .blackColor() containerView.addSubview(alphaView) self.alphaView = alphaView fromView.frame = containerView.bounds containerView.addSubview(fromView) let completion: (Bool) -> Void = { [weak self] finished in if finished { self?.popAniamtionCompletion(transitionContext, toView: toView, fromView: fromView, backgroundView: backgroundView, alphaView: alphaView) } } toView.frame.origin.x = -(toView.frame.size.width / 4.0) alphaView.alpha = 0.4 UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0.0, options: .CurveEaseOut, animations: { toView.frame.origin.x = 0 fromView.frame.origin.x = containerView.frame.size.width alphaView.alpha = 0.0 }, completion: completion) } private func popAniamtionCompletion(transitionContext: UIViewControllerContextTransitioning, toView: UIView, fromView: UIView, backgroundView: UIView, alphaView: UIView) { let cancelled = transitionContext.transitionWasCancelled() if cancelled { toView.transform = CGAffineTransformIdentity toView.removeFromSuperview() } else { fromView.removeFromSuperview() } backgroundView.removeFromSuperview() alphaView.removeFromSuperview() transitionContext.completeTransition(!cancelled) currentTransitionContext = nil self.backgroundView = nil self.alphaView = nil } private func pushAnimation(transitionContext: UIViewControllerContextTransitioning, toView: UIView, fromView: UIView, containerView: UIView) { let backgroundView = UIView(frame: containerView.bounds) backgroundView.backgroundColor = .blackColor() containerView.addSubview(backgroundView) self.backgroundView = backgroundView fromView.frame = containerView.bounds containerView.addSubview(fromView) let alphaView = UIView(frame: containerView.bounds) alphaView.backgroundColor = .blackColor() alphaView.alpha = 0.0 containerView.addSubview(alphaView) self.alphaView = alphaView toView.frame = containerView.bounds toView.frame.origin.x = containerView.frame.size.width containerView.addSubview(toView) let completion: (Bool) -> Void = { [weak self] finished in if finished { self?.pushAniamtionCompletion(transitionContext, toView: toView, fromView: fromView, backgroundView: backgroundView, alphaView: alphaView) } } UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0.0, options: .CurveEaseOut, animations: { fromView.frame.origin.x = -(fromView.frame.size.width / 4.0) toView.frame.origin.x = 0.0 alphaView.alpha = 0.4 }, completion: completion) } private func pushAniamtionCompletion(transitionContext: UIViewControllerContextTransitioning, toView: UIView, fromView: UIView, backgroundView: UIView, alphaView: UIView) { let cancelled = transitionContext.transitionWasCancelled() if cancelled { toView.removeFromSuperview() } fromView.transform = CGAffineTransformIdentity backgroundView.removeFromSuperview() fromView.removeFromSuperview() alphaView.removeFromSuperview() transitionContext.completeTransition(!cancelled) currentTransitionContext = nil self.backgroundView = nil self.alphaView = nil } }
b26fd3ab8ed8e8aa3f605bd6fb15bf34
42.557292
177
0.656702
false
false
false
false
barbosa/clappr-ios
refs/heads/master
Pod/Classes/Enum/ContainerEvent.swift
bsd-3-clause
1
public enum ContainerEvent: String { case PlaybackStateChanged = "clappr:container:playback_state_changed" case PlaybackDVRStateChanged = "clappr:container:playback_dvr_state_changed" case BitRate = "clappr:container:bit_rate" case Destroyed = "clappr:container:destroyed" case Ready = "clappr:container:ready" case Error = "clappr:container:error" case LoadedMetadata = "clappr:container:loaded_metadata" case TimeUpdated = "clappr:container:time_update" case Progress = "clappr:container:progress" case Play = "clappr:container:play" case Stop = "clappr:container:stop" case Pause = "clappr:container:pause" case Ended = "clappr:container:ended" case Tap = "clappr:container:tap" case Seek = "clappr:container:seek" case Volume = "clappr:container:volume" case Buffering = "clappr:container:buffering" case BufferFull = "clappr:container:buffer_full" case SettingsUpdated = "clappr:container:settings_updated" case HighDefinitionUpdated = "clappr:container:hd_updated" case MediaControlDisabled = "clappr:container:media_control_disabled" case MediaControlEnabled = "clappr:container:media_control_enabled" case AudioSourcesUpdated = "clappr:container:audio_sources_updated" case SubtitleSourcesUpdated = "clappr:container:subtitle_sources_updated" case SourceChanged = "clappr:container:source_changed" }
dafc7f13b9a02695fbb53360ea81e5a3
51.148148
80
0.749112
false
false
false
false
ArnavChawla/InteliChat
refs/heads/master
Carthage/Checkouts/swift-sdk/Source/VisualRecognitionV3/Models/ClassifiedImage.swift
mit
1
/** * Copyright IBM Corporation 2018 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation /** Results for one image. */ public struct ClassifiedImage: Decodable { /// Source of the image before any redirects. Not returned when the image is uploaded. public var sourceUrl: String? /// Fully resolved URL of the image after redirects are followed. Not returned when the image is uploaded. public var resolvedUrl: String? /// Relative path of the image file if uploaded directly. Not returned when the image is passed by URL. public var image: String? public var error: ErrorInfo? /// The classifiers. public var classifiers: [ClassifierResult] // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case sourceUrl = "source_url" case resolvedUrl = "resolved_url" case image = "image" case error = "error" case classifiers = "classifiers" } }
f1deb7086839c631df777e51c59c8734
33.022222
110
0.70934
false
false
false
false
RxSwiftCommunity/RxMKMapView
refs/heads/develop
Example/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift
gpl-3.0
5
// // RxCollectionViewDataSourceProxy.swift // RxCocoa // // Created by Krunoslav Zaher on 6/29/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit import RxSwift extension UICollectionView: HasDataSource { public typealias DataSource = UICollectionViewDataSource } private let collectionViewDataSourceNotSet = CollectionViewDataSourceNotSet() private final class CollectionViewDataSourceNotSet : NSObject , UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 0 } // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { rxAbstractMethod(message: dataSourceNotSet) } } /// For more information take a look at `DelegateProxyType`. open class RxCollectionViewDataSourceProxy : DelegateProxy<UICollectionView, UICollectionViewDataSource> , DelegateProxyType , UICollectionViewDataSource { /// Typed parent object. public weak private(set) var collectionView: UICollectionView? /// - parameter collectionView: Parent object for delegate proxy. public init(collectionView: ParentObject) { self.collectionView = collectionView super.init(parentObject: collectionView, delegateProxy: RxCollectionViewDataSourceProxy.self) } // Register known implementations public static func registerKnownImplementations() { self.register { RxCollectionViewDataSourceProxy(collectionView: $0) } } private weak var _requiredMethodsDataSource: UICollectionViewDataSource? = collectionViewDataSourceNotSet // MARK: delegate /// Required delegate method implementation. public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { (_requiredMethodsDataSource ?? collectionViewDataSourceNotSet).collectionView(collectionView, numberOfItemsInSection: section) } /// Required delegate method implementation. public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { (_requiredMethodsDataSource ?? collectionViewDataSourceNotSet).collectionView(collectionView, cellForItemAt: indexPath) } /// For more information take a look at `DelegateProxyType`. open override func setForwardToDelegate(_ forwardToDelegate: UICollectionViewDataSource?, retainDelegate: Bool) { _requiredMethodsDataSource = forwardToDelegate ?? collectionViewDataSourceNotSet super.setForwardToDelegate(forwardToDelegate, retainDelegate: retainDelegate) } } #endif
ec8b0ea018083febf51001a130114be4
36.526316
134
0.764025
false
false
false
false
6ag/BaoKanIOS
refs/heads/master
BaoKanIOS/Classes/Module/Profile/View/Info/JFInfoHeaderView.swift
apache-2.0
1
// // JFInfoHeaderView.swift // BaoKanIOS // // Created by zhoujianfeng on 16/5/26. // Copyright © 2016年 六阿哥. All rights reserved. // import UIKit import YYWebImage import SnapKit class JFInfoHeaderView: UIView { override init(frame: CGRect) { super.init(frame: frame) prepareUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /** 准备UI */ fileprivate func prepareUI() { backgroundColor = UIColor.white addSubview(avatarImageView) addSubview(usernameLabel) addSubview(levelLabel) addSubview(pointsLabel) avatarImageView.snp.makeConstraints { (make) in make.left.equalTo(MARGIN) make.centerY.equalTo(self) make.size.equalTo(CGSize(width: 50, height: 50)) } usernameLabel.snp.makeConstraints { (make) in make.left.equalTo(avatarImageView.snp.right).offset(20) make.top.equalTo(avatarImageView).offset(2) } levelLabel.snp.makeConstraints { (make) in make.left.equalTo(usernameLabel) make.bottom.equalTo(avatarImageView).offset(-2) } pointsLabel.snp.makeConstraints { (make) in make.top.equalTo(avatarImageView) make.right.equalTo(-MARGIN) } avatarImageView.yy_setImage(with: URL(string: JFAccountModel.shareAccount()!.avatarUrl!), options: YYWebImageOptions.allowBackgroundTask) usernameLabel.text = JFAccountModel.shareAccount()!.username! levelLabel.text = "等级:\(JFAccountModel.shareAccount()!.groupName!)" pointsLabel.text = "\(JFAccountModel.shareAccount()!.points!)积分" } // MARK: - 懒加载 fileprivate lazy var avatarImageView: UIImageView = { let avatarImageView = UIImageView() avatarImageView.layer.cornerRadius = 25 avatarImageView.layer.masksToBounds = true return avatarImageView }() fileprivate lazy var usernameLabel: UILabel = { let usernameLabel = UILabel() return usernameLabel }() fileprivate lazy var levelLabel: UILabel = { let levelLabel = UILabel() levelLabel.font = UIFont.systemFont(ofSize: 13) levelLabel.textColor = UIColor.gray return levelLabel }() fileprivate lazy var pointsLabel: UILabel = { let pointsLabel = UILabel() pointsLabel.font = UIFont.systemFont(ofSize: 13) pointsLabel.textColor = UIColor.gray return pointsLabel }() }
72eead3b158f94bd81ac38a8d6df9b5a
28.876404
145
0.621286
false
false
false
false
WhosPablo/PicShare
refs/heads/master
PicShare/SignUpViewController.swift
apache-2.0
1
// // ViewController.swift // PicShare // // Created by Pablo Arango on 10/14/15. // Copyright © 2015 Pablo Arango. All rights reserved. // import Parse import UIKit class SignUpViewController: UIViewController { @IBOutlet weak var signUpUsername: UITextField! @IBOutlet weak var signUpEmail: UITextField! @IBOutlet weak var signUpPassword: UITextField! @IBOutlet weak var signUpPasswordVerification: UITextField! @IBOutlet weak var signUpAlert: UILabel! var actInd: UIActivityIndicatorView = UIActivityIndicatorView( frame: CGRectMake(0, 0, 150, 150)) as UIActivityIndicatorView override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.actInd.center = self.view.center self.actInd.hidesWhenStopped = true self.actInd.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge view.addSubview(self.actInd) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func signUpAction(sender: AnyObject) { self.actInd.startAnimating() let username = self.signUpUsername.text let password = self.signUpPassword.text let passwordVerification = self.signUpPasswordVerification.text let email = self.signUpEmail.text if(username?.utf16.count<1){ self.signUpAlert.text = "Username field is empty" self.signUpAlert.hidden = false self.actInd.stopAnimating() return } if(email?.utf16.count<5){ self.signUpAlert.text = "Email field is empty or invalid" self.signUpAlert.hidden = false self.actInd.stopAnimating() return } if(password?.utf16.count<6){ self.signUpAlert.text = "Password field is empty or too short" self.signUpAlert.hidden = false self.actInd.stopAnimating() return } else if (password != passwordVerification){ self.signUpAlert.text = "Passwords do not match" self.signUpAlert.hidden = false self.actInd.stopAnimating() return } if (username?.utf16.count>=1 && password?.utf16.count>=1 && email?.utf16.count>=1 && password == passwordVerification){ self.actInd.startAnimating() let newUser = PFUser() newUser.username = username; newUser.password = password; newUser.email = email; newUser.signUpInBackgroundWithBlock({(success: Bool, error: NSError?) -> Void in self.actInd.stopAnimating() if(error == nil){ self.signUpAlert.hidden = true self.performSegueWithIdentifier("signUpDone", sender: self); } else { var errorString = error!.localizedDescription errorString.replaceRange(errorString.startIndex...errorString.startIndex, with: String(errorString[errorString.startIndex]).uppercaseString) self.signUpAlert.text = errorString self.signUpAlert.hidden = false } }) } } @IBAction func cancelAction(sender: AnyObject) { self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil) } }
b484dd777d5471c06df696e8376a6872
31.760684
160
0.576311
false
false
false
false
bykoianko/omim
refs/heads/master
iphone/Maps/Bookmarks/Categories/Sharing/BookmarksSharingViewController.swift
apache-2.0
1
import SafariServices @objc protocol BookmarksSharingViewControllerDelegate: AnyObject { func didShareCategory() } final class BookmarksSharingViewController: MWMTableViewController { typealias ViewModel = MWMAuthorizationViewModel @objc var categoryId = MWMFrameworkHelper.invalidCategoryId() var categoryUrl: URL? @objc weak var delegate: BookmarksSharingViewControllerDelegate? private var sharingTags: [MWMTag]? private var sharingUserStatus: MWMCategoryAuthorType? private var manager: MWMBookmarksManager { return MWMBookmarksManager.shared() } private var categoryAccessStatus: MWMCategoryAccessStatus? { guard categoryId != MWMFrameworkHelper.invalidCategoryId() else { assert(false) return nil } return manager.getCategoryAccessStatus(categoryId) } private let kPropertiesSegueIdentifier = "chooseProperties" private let kTagsControllerIdentifier = "tags" private let kEditOnWebSegueIdentifier = "editOnWeb" private let publicSectionIndex = 0 private let privateSectionIndex = 1 private let editOnWebCellIndex = 3 private let rowsInPrivateSection = 2 private var rowsInPublicSection: Int { return categoryAccessStatus == .public ? 4 : 3 } @IBOutlet private weak var uploadAndPublishCell: UploadActionCell! @IBOutlet private weak var getDirectLinkCell: UploadActionCell! @IBOutlet private weak var editOnWebCell: UITableViewCell! @IBOutlet private weak var licenseAgreementTextView: UITextView! { didSet { let htmlString = String(coreFormat: L("ugc_routes_user_agreement"), arguments: [ViewModel.termsOfUseLink()]) let attributes: [NSAttributedStringKey : Any] = [NSAttributedStringKey.font: UIFont.regular14(), NSAttributedStringKey.foregroundColor: UIColor.blackSecondaryText()] licenseAgreementTextView.attributedText = NSAttributedString.string(withHtml: htmlString, defaultAttributes: attributes) licenseAgreementTextView.delegate = self } } override func viewDidLoad() { super.viewDidLoad() title = L("sharing_options") configureActionCells() assert(categoryId != MWMFrameworkHelper.invalidCategoryId(), "We can't share nothing") guard let categoryAccessStatus = categoryAccessStatus else { return } switch categoryAccessStatus { case .local: break case .public: categoryUrl = manager.sharingUrl(forCategoryId: categoryId) uploadAndPublishCell.cellState = .completed case .private: categoryUrl = manager.sharingUrl(forCategoryId: categoryId) getDirectLinkCell.cellState = .completed case .other: break } } func configureActionCells() { uploadAndPublishCell.config(titles: [ .normal : L("upload_and_publish"), .inProgress : L("upload_and_publish_progress_text"), .completed : L("upload_and_publish_success") ], image: UIImage(named: "ic24PxGlobe"), delegate: self) getDirectLinkCell.config(titles: [ .normal : L("upload_and_get_direct_link"), .inProgress : L("direct_link_progress_text"), .completed : L("direct_link_success") ], image: UIImage(named: "ic24PxLink"), delegate: self) } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } override func numberOfSections(in _: UITableView) -> Int { return categoryAccessStatus == .public ? 1 : 2 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case publicSectionIndex: return rowsInPublicSection case privateSectionIndex: return rowsInPrivateSection default: return 0 } } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return section == 0 ? L("public_access") : L("limited_access") } override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { let cell = tableView.cellForRow(at: indexPath) if cell == getDirectLinkCell && getDirectLinkCell.cellState != .normal || cell == uploadAndPublishCell && uploadAndPublishCell.cellState != .normal { return nil } return indexPath } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let cell = tableView.cellForRow(at: indexPath) if cell == uploadAndPublishCell { startUploadAndPublishFlow() } else if cell == getDirectLinkCell { uploadAndGetDirectLink() } } func startUploadAndPublishFlow() { Statistics.logEvent(kStatSharingOptionsClick, withParameters: [kStatItem : kStatPublic]) performAfterValidation(anchor: uploadAndPublishCell) { [weak self] in if let self = self { self.performSegue(withIdentifier: self.kPropertiesSegueIdentifier, sender: self) } } } func uploadAndPublish() { guard categoryId != MWMFrameworkHelper.invalidCategoryId(), let tags = sharingTags, let userStatus = sharingUserStatus else { assert(false, "not enough data for public sharing") return } manager.setCategory(categoryId, authorType: userStatus) manager.setCategory(categoryId, tags: tags) manager.uploadAndPublishCategory(withId: categoryId, progress: { (progress) in self.uploadAndPublishCell.cellState = .inProgress }) { (url, error) in if let error = error as NSError? { self.uploadAndPublishCell.cellState = .normal self.showErrorAlert(error) } else { self.uploadAndPublishCell.cellState = .completed self.categoryUrl = url Statistics.logEvent(kStatSharingOptionsUploadSuccess, withParameters: [kStatTracks : self.manager.getCategoryTracksCount(self.categoryId), kStatPoints : self.manager.getCategoryMarksCount(self.categoryId)]) self.tableView.beginUpdates() self.tableView.deleteSections(IndexSet(arrayLiteral: self.privateSectionIndex), with: .fade) self.tableView.insertRows(at: [IndexPath(item: self.editOnWebCellIndex, section: self.publicSectionIndex)], with: .automatic) self.tableView.endUpdates() } } } func uploadAndGetDirectLink() { Statistics.logEvent(kStatSharingOptionsClick, withParameters: [kStatItem : kStatPrivate]) performAfterValidation(anchor: getDirectLinkCell) { [weak self] in guard let s = self, s.categoryId != MWMFrameworkHelper.invalidCategoryId() else { assert(false, "categoryId must be valid") return } s.manager.uploadAndGetDirectLinkCategory(withId: s.categoryId, progress: { (progress) in if progress == .uploadStarted { s.getDirectLinkCell.cellState = .inProgress } }, completion: { (url, error) in if let error = error as NSError? { s.getDirectLinkCell.cellState = .normal s.showErrorAlert(error) } else { s.getDirectLinkCell.cellState = .completed s.categoryUrl = url s.delegate?.didShareCategory() Statistics.logEvent(kStatSharingOptionsUploadSuccess, withParameters: [kStatTracks : s.manager.getCategoryTracksCount(s.categoryId), kStatPoints : s.manager.getCategoryMarksCount(s.categoryId)]) } }) } } func performAfterValidation(anchor: UIView, action: @escaping MWMVoidBlock) { if MWMFrameworkHelper.isNetworkConnected() { signup(anchor: anchor, onComplete: { success in if success { action() } else { Statistics.logEvent(kStatSharingOptionsError, withParameters: [kStatError : 1]) } }) } else { Statistics.logEvent(kStatSharingOptionsError, withParameters: [kStatError : 0]) MWMAlertViewController.activeAlert().presentDefaultAlert(withTitle: L("common_check_internet_connection_dialog_title"), message: L("common_check_internet_connection_dialog"), rightButtonTitle: L("downloader_retry"), leftButtonTitle: L("cancel")) { self.performAfterValidation(anchor: anchor, action: action) } } } func showErrorAlert(_ error: NSError) { guard error.code == kCategoryUploadFailedCode, let statusCode = error.userInfo[kCategoryUploadStatusKey] as? Int, let status = MWMCategoryUploadStatus(rawValue: statusCode) else { assert(false) return } switch (status) { case .networkError: Statistics.logEvent(kStatSharingOptionsUploadError, withParameters: [kStatError : 1]) self.showUploadError() case .serverError: Statistics.logEvent(kStatSharingOptionsUploadError, withParameters: [kStatError : 2]) self.showUploadError() case .authError: Statistics.logEvent(kStatSharingOptionsUploadError, withParameters: [kStatError : 3]) self.showUploadError() case .malformedData: Statistics.logEvent(kStatSharingOptionsUploadError, withParameters: [kStatError : 4]) self.showMalformedDataError() case .accessError: Statistics.logEvent(kStatSharingOptionsUploadError, withParameters: [kStatError : 5]) self.showAccessError() case .invalidCall: Statistics.logEvent(kStatSharingOptionsUploadError, withParameters: [kStatError : 6]) assert(false, "sharing is not available for paid bookmarks") } } private func showUploadError() { MWMAlertViewController.activeAlert().presentInfoAlert(L("unable_upload_errorr_title"), text: L("upload_error_toast")) } private func showMalformedDataError() { MWMAlertViewController.activeAlert().presentInfoAlert(L("unable_upload_errorr_title"), text: L("unable_upload_error_subtitle_broken")) } private func showAccessError() { MWMAlertViewController.activeAlert().presentInfoAlert(L("unable_upload_errorr_title"), text: L("unable_upload_error_subtitle_edited")) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == kPropertiesSegueIdentifier { if let vc = segue.destination as? SharingPropertiesViewController { vc.delegate = self } } else if segue.identifier == kEditOnWebSegueIdentifier { Statistics.logEvent(kStatSharingOptionsClick, withParameters: [kStatItem : kStatEditOnWeb]) if let vc = segue.destination as? EditOnWebViewController { vc.delegate = self vc.guideUrl = categoryUrl } } } } extension BookmarksSharingViewController: UITextViewDelegate { func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool { let safari = SFSafariViewController(url: URL) present(safari, animated: true, completion: nil) return false } } extension BookmarksSharingViewController: UploadActionCellDelegate { func cellDidPressShareButton(_ cell: UploadActionCell, senderView: UIView) { guard let url = categoryUrl else { assert(false, "must provide guide url") return } Statistics.logEvent(kStatSharingOptionsClick, withParameters: [kStatItem : kStatCopyLink]) let message = String(coreFormat: L("share_bookmarks_email_body_link"), arguments: [url.absoluteString]) let shareController = MWMActivityViewController.share(for: nil, message: message) { _, success, _, _ in if success { Statistics.logEvent(kStatSharingLinkSuccess, withParameters: [kStatFrom : kStatSharingOptions]) } } shareController?.present(inParentViewController: self, anchorView: senderView) } } extension BookmarksSharingViewController: SharingTagsViewControllerDelegate { func sharingTagsViewController(_ viewController: SharingTagsViewController, didSelect tags: [MWMTag]) { navigationController?.popViewController(animated: true) sharingTags = tags uploadAndPublish() } func sharingTagsViewControllerDidCancel(_ viewController: SharingTagsViewController) { navigationController?.popViewController(animated: true) } } extension BookmarksSharingViewController: SharingPropertiesViewControllerDelegate { func sharingPropertiesViewController(_ viewController: SharingPropertiesViewController, didSelect userStatus: MWMCategoryAuthorType) { sharingUserStatus = userStatus let storyboard = UIStoryboard.instance(.sharing) let tagsController = storyboard.instantiateViewController(withIdentifier: kTagsControllerIdentifier) as! SharingTagsViewController tagsController.delegate = self guard var viewControllers = navigationController?.viewControllers else { assert(false) return } viewControllers.removeLast() viewControllers.append(tagsController) navigationController?.setViewControllers(viewControllers, animated: true) } } extension BookmarksSharingViewController: EditOnWebViewControllerDelegate { func editOnWebViewControllerDidFinish(_ viewController: EditOnWebViewController) { dismiss(animated: true) } }
2f2eee871b62cd2f0836b7c461a79c5e
38.661064
125
0.666714
false
false
false
false
macteo/bezier
refs/heads/master
Bezier.playground/Sources/GenesisController.swift
mit
2
import UIKit public class GenesisController : UIViewController { let canvasSize : CGFloat = 300 var startPoint : CGPoint! var endPoint : CGPoint! var controlPoint1 : CGPoint! var controlPoint2 : CGPoint! let canvas = CALayer() let joinBezier = CAShapeLayer() let leftHandle = CAShapeLayer() let rightHandle = CAShapeLayer() let lefArm = CAShapeLayer() let rightArm = CAShapeLayer() let armsConnection = CAShapeLayer() let handleSize : CGFloat = 8 let animationDuration : TimeInterval = 3 let padding : CGFloat = 100 let leftArmBall = UIView() let rightArmBall = UIView() let armsConnectionBall = UIView() var startAnimationButton : UIButton! var resetAnimationButton : UIButton! let firstBridge = CAShapeLayer() let secondBridge = CAShapeLayer() let thirdBridge = CAShapeLayer() let firstBridgeBall = UIView() let secondBridgeBall = UIView() let thirdBridgeBall = UIView() public override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white startPoint = CGPoint(x: 0, y: canvasSize) endPoint = CGPoint(x: canvasSize, y: canvasSize / 2) controlPoint1 = CGPoint(x: 0, y: canvasSize / 2) controlPoint2 = CGPoint(x: canvasSize / 2, y: canvasSize / 3) canvas.addSublayer(armsConnection) canvas.addSublayer(lefArm) canvas.addSublayer(rightArm) canvas.addSublayer(joinBezier) canvas.addSublayer(leftHandle) canvas.addSublayer(rightHandle) canvas.frame = CGRect(x: padding, y: padding, width: canvasSize, height: canvasSize) canvas.borderColor = UIColor.white.cgColor canvas.borderWidth = 0.0 view.layer.addSublayer(canvas) let pointSize : CGFloat = 8 let originPoint = CAShapeLayer() originPoint.path = UIBezierPath(ovalIn: CGRect(x: startPoint.x, y: startPoint.y, width: pointSize, height: pointSize)).cgPath originPoint.frame = CGRect(x: -pointSize / 2, y: -pointSize / 2, width: pointSize, height: pointSize) originPoint.fillColor = UIColor.blue.cgColor canvas.addSublayer(originPoint) let finalPoint = CAShapeLayer() finalPoint.path = UIBezierPath(ovalIn: CGRect(x: endPoint.x, y: endPoint.y, width: pointSize, height: pointSize)).cgPath finalPoint.frame = CGRect(x: -pointSize / 2, y: -pointSize / 2, width: pointSize, height: pointSize) finalPoint.fillColor = UIColor.blue.cgColor canvas.addSublayer(finalPoint) let leftHandleView = UIView(frame: CGRect(x: controlPoint1.x + padding - 20, y: controlPoint1.y + padding - 20, width: 40, height: 40)) leftHandleView.backgroundColor = .clear leftHandleView.tag = 1 view.addSubview(leftHandleView) let leftHandlePan = UIPanGestureRecognizer(target: self, action: #selector(pan(gesture:))) leftHandleView.addGestureRecognizer(leftHandlePan) let rightHandleView = UIView(frame: CGRect(x: controlPoint2.x + padding - 20, y: controlPoint2.y + padding - 20, width: 40, height: 40)) rightHandleView.backgroundColor = .clear rightHandleView.tag = 2 view.addSubview(rightHandleView) let rightHandlePan = UIPanGestureRecognizer(target: self, action: #selector(pan(gesture:))) rightHandleView.addGestureRecognizer(rightHandlePan) startAnimationButton = UIButton(frame: CGRect(x: padding, y: canvasSize + padding, width: 60, height: 44)) startAnimationButton.setTitleColor(.black, for: .normal) startAnimationButton.setTitle("Play", for: .normal) startAnimationButton.addTarget(self, action: #selector(animate), for: .touchUpInside) view.addSubview(startAnimationButton) resetAnimationButton = UIButton(frame: CGRect(x: padding * 2 + 60, y: canvasSize + padding, width: 60, height: 44)) resetAnimationButton.setTitleColor(.black, for: .normal) resetAnimationButton.setTitle("Reset", for: .normal) resetAnimationButton.addTarget(self, action: #selector(resetAnimation), for: .touchUpInside) view.addSubview(resetAnimationButton) canvas.addSublayer(firstBridge) canvas.addSublayer(secondBridge) canvas.addSublayer(thirdBridge) drawLayers() } func drawLayers() { let bezier = UIBezierPath() bezier.move(to: CGPoint(x: startPoint.x, y: startPoint.y)) bezier.addCurve(to: CGPoint(x: endPoint.x, y:endPoint.y), controlPoint1: controlPoint1, controlPoint2: controlPoint2) joinBezier.frame = canvas.bounds joinBezier.path = bezier.cgPath joinBezier.lineWidth = 2 joinBezier.fillColor = UIColor.lightGray.withAlphaComponent(0.1).cgColor joinBezier.strokeColor = UIColor.clear.cgColor leftHandle.path = UIBezierPath(ovalIn: CGRect(x: controlPoint1.x, y: controlPoint1.y, width: handleSize, height: handleSize)).cgPath leftHandle.frame = CGRect(x: -handleSize / 2, y: -handleSize / 2, width: handleSize, height: handleSize) leftHandle.lineWidth = 2 leftHandle.fillColor = UIColor.white.cgColor leftHandle.strokeColor = UIColor.blue.cgColor rightHandle.path = UIBezierPath(ovalIn: CGRect(x: controlPoint2.x, y: controlPoint2.y, width: handleSize, height: handleSize)).cgPath rightHandle.frame = CGRect(x: -handleSize / 2, y: -handleSize / 2, width: handleSize, height: handleSize) rightHandle.lineWidth = 2 rightHandle.fillColor = UIColor.white.cgColor rightHandle.strokeColor = UIColor.blue.cgColor let leftArmPath = UIBezierPath() leftArmPath.move(to: CGPoint(x: startPoint.x, y: startPoint.y)) leftArmPath.addLine(to: controlPoint1) lefArm.frame = canvas.bounds lefArm.path = leftArmPath.cgPath lefArm.lineWidth = 2 lefArm.fillColor = UIColor.clear.cgColor lefArm.strokeColor = UIColor.blue.cgColor let rightArmPath = UIBezierPath() rightArmPath.move(to: CGPoint(x: endPoint.x, y: endPoint.y)) rightArmPath.addLine(to: controlPoint2) rightArm.frame = canvas.bounds rightArm.path = rightArmPath.cgPath rightArm.lineWidth = 2 rightArm.fillColor = UIColor.clear.cgColor rightArm.strokeColor = UIColor.blue.cgColor let armsConnectionPath = UIBezierPath() armsConnectionPath.move(to: CGPoint(x: controlPoint1.x, y: controlPoint1.y)) armsConnectionPath.addLine(to: controlPoint2) armsConnection.lineDashPattern = [3, 3, 3, 3] armsConnection.frame = canvas.bounds armsConnection.path = armsConnectionPath.cgPath armsConnection.lineWidth = 1 armsConnection.fillColor = UIColor.clear.cgColor armsConnection.strokeColor = UIColor.darkGray.cgColor let armBallSize : CGFloat = 6 let armBallColor = UIColor.green leftArmBall.frame = CGRect(x: padding + startPoint.x - armBallSize / 2, y: padding + startPoint.y - armBallSize / 2, width: armBallSize, height: armBallSize) leftArmBall.layer.cornerRadius = armBallSize / 2 leftArmBall.backgroundColor = armBallColor view.addSubview(leftArmBall) armsConnectionBall.frame = CGRect(x: padding + controlPoint1.x - armBallSize / 2, y: padding + controlPoint1.y - armBallSize / 2, width: armBallSize, height: armBallSize) armsConnectionBall.layer.cornerRadius = armBallSize / 2 armsConnectionBall.backgroundColor = armBallColor view.addSubview(armsConnectionBall) rightArmBall.frame = CGRect(x: padding + controlPoint2.x - armBallSize / 2, y: padding + controlPoint2.y - armBallSize / 2, width: armBallSize, height: armBallSize) rightArmBall.layer.cornerRadius = armBallSize / 2 rightArmBall.backgroundColor = armBallColor view.addSubview(rightArmBall) firstBridgeBall.frame = CGRect(x: padding + startPoint.x - armBallSize / 2, y: padding + startPoint.y - armBallSize / 2, width: armBallSize, height: armBallSize) firstBridgeBall.layer.cornerRadius = armBallSize / 2 firstBridgeBall.backgroundColor = .clear view.addSubview(firstBridgeBall) secondBridgeBall.frame = CGRect(x: padding + controlPoint1.x - armBallSize / 2, y: padding + controlPoint1.y - armBallSize / 2, width: armBallSize, height: armBallSize) secondBridgeBall.layer.cornerRadius = armBallSize / 2 secondBridgeBall.backgroundColor = .clear view.addSubview(secondBridgeBall) thirdBridgeBall.frame = CGRect(x: padding + startPoint.x - armBallSize / 2, y: padding + startPoint.y - armBallSize / 2, width: armBallSize, height: armBallSize) thirdBridgeBall.layer.cornerRadius = armBallSize / 2 thirdBridgeBall.backgroundColor = .clear view.addSubview(thirdBridgeBall) let firstBridgePath = UIBezierPath() firstBridgePath.move(to: startPoint) firstBridgePath.addLine(to: controlPoint1) firstBridge.frame = canvas.bounds firstBridge.path = firstBridgePath.cgPath firstBridge.lineWidth = 2 firstBridge.fillColor = UIColor.clear.cgColor firstBridge.strokeColor = UIColor.clear.cgColor let secondBridgePath = UIBezierPath() secondBridgePath.move(to: controlPoint1) secondBridgePath.addLine(to: controlPoint2) secondBridge.frame = canvas.bounds secondBridge.path = secondBridgePath.cgPath secondBridge.lineWidth = 2 secondBridge.fillColor = UIColor.clear.cgColor secondBridge.strokeColor = UIColor.clear.cgColor let thirdBridgePath = UIBezierPath() thirdBridgePath.move(to: controlPoint1) thirdBridgePath.addLine(to: controlPoint2) thirdBridge.frame = canvas.bounds thirdBridge.path = thirdBridgePath.cgPath thirdBridge.lineWidth = 2 thirdBridge.fillColor = UIColor.clear.cgColor thirdBridge.strokeColor = UIColor.clear.cgColor } func resetAnimation() { let firstBridgePath = UIBezierPath() firstBridgePath.move(to: startPoint) firstBridgePath.addLine(to: controlPoint1) firstBridge.path = firstBridgePath.cgPath firstBridge.strokeColor = UIColor.clear.cgColor let secondBridgePath = UIBezierPath() secondBridgePath.move(to: controlPoint1) secondBridgePath.addLine(to: controlPoint2) secondBridge.path = secondBridgePath.cgPath secondBridge.strokeColor = UIColor.clear.cgColor leftArmBall.center = padded(startPoint) armsConnectionBall.center = padded(controlPoint1) rightArmBall.center = padded(controlPoint2) firstBridgeBall.center = leftArmBall.center secondBridgeBall.center = armsConnectionBall.center thirdBridgeBall.center = leftArmBall.center joinBezier.strokeColor = UIColor.clear.cgColor } func animate() { resetAnimation() resetAnimationButton.isEnabled = false startAnimationButton.isEnabled = false joinBezier.strokeColor = UIColor.red.cgColor joinBezier.strokeStart = 0.0 joinBezier.strokeEnd = 0.0 firstBridge.strokeColor = UIColor.green.cgColor secondBridge.strokeColor = UIColor.green.cgColor thirdBridge.strokeColor = UIColor.green.cgColor firstBridgeBall.backgroundColor = .red secondBridgeBall.backgroundColor = .red thirdBridgeBall.backgroundColor = .red let animatorLinear = UIViewPropertyAnimator(duration: self.animationDuration, curve: .linear, animations: { self.leftArmBall.center = self.padded(self.controlPoint1) self.armsConnectionBall.center = self.padded(self.controlPoint2) self.rightArmBall.center = self.padded(self.endPoint) }) let firstBridgePath = UIBezierPath() firstBridgePath.move(to: controlPoint1) firstBridgePath.addLine(to: controlPoint2) let secondBridgePath = UIBezierPath() secondBridgePath.move(to: controlPoint2) secondBridgePath.addLine(to: endPoint) let thirdBridgePath = UIBezierPath() thirdBridgePath.move(to: padded(startPoint)) thirdBridgePath.addQuadCurve(to: padded(controlPoint2), controlPoint: padded(self.controlPoint1)) let fourthBridgePath = UIBezierPath() fourthBridgePath.move(to: padded(controlPoint1)) fourthBridgePath.addQuadCurve(to: padded(endPoint), controlPoint: padded(controlPoint2)) let displayLink = CADisplayLink(target: self, selector: #selector(update(displayLink:))) displayLink.preferredFramesPerSecond = 60 displayLink.add(to: RunLoop.main, forMode: .defaultRunLoopMode) animatorLinear.addCompletion { _ in self.resetAnimationButton.isEnabled = true self.startAnimationButton.isEnabled = true self.firstBridge.path = firstBridgePath.cgPath self.secondBridge.path = secondBridgePath.cgPath self.firstBridge.removeAllAnimations() self.secondBridge.removeAllAnimations() displayLink.remove(from: RunLoop.main, forMode: .defaultRunLoopMode) } animatorLinear.startAnimation() let firstAnimation = CABasicAnimation(keyPath: "path") firstAnimation.toValue = firstBridgePath.cgPath firstAnimation.duration = animationDuration firstAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) firstAnimation.fillMode = kCAFillModeBoth firstAnimation.isRemovedOnCompletion = false firstBridge.add(firstAnimation, forKey:firstAnimation.keyPath) let secondAnimation = CABasicAnimation(keyPath: "path") secondAnimation.toValue = secondBridgePath.cgPath secondAnimation.duration = animationDuration secondAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) secondAnimation.fillMode = kCAFillModeBoth secondAnimation.isRemovedOnCompletion = false secondBridge.add(secondAnimation, forKey:secondAnimation.keyPath) let thirdAnimation = CAKeyframeAnimation(keyPath: "position") thirdAnimation.path = thirdBridgePath.cgPath thirdAnimation.duration = animationDuration thirdAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) thirdAnimation.fillMode = kCAFillModeBoth thirdAnimation.isRemovedOnCompletion = false firstBridgeBall.layer.add(thirdAnimation, forKey:thirdAnimation.keyPath) let fourthAnimation = CAKeyframeAnimation(keyPath: "position") fourthAnimation.path = fourthBridgePath.cgPath fourthAnimation.duration = animationDuration fourthAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) fourthAnimation.fillMode = kCAFillModeBoth fourthAnimation.isRemovedOnCompletion = false secondBridgeBall.layer.add(fourthAnimation, forKey:fourthAnimation.keyPath) let fifthBridgePath = UIBezierPath() fifthBridgePath.move(to: padded(startPoint)) fifthBridgePath.addCurve(to: padded(endPoint), controlPoint1: padded(controlPoint1), controlPoint2: padded(controlPoint2)) let fifthAnimation = CAKeyframeAnimation(keyPath: "position") fifthAnimation.path = fifthBridgePath.cgPath fifthAnimation.duration = animationDuration fifthAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) fifthAnimation.fillMode = kCAFillModeBoth fifthAnimation.isRemovedOnCompletion = false thirdBridgeBall.layer.add(fifthAnimation, forKey:fifthAnimation.keyPath) let strokeAnimation = CABasicAnimation(keyPath: "strokeEnd") strokeAnimation.fromValue = 0.0 strokeAnimation.toValue = 1.0 strokeAnimation.duration = animationDuration strokeAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) strokeAnimation.fillMode = kCAFillModeBoth strokeAnimation.isRemovedOnCompletion = false joinBezier.add(strokeAnimation, forKey:strokeAnimation.keyPath) } func padded(_ point: CGPoint) -> CGPoint { return CGPoint(x: point.x + padding, y: point.y + padding) } func unpadded(_ point: CGPoint) -> CGPoint { return CGPoint(x: point.x - padding, y: point.y - padding) } @objc func update(displayLink: CADisplayLink) { let first = unpadded(firstBridgeBall.layer.presentation()!.position) let second = unpadded(secondBridgeBall.layer.presentation()!.position) let thirdBridgePath = UIBezierPath() thirdBridgePath.move(to: first) thirdBridgePath.addLine(to: second) thirdBridge.path = thirdBridgePath.cgPath } func pan(gesture: UIPanGestureRecognizer) { switch (gesture.state) { case .changed: let translation = gesture.translation(in: gesture.view) var x = gesture.view!.center.x + translation.x var y = gesture.view!.center.y + translation.y if x < 0 { x = 0 } if x > canvasSize + 2 * padding { x = canvasSize + 2 * padding } if y < 0 { y = 0 } if y > view.bounds.size.height { y = view.bounds.size.height } gesture.view!.center = CGPoint(x: x, y: y) gesture.setTranslation(CGPoint(x:0, y:0), in: gesture.view) var point = controlPoint1! if gesture.view?.tag == 2 { point = controlPoint2! } x = point.x + translation.x y = point.y + translation.y if x < -padding { x = -padding } if x > canvasSize + padding { x = canvasSize + padding } if y < -padding { y = -padding } if y > view.bounds.size.height - padding { y = view.bounds.size.height - padding } point = CGPoint(x: x, y: y) if gesture.view?.tag == 1 { controlPoint1 = point } else { controlPoint2 = point } drawLayers() default: break } } }
53dafadc59238a449f2dd948f5b9d2a1
45.146341
178
0.668182
false
false
false
false
MukeshKumarS/Swift
refs/heads/master
test/SILOptimizer/unreachable_code.swift
apache-2.0
1
// RUN: %target-swift-frontend -emit-sil %s -o /dev/null -verify func ifFalse() -> Int { if false { // expected-note {{always evaluates to false}} return 0 // expected-warning {{will never be executed}} } else { return 1 } } func ifTrue() -> Int { _ = 0 if true { // expected-note {{always evaluates to true}} return 1 } return 0 // expected-warning {{will never be executed}} } // Work-around <rdar://problem/17687851> by ensuring there is // something that appears to be user code in unreachable blocks. func userCode() {} func whileTrue() { var x = 0 while true { // expected-note {{always evaluates to true}} x += 1 } userCode() // expected-warning {{will never be executed}} } func whileTrueSilent() { while true { } } // no warning! func whileTrueReachable(v: Int) -> () { var x = 0 while true { if v == 0 { break } x += 1 } x-- } func whileTrueTwoPredecessorsEliminated() -> () { var x = 0 while (true) { // expected-note {{always evaluates to true}} if false { break } x += 1 } userCode() // expected-warning {{will never be executed}} } func unreachableBranch() -> Int { if false { // expected-note {{always evaluates to false}} // FIXME: It'd be nice if the warning were on 'if true' instead of the // body. if true { return 0 // expected-warning {{will never be executed}} } } else { return 1 } } // We should not report unreachable user code inside inlined transparent function. @_transparent func ifTrueTransparent(b: Bool) -> Int { _ = 0 if b { return 1 } return 0 } func testIfTrueTransparent() { ifTrueTransparent(true) // no-warning ifTrueTransparent(false) // no-warning } // We should not report unreachable user code inside generic instantiations. // TODO: This test should start failing after we add support for generic // specialization in SIL. To fix it, add generic instantiation detection // within the DeadCodeElimination pass to address the corresponding FIXME note. protocol HavingGetCond { func getCond() -> Bool } struct ReturnsTrue : HavingGetCond { func getCond() -> Bool { return true } } struct ReturnsOpaque : HavingGetCond { var b: Bool func getCond() -> Bool { return b } } func ifTrueGeneric<T : HavingGetCond>(x: T) -> Int { if x.getCond() { return 1 } return 0 } func testIfTrueGeneric(b1: ReturnsOpaque, b2: ReturnsTrue) { ifTrueGeneric(b1) // no-warning ifTrueGeneric(b2) // no-warning } // Test switch_enum folding/diagnostic. enum X { case One case Two case Three } func testSwitchEnum(xi: Int) -> Int { var x = xi let cond: X = .Two switch cond { // expected-warning {{switch condition evaluates to a constant}} case .One: userCode() // expected-note {{will never be executed}} case .Two: x-- case .Three: x-- } switch cond { // no warning default: x += 1 } switch cond { // no warning case .Two: x += 1 } switch cond { case .One: x += 1 } // expected-error{{switch must be exhaustive}} switch cond { case .One: x += 1 case .Three: x += 1 } // expected-error{{switch must be exhaustive}} switch cond { // expected-warning{{switch condition evaluates to a constant}} case .Two: x += 1 default: userCode() // expected-note{{will never be executed}} } switch cond { // expected-warning{{switch condition evaluates to a constant}} case .One: userCode() // expected-note{{will never be executed}} default: x -= 1 } return x; } // Treat nil as .None and do not emit false // non-exhaustive warning. func testSwitchEnumOptionalNil(x: Int?) -> Int { switch x { // no warning case .Some(_): return 1 case nil: return -1 } } // Do not emit false non-exhaustive warnings if both // true and false are covered by the switch. func testSwitchEnumBool(b: Bool, xi: Int) -> Int { var x = xi let Cond = b switch Cond { // no warning default: x += 1 } switch Cond { case true: x += 1 } // expected-error{{switch must be exhaustive}} switch Cond { case false: x += 1 } // expected-error{{switch must be exhaustive}} switch Cond { // no warning case true: x += 1 case false: x -= 1 } return x } func testSwitchOptionalBool (b:Bool?, xi: Int) -> Int { var x = xi switch b { // No warning case .Some(true): x += 1 case .Some(false): x += 1 case .None: x -= 1 } switch b { case .Some(true): x += 1 case .None: x-- } // expected-error{{switch must be exhaustive}} return xi } // Do not emit false non-exhaustive warnings if both // true and false are covered for a boolean element of a tuple. func testSwitchEnumBoolTuple(b1: Bool, b2: Bool, xi: Int) -> Int { var x = xi let Cond = (b1, b2) switch Cond { // no warning default: x += 1 } switch Cond { case (true, true): x += 1 // FIXME: Two expect statements are written, because unreachable diagnostics produces N errors // for non-exhaustive switches on tuples of N elements } // expected-error{{switch must be exhaustive}} expected-error{{switch must be exhaustive}} switch Cond { case (false, true): x += 1 // FIXME: Two expect statements are written, because unreachable diagnostics produces N errors // for non-exhaustive switches on tuples of N elements } // expected-error{{switch must be exhaustive}} expected-error{{switch must be exhaustive}} switch Cond { // no warning case (true, true): x += 1 case (true, false): x += 1 case (false, true): x -= 1 case (false, false): x -= 1 } return x } @noreturn @_silgen_name("exit") func exit() -> () func reachableThroughNonFoldedPredecessor(@autoclosure fn: () -> Bool = false) { if !_fastPath(fn()) { exit() } var _: Int = 0 // no warning } func intConstantTest() -> Int{ let y: Int = 1 if y == 1 { // expected-note {{condition always evaluates to true}} return y } return 1 // expected-warning {{will never be executed}} } func intConstantTest2() -> Int{ let y:Int = 1 let x:Int = y if x != 1 { // expected-note {{condition always evaluates to false}} return y // expected-warning {{will never be executed}} } return 3 } func test_single_statement_closure(fn:() -> ()) {} test_single_statement_closure() { exit() // no-warning } class C { } class Super { var s = C() deinit { // no-warning } } class D : Super { var c = C() deinit { // no-warning exit() } } // <rdar://problem/20097963> incorrect DI diagnostic in unreachable code enum r20097963Test { case A case B } class r20097963MyClass { func testStr(t: r20097963Test) -> String { let str: String switch t { case .A: str = "A" case .B: str = "B" default: // expected-warning {{default will never be executed}} str = "unknown" // Should not be rejected. } return str } } @noreturn func die() { die() } func testGuard(a : Int) { guard case 4 = a else { } // expected-error {{'guard' body may not fall through, consider using 'return' or 'break'}} guard case 4 = a else { return } // ok guard case 4 = a else { die() } // ok guard case 4 = a else { fatalError("baaad") } // ok for _ in 0...100 { guard case 4 = a else { continue } // ok } } public func testFailingCast(s:String) -> Int { // There should be no notes or warnings about a call to a noreturn function, because we do not expose // how casts are lowered. return s as! Int // expected-warning {{cast from 'String' to unrelated type 'Int' always fails}} } enum MyError : ErrorType { case A } @noreturn func raise() throws { throw MyError.A } func test_raise_1() throws -> Int { try raise() } func test_raise_2() throws -> Int { try raise() // expected-note {{a call to a noreturn function}} try raise() // expected-warning {{will never be executed}} } // If a guaranteed self call requires cleanup, don't warn about // release instructions struct Algol { var x: [UInt8] @noreturn func fail() throws { throw MyError.A } mutating func blah() throws -> Int { try fail() // no-warning } } class Lisp { @noreturn func fail() throws { throw MyError.A } } func transform<Scheme : Lisp>(s: Scheme) throws { try s.fail() // no-warning } func deferNoReturn() throws { defer { _ = Lisp() // no-warning } die() } func deferTryNoReturn() throws { defer { _ = Lisp() // no-warning } try raise() } func noReturnInDefer() { defer { _ = Lisp() die() // expected-note {{a call to a noreturn function}} die() // expected-warning {{will never be executed}} } } while true { } // no warning!
022d5ab0a11b6261f69a381a7dc471a9
20.014354
121
0.62352
false
false
false
false
ello/ello-ios
refs/heads/master
Specs/Networking/AuthenticationManagerSpec.swift
mit
1
//// /// AuthenticationManagerSpec.swift // @testable import Ello import Quick import Nimble class AuthenticationManagerSpec: QuickSpec { override func spec() { describe("AuthenticationManager") { describe("canMakeRequest(ElloAPI)") { let noTokenReqd: [ElloAPI] = [ .auth(email: "", password: ""), .reAuth(token: ""), .anonymousCredentials ] let anonymous: [ElloAPI] = [ .availability(content: [:]), .join(email: "", username: "", password: "", invitationCode: nil), .categories ] let authdOnly: [ElloAPI] = [ .amazonCredentials, .currentUserProfile, .pushSubscriptions(token: Data()) ] let expectations: [(AuthState, supported: [ElloAPI], unsupported: [ElloAPI])] = [ (.noToken, supported: noTokenReqd, unsupported: authdOnly), (.anonymous, supported: noTokenReqd + anonymous, unsupported: authdOnly), (.authenticated, supported: authdOnly, unsupported: []), (.initial, supported: noTokenReqd, unsupported: anonymous + authdOnly), (.userCredsSent, supported: noTokenReqd, unsupported: anonymous + authdOnly), ( .shouldTryUserCreds, supported: noTokenReqd, unsupported: anonymous + authdOnly ), (.refreshTokenSent, supported: noTokenReqd, unsupported: anonymous + authdOnly), ( .shouldTryRefreshToken, supported: noTokenReqd, unsupported: anonymous + authdOnly ), ( .anonymousCredsSent, supported: noTokenReqd, unsupported: anonymous + authdOnly ), ( .shouldTryAnonymousCreds, supported: noTokenReqd, unsupported: anonymous + authdOnly ), ] for (state, supported, unsupported) in expectations { for supportedEndpoint in supported { it("\(state) should support \(supportedEndpoint)") { let manager = AuthenticationManager.shared manager.specs(setAuthState: state) expect(manager.canMakeRequest(supportedEndpoint)) == true } } for unsupportedEndpoint in unsupported { it("\(state) should not support \(unsupportedEndpoint)") { let manager = AuthenticationManager.shared manager.specs(setAuthState: state) expect(manager.canMakeRequest(unsupportedEndpoint)) == false } } } } } } }
ae907067e0a68f2bc924666cd90e64df
44.397059
100
0.487528
false
false
false
false
material-components/material-components-ios-codelabs
refs/heads/master
MDC-104/Swift/Complete/Shrine/Shrine/AppDelegate.swift
apache-2.0
1
/* Copyright 2018-present the Material Components for iOS authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. // Set our default catalog filter to the Featured items Catalog.categoryFilter = "Featured" self.window = UIWindow(frame: UIScreen.main.bounds) let storyboard = UIStoryboard(name: "Main", bundle: nil) //TODO: Change the root view controller identifier to BackdropViewController let viewController = storyboard.instantiateViewController(withIdentifier: "BackdropViewController") self.window?.rootViewController = viewController self.window?.makeKeyAndVisible() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
1b4ddfddc73ccfb4abaac12e752456a0
45.238806
281
0.777276
false
false
false
false
JosephNK/JNKSwiftLib
refs/heads/master
JNKSwiftLib/FBSDKWrapper.swift
mit
1
// // FBSDKWrapper.swift // JNKSwiftLib // // Created by JosephNK on 2017. 2. 5.. // Copyright © 2017년 JosephNK. All rights reserved. // import UIKit import FBSDKCoreKit import FBSDKLoginKit public class FBSDKWrapper { public static let sharedInstance = FBSDKWrapper() init() { } public func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) { let _ = FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions) } public func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { let handle = FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: sourceApplication, annotation: annotation) return handle } public func getAccessToken() -> FBSDKAccessToken { return FBSDKAccessToken.current() } public func getCurrentAccessToken() -> (appID: String, tokenString: String, expirationDate: Date)? { if let token = FBSDKAccessToken.current() { return (appID: token.appID, tokenString: token.tokenString, expirationDate: token.expirationDate) } return nil } // ex) requestGraph: "me", parameters: ["fields": "email, first_name, last_name"] public func requestGraph(graphPath: String!, parameters: [AnyHashable : Any]!, completionHandler: @escaping ((_ result: Any?, _ error: Error?) -> Void)) { FBSDKGraphRequest(graphPath: graphPath, parameters: parameters).start { (connection, result, error) in completionHandler(result, error) } } // ex) permissions: ["email"] public func requestLogin(permissions: [Any]!, from fromViewController: UIViewController!, completionHandler: @escaping ((_ isLogin: Bool) -> Void)) { let loginManager = FBSDKLoginManager() loginManager.logIn(withReadPermissions: permissions, from: fromViewController) { (result, error) in if error != nil { completionHandler(false) return } if let _result = result { if _result.isCancelled { completionHandler(false) return } } completionHandler(true) } } }
923113d2e6d6a775f1c8985daa5fe45d
35.304348
160
0.631138
false
false
false
false
LearningSwift2/LearningApps
refs/heads/master
SimpleVideoPlayer/SimpleVideoPlayer/ViewController.swift
apache-2.0
1
// // ViewController.swift // SimpleVideoPlayer // // Created by Phil Wright on 12/1/15. // Copyright © 2015 Touchopia, LLC. All rights reserved. // import UIKit import AVKit import AVFoundation class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "MoviePlayer" { let destination = segue.destinationViewController as! AVPlayerViewController if let path = NSBundle.mainBundle().pathForResource("GITGirlsProgram", ofType:"mp4") { let url = NSURL(fileURLWithPath: path) destination.player = AVPlayer(URL: url) } } } }
5eaf94b34bf5e746a132e5a892a4d2ad
26.648649
102
0.609971
false
false
false
false
alickbass/ViewComponents
refs/heads/master
ViewComponents/UIControlStyle.swift
mit
1
// // UIControlStyle.swift // ViewComponents // // Created by Oleksii on 01/05/2017. // Copyright © 2017 WeAreReasonablePeople. All rights reserved. // import UIKit private enum UIControlStyleKey: Int, StyleKey { case isEnabled = 150, isSelected, isHighlighted case contentVerticalAlignment, contentHorizontalAlignment } public extension AnyStyle where T: UIControl { private typealias ViewStyle<Item> = Style<T, Item, UIControlStyleKey> public static func isEnabled(_ value: Bool) -> AnyStyle<T> { return ViewStyle(value, key: .isEnabled, sideEffect: { $0.isEnabled = $1 }).toAnyStyle } public static func isSelected(_ value: Bool) -> AnyStyle<T> { return ViewStyle(value, key: .isSelected, sideEffect: { $0.isSelected = $1 }).toAnyStyle } public static func isHighlighted(_ value: Bool) -> AnyStyle<T> { return ViewStyle(value, key: .isHighlighted, sideEffect: { $0.isHighlighted = $1 }).toAnyStyle } public static func contentVerticalAlignment(_ value: UIControlContentVerticalAlignment) -> AnyStyle<T> { return ViewStyle(value, key: .contentVerticalAlignment, sideEffect: { $0.contentVerticalAlignment = $1 }).toAnyStyle } public static func contentHorizontalAlignment(_ value: UIControlContentHorizontalAlignment) -> AnyStyle<T> { return ViewStyle(value, key: .contentHorizontalAlignment, sideEffect: { $0.contentHorizontalAlignment = $1 }).toAnyStyle } }
2997acf10e0d824c648834258d308a54
38.078947
128
0.705724
false
false
false
false
chashmeetsingh/Youtube-iOS
refs/heads/master
YouTube Demo/AppDelegate.swift
mit
1
// // AppDelegate.swift // YouTube Demo // // Created by Chashmeet Singh on 06/01/17. // Copyright © 2017 Chashmeet Singh. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) window?.makeKeyAndVisible() let layout = UICollectionViewFlowLayout() window?.rootViewController = UINavigationController(rootViewController: HomeController(collectionViewLayout: layout)) UINavigationBar.appearance().barTintColor = UIColor.rgb(red: 230, green: 32, blue: 31) // Remove black shadow UINavigationBar.appearance().shadowImage = UIImage() UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default) application.statusBarStyle = .lightContent let statusBarBackgroundView = UIView() statusBarBackgroundView.backgroundColor = UIColor.rgb(red: 194, green: 31, blue: 31) window?.addSubview(statusBarBackgroundView) window?.addConstraintsWithFormat(format: "H:|[v0]|", view: statusBarBackgroundView) window?.addConstraintsWithFormat(format: "V:|[v0(20)]", view: statusBarBackgroundView) return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
d9b060e45006ed984cc62740b23180fc
46.621212
285
0.727967
false
false
false
false
Hbaoxian/HBXXMPPFrameWorkDemo
refs/heads/master
Demo/Pods/KissXML/KissXML/DDXML.swift
apache-2.0
7
// // DDXML.swift // KissXML // // Created by David Chiles on 1/29/16. // // import Foundation #if os(iOS) || os(watchOS) || os(tvOS) public typealias XMLNode = DDXMLNode public typealias XMLElement = DDXMLElement public typealias XMLDocument = DDXMLDocument public let XMLInvalidKind = DDXMLInvalidKind public let XMLDocumentKind = DDXMLDocumentKind public let XMLElementKind = DDXMLElementKind public let XMLAttributeKind = DDXMLAttributeKind public let XMLNamespaceKind = DDXMLNamespaceKind public let XMLProcessingInstructionKind = DDXMLProcessingInstructionKind public let XMLCommentKind = DDXMLCommentKind public let XMLTextKind = DDXMLTextKind public let XMLDTDKind = DDXMLDTDKind public let XMLEntityDeclarationKind = DDXMLEntityDeclarationKind public let XMLAttributeDeclarationKind = DDXMLAttributeDeclarationKind public let XMLElementDeclarationKind = DDXMLElementDeclarationKind public let XMLNotationDeclarationKind = DDXMLNotationDeclarationKind public let XMLNodeOptionsNone = DDXMLNodeOptionsNone public let XMLNodeExpandEmptyElement = DDXMLNodeExpandEmptyElement public let XMLNodeCompactEmptyElement = DDXMLNodeCompactEmptyElement public let XMLNodePrettyPrint = DDXMLNodePrettyPrint #endif
bdc50d7b17725ade867857d500bc6b38
40.0625
77
0.787671
false
false
false
false
SwiftAndroid/swift
refs/heads/master
test/Interpreter/SDK/archiving_generic_swift_class.swift
apache-2.0
4
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop // UNSUPPORTED: OS=tvos // UNSUPPORTED: OS=watchos import Foundation final class Foo<T: NSCoding>: NSObject, NSCoding { var one, two: T init(one: T, two: T) { self.one = one self.two = two } @objc required convenience init(coder: NSCoder) { let one = coder.decodeObject(forKey: "one") as! T let two = coder.decodeObject(forKey :"two") as! T self.init(one: one, two: two) } @objc(encodeWithCoder:) func encode(with encoder: NSCoder) { encoder.encode(one, forKey: "one") encoder.encode(two, forKey: "two") } } // FIXME: W* macro equivalents should be in the Darwin/Glibc overlay func WIFEXITED(_ status: Int32) -> Bool { return (status & 0o177) == 0 } func WEXITSTATUS(_ status: Int32) -> Int32 { return (status >> 8) & 0xFF } // FIXME: "environ" should be in the Darwin overlay too @_silgen_name("_NSGetEnviron") func _NSGetEnviron() -> UnsafeMutablePointer<UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>> var environ: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?> { return _NSGetEnviron().pointee } func driver() { // Create a pipe to connect the archiver to the unarchiver. var pipes: [Int32] = [0, 0] guard pipe(&pipes) == 0 else { fatalError("pipe failed") } let pipeRead = pipes[0], pipeWrite = pipes[1] var archiver: pid_t = 0, unarchiver: pid_t = 0 let envp = environ do { // Set up the archiver's stdout to feed into our pipe. var archiverActions: posix_spawn_file_actions_t? = nil guard posix_spawn_file_actions_init(&archiverActions) == 0 else { fatalError("posix_spawn_file_actions_init failed") } defer { posix_spawn_file_actions_destroy(&archiverActions) } guard posix_spawn_file_actions_adddup2(&archiverActions, pipeWrite, STDOUT_FILENO) == 0 && posix_spawn_file_actions_addclose(&archiverActions, pipeRead) == 0 else { fatalError("posix_spawn_file_actions_add failed") } // Spawn the archiver process. let archiverArgv: [UnsafeMutablePointer<Int8>?] = [ Process.unsafeArgv[0], UnsafeMutablePointer(("-archive" as StaticString).utf8Start), nil ] guard posix_spawn(&archiver, Process.unsafeArgv[0], &archiverActions, nil, archiverArgv, envp) == 0 else { fatalError("posix_spawn failed") } } do { // Set up the unarchiver's stdin to read from our pipe. var unarchiverActions: posix_spawn_file_actions_t? = nil guard posix_spawn_file_actions_init(&unarchiverActions) == 0 else { fatalError("posix_spawn_file_actions_init failed") } defer { posix_spawn_file_actions_destroy(&unarchiverActions) } guard posix_spawn_file_actions_adddup2(&unarchiverActions, pipeRead, STDIN_FILENO) == 0 && posix_spawn_file_actions_addclose(&unarchiverActions, pipeWrite) == 0 else { fatalError("posix_spawn_file_actions_add failed") } // Spawn the unarchiver process. var unarchiver: pid_t = 0 let unarchiverArgv: [UnsafeMutablePointer<Int8>?] = [ Process.unsafeArgv[0], UnsafeMutablePointer(("-unarchive" as StaticString).utf8Start), nil ] guard posix_spawn(&unarchiver, Process.unsafeArgv[0], &unarchiverActions, nil, unarchiverArgv, envp) == 0 else { fatalError("posix_spawn failed") } } // Wash our hands of the pipe, now that the subprocesses have started. close(pipeRead) close(pipeWrite) // Wait for the subprocesses to finish. var waiting: Set<pid_t> = [archiver, unarchiver] while !waiting.isEmpty { var status: Int32 = 0 let pid = wait(&status) if pid == -1 { // If the error was EINTR, just wait again. if errno == EINTR { continue } // If we have no children to wait for, stop. if errno == ECHILD { break } fatalError("wait failed") } waiting.remove(pid) // Ensure the process exited successfully. guard WIFEXITED(status) && WEXITSTATUS(status) == 0 else { fatalError("subprocess exited abnormally") } } } func archive() { let data = NSMutableData() let archiver = NSKeyedArchiver(forWritingWith: data) archiver.encode(Foo<NSString>(one: "one", two: "two"), forKey: "strings") archiver.encode(Foo<NSNumber>(one: 1, two: 2), forKey: "numbers") archiver.finishEncoding() // Output the archived data over stdout, which should be piped to stdin // on the unarchiver process. while true { let status = write(STDOUT_FILENO, data.bytes, data.length) if status == data.length { break } if errno == EINTR { continue } fatalError("write failed") } } func unarchive() { // FIXME: Pre-instantiate the generic classes that were archived, since // the ObjC runtime doesn't know how. NSStringFromClass(Foo<NSNumber>.self) NSStringFromClass(Foo<NSString>.self) // Read in the data from stdin, where the archiver process should have // written it. var rawData: [UInt8] = [] var buffer = [UInt8](repeating: 0, count: 4096) while true { let count = read(STDIN_FILENO, &buffer, 4096) if count == 0 { break } if count == -1 { if errno == EINTR { continue } fatalError("read failed") } rawData += buffer[0..<count] } // Feed it into an unarchiver. let data = NSData(bytes: rawData, length: rawData.count) let unarchiver = NSKeyedUnarchiver(forReadingWith: data) guard let strings = unarchiver.decodeObject(forKey: "strings") as? Foo<NSString> else { fatalError("unable to unarchive Foo<NSString>") } guard let numbers = unarchiver.decodeObject(forKey: "numbers") as? Foo<NSNumber> else { fatalError("unable to unarchive Foo<NSNumber>") } // CHECK-LABEL: <_TtGC4main3FooCSo8NSString_: {{0x[0-9a-f]+}}> #0 // CHECK: one: one // CHECK: two: two // CHECK-LABEL: <_TtGC4main3FooCSo8NSNumber_: {{0x[0-9a-f]+}}> #0 // CHECK: one: 1 // CHECK: two: 2 dump(strings) dump(numbers) } // Pick a mode based on the command-line arguments. // The test launches as a "driver" which then respawns itself into reader // and writer subprocesses. if Process.arguments.count < 2 { driver() } else if Process.arguments[1] == "-archive" { archive() } else if Process.arguments[1] == "-unarchive" { unarchive() } else { fatalError("invalid commandline argument") }
dbc21c644cdb12ce84493539e20555a9
30.624413
96
0.632274
false
false
false
false
larryhou/swift
refs/heads/master
LocateMe/LocateMe/LocateViewController.swift
mit
1
// // LocateViewController.swift // LocateMe // // Created by doudou on 8/17/14. // Copyright (c) 2014 larryhou. All rights reserved. // import Foundation import CoreLocation import UIKit extension CLAuthorizationStatus { var description: String { var status: String switch self { case .Authorized:status="Authorized" case .AuthorizedWhenInUse:status="AuthorizedWhenInUse" case .Denied:status="Denied" case .NotDetermined:status="NotDetermined" case .Restricted:status="Restriced" } return "CLAuthorizationStatus.\(status)" } } class LocateViewController: UITableViewController, SetupSettingReceiver, CLLocationManagerDelegate { enum LocationUpdateStatus: String { case Updating = "Updating" case Timeout = "Timeout" case Acquired = "Acquired Location" case Error = "Error" case None = "None" } enum SectionType: Int { case LocateStatus = 0 case BestMeasurement = 1 case Measurements = 2 } enum CellIdentifier: String { case Status = "StatusCell" case Measurement = "MeasurementCell" } private var setting: LocateSettingInfo! private var dateFormatter: NSDateFormatter! private var leftFormatter: NSNumberFormatter! private var bestMeasurement: CLLocation! private var measurements: [CLLocation]! private var locationManager: CLLocationManager! private var timer: NSTimer! private var remainTime: Float! private var status: LocationUpdateStatus! func setupSetting(setting: LocateSettingInfo) { self.setting = setting } override func viewDidLoad() { dateFormatter = NSDateFormatter() dateFormatter.dateFormat = localizeString("DateFormat") leftFormatter = NSNumberFormatter() leftFormatter.minimumIntegerDigits = 2 leftFormatter.maximumFractionDigits = 0 measurements = [] locationManager = CLLocationManager() } override func viewWillAppear(animated: Bool) { if bestMeasurement == nil { startUpdateLocation() } } override func viewWillDisappear(animated: Bool) { stopUpdatingLocation(.None) } // MARK: 数据重置 @IBAction func refresh(sender: UIBarButtonItem) { startUpdateLocation() } // MARK: 定位相关 func startUpdateLocation() { if timer != nil { timer.invalidate() timer = nil } locationManager.stopUpdatingLocation() measurements.removeAll(keepCapacity: false) bestMeasurement = nil status = .Updating tableView.reloadData() println(setting) remainTime = setting.sliderValue timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "timeTickUpdate", userInfo: nil, repeats: true) // FIXME: 无法使用带参数的selector,否则报错: [NSCFTimer copyWithZone:]: unrecognized selector sent to instance // timer = NSTimer.scheduledTimerWithTimeInterval(delay, // target: self, selector: "stopUpdatingLocation:", // userInfo: nil, repeats: false) if (CLLocationManager.authorizationStatus() != CLAuthorizationStatus.AuthorizedWhenInUse) { locationManager.requestWhenInUseAuthorization() } locationManager.desiredAccuracy = setting.accuracy locationManager.delegate = self locationManager.startUpdatingLocation() } func stopUpdatingLocation(status: LocationUpdateStatus) { if status != .None { self.status = status tableView.reloadData() } locationManager.stopUpdatingLocation() locationManager.delegate = nil if timer != nil { timer.invalidate() timer = nil } } func timeTickUpdate() { remainTime!-- tableView.reloadData() if remainTime <= 0 { stopUpdatingLocation(.Timeout) } } func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) { println("authorization:\(status.description)") } func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { for data in locations { var location = data as CLLocation measurements.append(location) if bestMeasurement == nil || bestMeasurement.horizontalAccuracy > location.horizontalAccuracy { bestMeasurement = location if location.horizontalAccuracy < locationManager.desiredAccuracy { stopUpdatingLocation(.Acquired) } } } tableView.reloadData() } func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) { stopUpdatingLocation(.Error) } // MARK: 列表展示 override func numberOfSectionsInTableView(tableView: UITableView!) -> Int { return bestMeasurement != nil ? 3 : 1 } override func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat { switch SectionType.fromRaw(indexPath.section)! { case .LocateStatus:return 60.0 //FIXME: 自定义UITableViewCell需要手动指定高度 default:return super.tableView(tableView, heightForRowAtIndexPath: indexPath) } } override func tableView(tableView: UITableView!, titleForHeaderInSection section: Int) -> String! { if let type = SectionType.fromRaw(section) { switch type { case .LocateStatus: return localizeString("Status") case .BestMeasurement: return localizeString("Best Measurement") case .Measurements: return localizeString("All Measurements") } } else { return nil } } override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { if let type = SectionType.fromRaw(section) { switch type { case .LocateStatus:return 1 case .BestMeasurement:return 1 case .Measurements:return measurements.count } } else { return 0 } } override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { if let type = SectionType.fromRaw(indexPath.section) { switch type { case .LocateStatus: var cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier.Status.toRaw()) as StatusTableViewCell cell.timeTicker.text = leftFormatter.stringFromNumber(remainTime) cell.label.text = localizeString(status.toRaw()) if status == .Updating { cell.timeTicker.alpha = 1.0 if !cell.indicator.isAnimating() { cell.indicator.startAnimating() } } else { cell.timeTicker.alpha = 0.0 if cell.indicator.isAnimating() { cell.indicator.stopAnimating() } } return cell case .BestMeasurement: var cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier.Measurement.toRaw()) as UITableViewCell cell.textLabel.text = bestMeasurement.getCoordinateString() cell.detailTextLabel.text = dateFormatter.stringFromDate(bestMeasurement.timestamp) return cell case .Measurements: var location = measurements[indexPath.row] var cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier.Measurement.toRaw()) as UITableViewCell cell.textLabel.text = location.getCoordinateString() cell.detailTextLabel.text = dateFormatter.stringFromDate(location.timestamp) return cell } } else { return nil } } override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) { tableView.deselectRowAtIndexPath(indexPath, animated: true) } // MARK: segue override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { if segue.identifier == "LocationDetailSegue" { var indexPath = tableView.indexPathForCell(sender as UITableViewCell) var type: SectionType = SectionType.fromRaw(indexPath.section)! var destinationCtrl = segue.destinationViewController as LocationDetailViewController switch type { case .BestMeasurement: destinationCtrl.location = bestMeasurement case .Measurements: destinationCtrl.location = measurements[indexPath.row] default:break } } } }
5e373c399179cf361fb9a7f0ed418990
28.266904
118
0.691756
false
false
false
false
AlesTsurko/DNMKit
refs/heads/master
DNM_iOS/DNM_iOS/DurationalExtension.swift
gpl-2.0
1
// // DurationalExtension.swift // denm_view // // Created by James Bean on 8/23/15. // Copyright © 2015 James Bean. All rights reserved. // import UIKit public class DurationalExtension: LigatureHorizontal { public var width: CGFloat = 0 public init(y: CGFloat, left: CGFloat, right: CGFloat, width: CGFloat) { super.init(y: y, left: left, right: right) self.width = width build() } public override init() { super.init() } public override init(layer: AnyObject) { super.init(layer: layer) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override func setVisualAttributes() { lineWidth = width strokeColor = UIColor.grayscaleColorWithDepthOfField(.Middleground).CGColor opacity = 0.666 } }
f5e446fcf0b07fa63911c40e9547e661
26.866667
83
0.651914
false
false
false
false
PrashantMangukiya/SwiftUIDemo
refs/heads/master
Demo24-UIToolbar/Demo24-UIToolbar/ViewController.swift
mit
1
// // ViewController.swift // Demo24-UIToolbar // // Created by Prashant on 10/10/15. // Copyright © 2015 PrashantKumar Mangukiya. All rights reserved. // import UIKit class ViewController: UIViewController { // maintain state that toolbar is hiden or not. var toolbarHidden: Bool = false // outlet - toolbar @IBOutlet var toolbar: UIToolbar! // Action - toggle button @IBAction func toggleButtonAction(_ sender: UIButton) { // We are moving tool bar out of screen using animation. // i.e. we are changing the frame postion for the toolbar and change it's alpha. UIView.animate(withDuration: 1.0, animations: { () -> Void in // show/hide toolbar if self.toolbarHidden { self.toolbarHidden = false let frameRect = CGRect(x: self.toolbar.frame.origin.x, y: self.toolbar.frame.origin.y - self.toolbar.frame.height , width: self.toolbar.frame.width , height: self.toolbar.frame.height) self.toolbar.frame = frameRect self.toolbar.alpha = 1.0 }else { self.toolbarHidden = true let frameRect = CGRect(x: self.toolbar.frame.origin.x , y: self.toolbar.frame.origin.y + self.toolbar.frame.height, width: self.toolbar.frame.width , height: self.toolbar.frame.height) self.toolbar.frame = frameRect self.toolbar.alpha = 0 } }) } // outlet - debug label @IBOutlet var debugLabel: UILabel! // action - rewind button @IBAction func rewindButtonAction(_ sender: UIBarButtonItem) { self.debugLabel.text = "Rewind - Action" } // action - play button @IBAction func playButtonAction(_ sender: UIBarButtonItem) { self.debugLabel.text = "Play - Action" } // action - pause button @IBAction func pauseButtonAction(_ sender: UIBarButtonItem) { self.debugLabel.text = "Pause - Action" } // action - forward button @IBAction func forwardButtonAction(_ sender: UIBarButtonItem) { self.debugLabel.text = "Forward - Action" } // MARK: - View functions override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
e9223a67cca05d1bde0124ebd2c0203b
29.022222
206
0.57883
false
false
false
false
thiagolioy/marvelapp
refs/heads/master
Marvel/Network/MarvelAPIManager.swift
mit
1
// // MarvelAPIManager.swift // Marvel // // Created by Thiago Lioy on 14/11/16. // Copyright © 2016 Thiago Lioy. All rights reserved. // import Foundation import Moya import RxSwift import ObjectMapper import Moya_ObjectMapper extension Response { func removeAPIWrappers() -> Response { guard let json = try? self.mapJSON() as? Dictionary<String, AnyObject>, let results = json?["data"]?["results"] ?? [], let newData = try? JSONSerialization.data(withJSONObject: results, options: .prettyPrinted) else { return self } let newResponse = Response(statusCode: self.statusCode, data: newData, response: self.response) return newResponse } } struct MarvelAPIManager { let provider: RxMoyaProvider<MarvelAPI> let disposeBag = DisposeBag() init() { provider = RxMoyaProvider<MarvelAPI>() } } extension MarvelAPIManager { typealias AdditionalStepsAction = (() -> ()) fileprivate func requestObject<T: Mappable>(_ token: MarvelAPI, type: T.Type, completion: @escaping (T?) -> Void, additionalSteps: AdditionalStepsAction? = nil) { provider.request(token) .debug() .mapObject(T.self) .subscribe { event -> Void in switch event { case .next(let parsedObject): completion(parsedObject) additionalSteps?() case .error(let error): print(error) completion(nil) default: break } }.addDisposableTo(disposeBag) } fileprivate func requestArray<T: Mappable>(_ token: MarvelAPI, type: T.Type, completion: @escaping ([T]?) -> Void, additionalSteps: AdditionalStepsAction? = nil) { provider.request(token) .debug() .map { response -> Response in return response.removeAPIWrappers() } .mapArray(T.self) .subscribe { event -> Void in switch event { case .next(let parsedArray): completion(parsedArray) additionalSteps?() case .error(let error): print(error) completion(nil) default: break } }.addDisposableTo(disposeBag) } } protocol MarvelAPICalls { func characters(query: String?, completion: @escaping ([Character]?) -> Void) } extension MarvelAPIManager: MarvelAPICalls { func characters(query: String? = nil, completion: @escaping ([Character]?) -> Void) { requestArray(.characters(query), type: Character.self, completion: completion) } }
eb7f9d732a7bcb89584d9f5df7b00a03
29.323529
110
0.515681
false
false
false
false
IngmarStein/swift
refs/heads/master
benchmark/single-source/PolymorphicCalls.swift
apache-2.0
4
//===--- PolymorphicCalls.swift -------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /* This benchmark is used to check the performance of polymorphic invocations. Essentially, it checks how good a compiler can optimize virtual calls of class methods in cases where multiple sub-classes of a given class are available. In particular, this benchmark would benefit from a good devirtualization. In case of applying a speculative devirtualization, it would be benefit from applying a jump-threading in combination with the speculative devirtualization. */ import TestsUtils public class A { let b: B init(b:B) { self.b = b } public func run1() -> Int { return b.f1() + b.f2() + b.f3() } public func run2() -> Int { return b.run() } } // B has no known subclasses public class B { let x: Int init(x:Int) { self.x = x } public func f1() -> Int { return x + 1 } public func f2() -> Int { return x + 11 } public func f3() -> Int { return x + 111 } public func run() -> Int { return f1() + f2() + f3() } } public class A1 { let b: B1 public init(b:B1) { self.b = b } public func run1() -> Int { return b.f1() + b.f2() + b.f3() } public func run2() -> Int { return b.run() } } // B1 has 1 known subclass public class B1 { func f1() -> Int { return 0 } func f2() -> Int { return 0 } func f3() -> Int { return 0 } public func run() -> Int { return f1() + f2() + f3() } } public class C1: B1 { let x: Int init(x:Int) { self.x = x } override public func f1() -> Int { return x + 2 } override public func f2() -> Int { return x + 22 } override public func f3() -> Int { return x + 222 } } public class A2 { let b:B2 public init(b:B2) { self.b = b } public func run1() -> Int { return b.f1() + b.f2() + b.f3() } public func run2() -> Int { return b.run() } } // B2 has 2 known subclasses public class B2 { func f1() -> Int { return 0 } func f2() -> Int { return 0 } func f3() -> Int { return 0 } public func run() -> Int { return f1() + f2() + f3() } } public class C2 : B2 { let x: Int init(x:Int) { self.x = x } override public func f1() -> Int { return x + 3 } override public func f2() -> Int { return x + 33 } override public func f3() -> Int { return x + 333 } } public class D2 : B2 { let x: Int init(x:Int) { self.x = x } override public func f1() -> Int { return x + 4 } override public func f2() -> Int { return x + 44 } override public func f3() -> Int { return x + 444 } } public class A3 { let b: B3 public init(b:B3) { self.b = b } public func run1() -> Int { return b.f1() + b.f2() + b.f3() } public func run2() -> Int { return b.run() } } // B3 has 3 known subclasses public class B3 { func f1() -> Int { return 0 } func f2() -> Int { return 0 } func f3() -> Int { return 0 } public func run() -> Int { return f1() + f2() + f3() } } public class C3: B3 { let x: Int init(x:Int) { self.x = x } override public func f1() -> Int { return x + 5 } override public func f2() -> Int { return x + 55 } override public func f3() -> Int { return x + 555 } } public class D3: B3 { let x: Int init(x:Int) { self.x = x } override public func f1() -> Int { return x + 6 } override public func f2() -> Int { return x + 66 } override public func f3() -> Int { return x + 666 } } public class E3:B3 { let x: Int init(x:Int) { self.x = x } override public func f1() -> Int { return x + 7 } override public func f2() -> Int { return x + 77 } override public func f3() -> Int { return x + 777 } } public class F3 : B3 { let x: Int init(x:Int) { self.x = x } override public func f1() -> Int { return x + 8 } override public func f2() -> Int { return x + 88 } override public func f3() -> Int { return x + 888 }} // Test the cost of polymorphic method invocation // on a class without any subclasses @inline(never) func test(_ a:A, _ UPTO: Int) -> Int64 { var cnt: Int64 = 0 for _ in 0..<UPTO { cnt += a.run2() } return cnt } // Test the cost of polymorphic method invocation // on a class with 1 subclass @inline(never) func test(_ a:A1, _ UPTO: Int) -> Int64 { var cnt: Int64 = 0 for _ in 0..<UPTO { cnt += a.run2() } return cnt } // Test the cost of polymorphic method invocation // on a class with 2 subclasses @inline(never) func test(_ a:A2, _ UPTO: Int) -> Int64 { var cnt: Int64 = 0 for _ in 0..<UPTO { cnt += a.run2() } return cnt } // Test the cost of polymorphic method invocation // on a class with 2 subclasses on objects // of different subclasses @inline(never) func test(_ a2_c2:A2, _ a2_d2:A2, _ UPTO: Int) -> Int64 { var cnt: Int64 = 0 for _ in 0..<UPTO/2 { cnt += a2_c2.run2() cnt += a2_d2.run2() } return cnt } // Test the cost of polymorphic method invocation // on a class with 4 subclasses on objects // of different subclasses @inline(never) func test(_ a3_c3: A3, _ a3_d3: A3, _ a3_e3: A3, _ a3_f3: A3, _ UPTO: Int) -> Int64 { var cnt: Int64 = 0 for _ in 0..<UPTO/4 { cnt += a3_c3.run2() cnt += a3_d3.run2() cnt += a3_e3.run2() cnt += a3_f3.run2() } return cnt } @inline(never) public func run_PolymorphicCalls(_ N:Int) { let UPTO = 10000 * N let a = A(b:B(x:1)) _ = test(a, UPTO) let a1 = A1(b:C1(x:1)) _ = test(a1, UPTO) let a2 = A2(b:C2(x:1)) _ = test(a2, UPTO) let a2_c2 = A2(b:C2(x:1)) let a2_d2 = A2(b:D2(x:1)) _ = test(a2_c2, a2_d2, UPTO) let a3_c3 = A3(b:C3(x:1)) let a3_d3 = A3(b:D3(x:1)) let a3_e3 = A3(b:E3(x:1)) let a3_f3 = A3(b:F3(x:1)) _ = test(a3_c3, a3_d3, a3_e3, a3_f3, UPTO) }
95332e75a5f135aa8ade6914a46fef97
19.537538
85
0.517473
false
false
false
false
maikotrindade/ios-basics
refs/heads/master
playground3.playground/Contents.swift
gpl-3.0
1
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" func firstfunction() { print("Hello!") } firstfunction() func secondFunction() -> Int { return 12345 } secondFunction() func thirdFunc (firstValue : Int, secondValue: Int) -> Int { return firstValue + secondValue } thirdFunc(100, 900) //thirdFunc(100, secondValue: 123) func forthFunction(firstValue : Int, secondValue: Int) -> (doubled : Int, qradrupled : Int) { return (firstValue * 2, secondValue * 4) } forthFunction(2, 2) forthFunction(2, 2).0 forthFunction(2, 2).qradrupled //array of numbers func addNumbers(numbers: Int...) -> Int { var total = 0 for number in numbers { total += number } return total } addNumbers(1,2,3,4,5,6,7,8,9,10) //params func swapValues(inout firstValue: Int, inout secondValue: Int) { let tempValue = firstValue firstValue = secondValue secondValue = tempValue } var swap1 = 10 var swap2 = 20 swapValues(&swap1, &swap2) print("\(swap1), \(swap2)") //variable as Func var numbersFunc: (Int...) -> Int numbersFunc = addNumbers numbersFunc(2,3,4,5,6,7) //func as param func timesThree(number: Int) -> Int{ return number*3 } //func doSomethingToNumber (aNumber: Int, thingToDo: (Int)->Int)->Int { // return thingsToDo(aNumber) //} //doSomethingToNumber(4, thingToDo: timesThree) func createAdder(numberToAdd: Int) -> (Int) -> Int { func adder(number:Int) -> Int{ return number + numberToAdd } return adder } var addTwo = createAdder(2) addTwo(2) func createInc(incrementAmount : Int) -> () -> Int { var amount = 0 func incrementor () -> Int { amount += incrementAmount return amount } return incrementor } var incrementByTen = createInc(10) incrementByTen() incrementByTen() class Vehicle { var color : String? var maxSpeed = 80 func description() -> String { return "A \(self.color) vehicle" } func travel() { print("Traveling ar \(maxSpeed) kph") } } var redVehicle = Vehicle() redVehicle.color = "Red" redVehicle.maxSpeed = 95
e210c38b87982d33e9fd265bfbc062cd
9.549296
93
0.624833
false
false
false
false
MateuszKarwat/Napi
refs/heads/master
Napi/Controllers/Preferences/Tabs/MatchPreferencesViewController.swift
mit
1
// // Created by Mateusz Karwat on 09/04/2017. // Copyright © 2017 Mateusz Karwat. All rights reserved. // import AppKit final class MatchPreferencesViewController: NSViewController { @IBOutlet private weak var cancelRadioButton: NSButton! @IBOutlet private weak var overrideRadioButton: NSButton! @IBOutlet private weak var backupNewSubtitlesRadioButton: NSButton! @IBOutlet private weak var backupExistingSubtitlesRadioButton: NSButton! var radioButtonsBinding: [NameMatcher.NameConflictAction: NSButton] { return [.cancel: cancelRadioButton, .override: overrideRadioButton, .backupSourceItem: backupNewSubtitlesRadioButton, .backupDestinationItem: backupExistingSubtitlesRadioButton] } override func viewDidLoad() { super.viewDidLoad() setupRadioButtons() } private func setupRadioButtons() { if let enabledRadioButton = radioButtonsBinding[Preferences[.nameConflictAction]] { enabledRadioButton.state = .on } } @IBAction func nameConflictActionRadioButtonDidChange(_ sender: NSButton) { radioButtonsBinding.forEach { nameConflictAction, radioButton in if radioButton === sender { Preferences[.nameConflictAction] = nameConflictAction return } } } }
ad52c780641f07649976600bec401ba6
32.707317
91
0.68741
false
false
false
false
huangboju/Moots
refs/heads/master
Examples/Lumia/Lumia/Component/DynamicsCatalog/Controllers/ItemPropertiesVC.swift
mit
1
// // ItemPropertiesVC.swift // Lumia // // Created by 黄伯驹 on 2020/1/1. // Copyright © 2020 黄伯驹. All rights reserved. // import UIKit class ItemPropertiesVC: UIViewController { private lazy var square: UIImageView = { let square = UIImageView(image: UIImage(named: "Box1")?.withRenderingMode(.alwaysTemplate)) square.frame = CGRect(origin: CGPoint(x: 110, y: 279), size: CGSize(width: 100, height: 100)) square.tintColor = .darkGray square.isUserInteractionEnabled = true return square }() private lazy var square1: UIImageView = { let square = UIImageView(image: UIImage(named: "Box1")?.withRenderingMode(.alwaysTemplate)) square.frame = CGRect(origin: CGPoint(x: 250, y: 279), size: CGSize(width: 100, height: 100)) square.tintColor = .darkGray square.isUserInteractionEnabled = true return square }() private lazy var square2PropertiesBehavior: UIDynamicItemBehavior = { let square2PropertiesBehavior = UIDynamicItemBehavior(items: [square1]) square2PropertiesBehavior.elasticity = 0.5 return square2PropertiesBehavior }() private lazy var square1PropertiesBehavior: UIDynamicItemBehavior = { let square1PropertiesBehavior = UIDynamicItemBehavior(items: [square]) return square1PropertiesBehavior }() var animator: UIDynamicAnimator? override func loadView() { view = DecorationView() } override func viewDidLoad() { super.viewDidLoad() view.addSubview(square) view.addSubview(square1) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Replay", style: .plain, target: self, action: #selector(replayAction)) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let animator = UIDynamicAnimator(referenceView: view) // We want to show collisions between views and boundaries with different // elasticities, we thus associate the two views to gravity and collision // behaviors. We will only change the restitution parameter for one of these // views. let gravityBeahvior = UIGravityBehavior(items: [square, square1]) let collisionBehavior = UICollisionBehavior(items: [square, square1]) collisionBehavior.translatesReferenceBoundsIntoBoundary = true // A dynamic item behavior gives access to low-level properties of an item // in Dynamics, here we change restitution on collisions only for square2, // and keep square1 with its default value. // A dynamic item behavior is created for square1 so it's velocity can be // manipulated in the -resetAction: method. animator.addBehavior(square1PropertiesBehavior) animator.addBehavior(square2PropertiesBehavior) animator.addBehavior(gravityBeahvior) animator.addBehavior(collisionBehavior) self.animator = animator } @objc func replayAction() { square1PropertiesBehavior.addLinearVelocity(CGPoint(x: 0, y: -1 * square1PropertiesBehavior.linearVelocity(for: square).y), for: square) square.center = CGPoint(x: 90, y: 171) animator?.updateItem(usingCurrentState: square) square2PropertiesBehavior.addLinearVelocity(CGPoint(x: 0, y: -1 * square2PropertiesBehavior.linearVelocity(for: square1).y), for: square1) square1.center = CGPoint(x: 230, y: 171) animator?.updateItem(usingCurrentState: square1) } }
4a3cf4c967ce07ad366f6e12beb437d6
37.284211
146
0.674457
false
false
false
false
carabina/string-in-chain
refs/heads/master
Example/Tests/Tests.swift
mit
1
// https://github.com/Quick/Quick import Quick import Nimble import StringInChain class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" dispatch_async(dispatch_get_main_queue()) { time = "done" } waitUntil { done in NSThread.sleepForTimeInterval(0.5) expect(time) == "done" done() } } } } } }
da62b4c4f9cf0f94193ce5973bf64e5c
22.48
63
0.365417
false
false
false
false
LoveZYForever/HXWeiboPhotoPicker
refs/heads/master
Pods/HXPHPicker/Sources/HXPHPicker/Picker/Controller/PhotoPickerController+FetchAsset.swift
mit
1
// // PhotoPickerController+FetchAsset.swift // HXPHPicker // // Created by Slience on 2021/8/25. // import UIKit import Photos // MARK: fetch Asset extension PhotoPickerController { func fetchData(status: PHAuthorizationStatus) { if status.rawValue >= 3 { PHPhotoLibrary.shared().register(self) // 有权限 ProgressHUD.showLoading(addedTo: view, afterDelay: 0.15, animated: true) fetchCameraAssetCollection() }else if status.rawValue >= 1 { // 无权限 view.addSubview(deniedView) } } /// 获取相机胶卷资源集合 func fetchCameraAssetCollection() { if !config.allowLoadPhotoLibrary { if cameraAssetCollection == nil { cameraAssetCollection = PhotoAssetCollection( albumName: config.albumList.emptyAlbumName.localized, coverImage: config.albumList.emptyCoverImageName.image ) } fetchCameraAssetCollectionCompletion?(cameraAssetCollection) return } if config.creationDate { options.sortDescriptors = [NSSortDescriptor.init(key: "creationDate", ascending: config.creationDate)] } PhotoManager.shared.fetchCameraAssetCollection( for: selectOptions, options: options ) { [weak self] (assetCollection) in guard let self = self else { return } if assetCollection.count == 0 { self.cameraAssetCollection = PhotoAssetCollection( albumName: self.config.albumList.emptyAlbumName.localized, coverImage: self.config.albumList.emptyCoverImageName.image ) }else { // 获取封面 self.cameraAssetCollection = assetCollection } if self.config.albumShowMode == .popup { self.fetchAssetCollections() } self.fetchCameraAssetCollectionCompletion?(self.cameraAssetCollection) } } /// 获取相册集合 func fetchAssetCollections() { cancelAssetCollectionsQueue() let operation = BlockOperation() operation.addExecutionBlock { [unowned operation] in if self.config.creationDate { self.options.sortDescriptors = [ NSSortDescriptor( key: "creationDate", ascending: self.config.creationDate ) ] } self.assetCollectionsArray = [] var localCount = self.localAssetArray.count + self.localCameraAssetArray.count var coverImage = self.localCameraAssetArray.first?.originalImage if coverImage == nil { coverImage = self.localAssetArray.first?.originalImage } var firstSetImage = true for phAsset in self.selectedAssetArray where phAsset.phAsset == nil { let inLocal = self.localAssetArray.contains( where: { $0.isEqual(phAsset) }) let inLocalCamera = self.localCameraAssetArray.contains( where: { $0.isEqual(phAsset) } ) if !inLocal && !inLocalCamera { if firstSetImage { coverImage = phAsset.originalImage firstSetImage = false } localCount += 1 } } if operation.isCancelled { return } if !self.config.allowLoadPhotoLibrary { DispatchQueue.main.async { self.cameraAssetCollection?.realCoverImage = coverImage self.cameraAssetCollection?.count += localCount self.assetCollectionsArray.append(self.cameraAssetCollection!) self.fetchAssetCollectionsCompletion?(self.assetCollectionsArray) } return } PhotoManager.shared.fetchAssetCollections( for: self.options, showEmptyCollection: false ) { [weak self] (assetCollection, isCameraRoll, stop) in guard let self = self else { stop.pointee = true return } if operation.isCancelled { stop.pointee = true return } if let assetCollection = assetCollection { if let collection = assetCollection.collection, let canAdd = self.pickerDelegate?.pickerController(self, didFetchAssetCollections: collection) { if !canAdd { return } } assetCollection.count += localCount if isCameraRoll { self.assetCollectionsArray.insert(assetCollection, at: 0) }else { self.assetCollectionsArray.append(assetCollection) } }else { if let cameraAssetCollection = self.cameraAssetCollection { self.cameraAssetCollection?.count += localCount if coverImage != nil { self.cameraAssetCollection?.realCoverImage = coverImage } if !self.assetCollectionsArray.isEmpty { self.assetCollectionsArray[0] = cameraAssetCollection }else { self.assetCollectionsArray.append(cameraAssetCollection) } } DispatchQueue.main.async { self.fetchAssetCollectionsCompletion?(self.assetCollectionsArray) } } } } assetCollectionsQueue.addOperation(operation) } func cancelAssetCollectionsQueue() { assetCollectionsQueue.cancelAllOperations() } private func getSelectAsset() -> ([PHAsset], [PhotoAsset]) { var selectedAssets = [PHAsset]() var selectedPhotoAssets: [PhotoAsset] = [] var localIndex = -1 for (index, photoAsset) in selectedAssetArray.enumerated() { if config.selectMode == .single { break } photoAsset.selectIndex = index photoAsset.isSelected = true if let phAsset = photoAsset.phAsset { selectedAssets.append(phAsset) selectedPhotoAssets.append(photoAsset) }else { let inLocal = localAssetArray .contains { if $0.isEqual(photoAsset) { localAssetArray[localAssetArray.firstIndex(of: $0)!] = photoAsset return true } return false } let inLocalCamera = localCameraAssetArray .contains(where: { if $0.isEqual(photoAsset) { localCameraAssetArray[ localCameraAssetArray.firstIndex(of: $0)! ] = photoAsset return true } return false }) if !inLocal && !inLocalCamera { if photoAsset.localIndex > localIndex { localIndex = photoAsset.localIndex localAssetArray.insert(photoAsset, at: 0) }else { if localIndex == -1 { localIndex = photoAsset.localIndex localAssetArray.insert(photoAsset, at: 0) }else { localAssetArray.insert(photoAsset, at: 1) } } } } } return (selectedAssets, selectedPhotoAssets) } /// 获取相册里的资源 /// - Parameters: /// - assetCollection: 相册 /// - completion: 完成回调 func fetchPhotoAssets( assetCollection: PhotoAssetCollection?, completion: (([PhotoAsset], PhotoAsset?, Int, Int) -> Void)? ) { cancelFetchAssetsQueue() let operation = BlockOperation() operation.addExecutionBlock { [unowned operation] in var photoCount = 0 var videoCount = 0 self.localAssetArray.forEach { $0.isSelected = false } self.localCameraAssetArray.forEach { $0.isSelected = false } let result = self.getSelectAsset() let selectedAssets = result.0 let selectedPhotoAssets = result.1 var localAssets: [PhotoAsset] = [] if operation.isCancelled { return } localAssets.append(contentsOf: self.localCameraAssetArray.reversed()) localAssets.append(contentsOf: self.localAssetArray) var photoAssets = [PhotoAsset]() photoAssets.reserveCapacity(assetCollection?.count ?? 10) var lastAsset: PhotoAsset? assetCollection?.enumerateAssets( usingBlock: { [weak self] (photoAsset, index, stop) in guard let self = self, let phAsset = photoAsset.phAsset else { stop.pointee = true return } if operation.isCancelled { stop.pointee = true return } if let canAdd = self.pickerDelegate?.pickerController(self, didFetchAssets: phAsset) { if !canAdd { return } } if self.selectOptions.contains(.gifPhoto) { if phAsset.isImageAnimated { photoAsset.mediaSubType = .imageAnimated } } if self.config.selectOptions.contains(.livePhoto) { if phAsset.isLivePhoto { photoAsset.mediaSubType = .livePhoto } } switch photoAsset.mediaType { case .photo: if !self.selectOptions.isPhoto { return } photoCount += 1 case .video: if !self.selectOptions.isVideo { return } videoCount += 1 } var asset = photoAsset if let index = selectedAssets.firstIndex(of: phAsset) { let selectPhotoAsset = selectedPhotoAssets[index] asset = selectPhotoAsset lastAsset = selectPhotoAsset } photoAssets.append(asset) }) if self.config.photoList.showAssetNumber { localAssets.forEach { if $0.mediaType == .photo { photoCount += 1 }else { videoCount += 1 } } } photoAssets.append(contentsOf: localAssets.reversed()) if self.config.photoList.sort == .desc { photoAssets.reverse() } if operation.isCancelled { return } DispatchQueue.main.async { completion?(photoAssets, lastAsset, photoCount, videoCount) } } assetsQueue.addOperation(operation) } func cancelFetchAssetsQueue() { assetsQueue.cancelAllOperations() } }
fc0553934e2ac436422e4487c3f80602
38.229032
119
0.491983
false
false
false
false
LeafPlayer/Leaf
refs/heads/master
Leaf/UIComponents/NSBackgourndChangableButton.swift
gpl-3.0
1
// // NSBackgourndChangableButton.swift // Leaf // // Created by lincolnlaw on 2017/11/2. // Copyright © 2017年 lincolnlaw. All rights reserved. // import Cocoa final class NSBackgourndChangableButton: NSView { typealias Action = (NSBackgourndChangableButton) -> Void private let normalBackground = CGColor(gray: 0, alpha: 0) private let hoverBackground = CGColor(gray: 0, alpha: 0.25) private let pressedBackground = CGColor(gray: 0, alpha: 0.35) public private(set) var action: Action = { _ in } override init(frame frameRect: NSRect) { super.init(frame: frameRect) } required init?(coder decoder: NSCoder) { super.init(coder: decoder) } convenience init(action: @escaping Action) { self.init(frame: .zero) self.action = action wantsLayer = true layer?.cornerRadius = 4 } override var frame: NSRect { get { return super.frame } set { for area in trackingAreas { removeTrackingArea(area) } super.frame = newValue addTrackingArea(NSTrackingArea(rect: bounds, options: [.activeInKeyWindow, .mouseEnteredAndExited], owner: self, userInfo: nil)) } } override func mouseEntered(with event: NSEvent) { layer?.backgroundColor = hoverBackground } override func mouseExited(with event: NSEvent) { layer?.backgroundColor = normalBackground } override func mouseDown(with event: NSEvent) { layer?.backgroundColor = pressedBackground action(self) } override func mouseUp(with event: NSEvent) { layer?.backgroundColor = hoverBackground } }
2b18a06df536821ee84fd52be1ffc35a
27.583333
140
0.638484
false
false
false
false
xwu/swift
refs/heads/master
test/ClangImporter/objc_async.swift
apache-2.0
1
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -I %S/Inputs/custom-modules -disable-availability-checking %s -verify // REQUIRES: objc_interop // REQUIRES: concurrency import Foundation import ObjCConcurrency @MainActor func onlyOnMainActor() { } func testSlowServer(slowServer: SlowServer) async throws { let _: Int = await slowServer.doSomethingSlow("mail") let _: Bool = await slowServer.checkAvailability() let _: String = try await slowServer.findAnswer() let _: String = try await slowServer.findAnswerFailingly() let (aOpt, b) = try await slowServer.findQAndA() if let a = aOpt { // make sure aOpt is optional print(a) } let _: String = b // make sure b is non-optional let _: String = try await slowServer.findAnswer() let _: Void = await slowServer.doSomethingFun("jump") let _: (Int) -> Void = slowServer.completionHandler // async version let _: Int = await slowServer.doSomethingConflicted("thinking") // still async version... let _: Int = slowServer.doSomethingConflicted("thinking") // expected-error@-1{{expression is 'async' but is not marked with 'await'}}{{16-16=await }} // expected-note@-2{{call is 'async'}} let _: String? = try await slowServer.fortune() let _: Int = try await slowServer.magicNumber(withSeed: 42) await slowServer.serverRestart("localhost") await slowServer.serverRestart("localhost", atPriority: 0.8) _ = await slowServer.allOperations() let _: Int = await slowServer.bestName("hello") let _: Int = await slowServer.customize("hello") let _: String = await slowServer.dance("slide") let _: String = await slowServer.__leap(17) slowServer.repeatTrick("jump") // expected-error{{missing argument for parameter 'completionHandler' in call}} _ = try await slowServer.someAsyncMethod() _ = await slowServer.operations() _ = await slowServer.runOnMainThread() } func testSlowServerSynchronous(slowServer: SlowServer) { // synchronous version let _: Int = slowServer.doSomethingConflicted("thinking") slowServer.poorlyNamed("hello") { (i: Int) in print(i) } slowServer.customize(with: "hello") { (i: Int) in print(i) } slowServer.dance("jig") { s in print(s + "") } slowServer.leap(17) { s in print(s + "") } slowServer.repeatTrick("jump") { i in print(i + 1) } let s = slowServer.operations _ = s + [] slowServer.runOnMainThread { s in print(s) onlyOnMainActor() // okay because runOnMainThread has a @MainActor closure } slowServer.overridableButRunsOnMainThread { s in print(s) onlyOnMainActor() // okay because parameter has @_unsafeMainActor } let _: Int = slowServer.overridableButRunsOnMainThread // expected-error{{cannot convert value of type '(((String) -> Void)?) -> Void' to specified type 'Int'}} } func testSlowServerOldSchool(slowServer: SlowServer) { slowServer.doSomethingSlow("mail") { i in _ = i } _ = slowServer.allOperations } func testSendable(fn: () -> Void) { // expected-note{{parameter 'fn' is implicitly non-sendable}} doSomethingConcurrently(fn) // expected-error@-1{{passing non-sendable parameter 'fn' to function expecting a @Sendable closure}} doSomethingConcurrentlyButUnsafe(fn) // okay, @Sendable not part of the type var x = 17 doSomethingConcurrently { print(x) // expected-error{{reference to captured var 'x' in concurrently-executing code}} x = x + 1 // expected-error{{mutation of captured var 'x' in concurrently-executing code}} // expected-error@-1{{reference to captured var 'x' in concurrently-executing code}} } } func testSendableInAsync() async { var x = 17 doSomethingConcurrentlyButUnsafe { x = 42 // expected-error{{mutation of captured var 'x' in concurrently-executing code}} } print(x) } // Check import of attributes func globalAsync() async { } actor MySubclassCheckingSwiftAttributes : ProtocolWithSwiftAttributes { func syncMethod() { } // expected-note 2{{calls to instance method 'syncMethod()' from outside of its actor context are implicitly asynchronous}} nonisolated func independentMethod() { syncMethod() // expected-error{{ctor-isolated instance method 'syncMethod()' can not be referenced from a non-isolated context}} } nonisolated func nonisolatedMethod() { } @MainActor func mainActorMethod() { syncMethod() // expected-error{{actor-isolated instance method 'syncMethod()' can not be referenced from the main actor}} } @MainActor func uiActorMethod() { } } // Sendable conformance inference for imported types. func acceptCV<T: Sendable>(_: T) { } func testCV(r: NSRange) { acceptCV(r) } // Global actor (unsafe) isolation. actor SomeActor { } @globalActor struct SomeGlobalActor { static let shared = SomeActor() } class MyButton : NXButton { @MainActor func testMain() { onButtonPress() // okay } @SomeGlobalActor func testOther() { onButtonPress() // expected-error{{call to main actor-isolated instance method 'onButtonPress()' in a synchronous global actor 'SomeGlobalActor'-isolated context}} } func test() { onButtonPress() // okay } } func testButtons(mb: MyButton) { mb.onButtonPress() } func testMirrored(instance: ClassWithAsync) async { await instance.instanceAsync() await instance.protocolMethod() await instance.customAsyncName() } @MainActor class MyToolbarButton : NXButton { var count = 5 func f() { Task { let c = count print(c) } } }
1da4afc9088dd2dbb78f43e047982998
28.918033
167
0.706119
false
true
false
false
clwi/CWPack
refs/heads/master
goodies/swift/CWPack.swift
mit
1
// // CWPack.swift // CWPack // // Created by Claes Wihlborg on 2022-01-17. // /* The MIT License (MIT) Copyright (c) 2021 Claes Wihlborg Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation //import AppKit enum CWPackError: Error { case fileError(_ errNo:Int) case contextError(_ err:Int32) case packerError(_ err:String) case unpackerError(_ err:String) } // MARK: ------------------------------ MessagePack Objects struct CWNil { } struct ArrayHeader { let count:Int init (_ count:Int) {self.count = count} init () {count = 0} } struct DictionaryHeader { let count:UInt32 init (_ count:UInt32) {self.count = count} init () {count = 0} } struct MsgPackExt { let type: Int8 let data: Data init (_ type:Int8, _ data: Data) { self.type = type self.data = data } } // MARK: ------------------------------ MessagePacker class CWPacker { let p: UnsafeMutablePointer<cw_pack_context> var optimizeReal: Bool = true var OK: Bool {p.pointee.return_code == CWP_RC_OK} init(_ p:UnsafeMutablePointer<cw_pack_context>) { self.p = p } } class CWDataPacker: CWPacker { private var context = dynamic_memory_pack_context() var data: Data { let c:Int = context.pc.current - context.pc.start return Data(bytes:context.pc.start, count:c)} init() { super.init(&context.pc) init_dynamic_memory_pack_context(&context, 1024) } } class CWFilePacker: CWPacker { private var context = file_pack_context() private let ownsChannel: Bool let fh: FileHandle? func flush() {cw_pack_flush(&context.pc)} init(to descriptor:Int32) { ownsChannel = false fh = nil super.init(&context.pc) init_file_pack_context(&context, 1024, descriptor) } init(to url:URL) throws { fh = try FileHandle(forWritingTo: url) ownsChannel = true super.init(&context.pc) init_file_pack_context(&context, 1024, fh!.fileDescriptor) } deinit { terminate_file_pack_context(&context) // if ownsChannel {close(context.fileDescriptor)} } } // MARK: ------------------------------ MessageUnpacker class CWUnpacker { let p: UnsafeMutablePointer<cw_unpack_context> var OK: Bool {p.pointee.return_code == CWP_RC_OK} init(_ p:UnsafeMutablePointer<cw_unpack_context>) { self.p = p } } class CWDataUnpacker: CWUnpacker { private var context = cw_unpack_context() private var buffer: [UInt8] init(from data: Data) { buffer = Array(repeating: UInt8(0), count: data.count) super.init(&context) data.copyBytes(to: &buffer, count: data.count) cw_unpack_context_init(&context, buffer, UInt(data.count), nil) } } class CWFileUnpacker: CWUnpacker { private var context = file_unpack_context() private let ownsChannel: Bool let fh: FileHandle? init(from descriptor:Int32) { ownsChannel = false fh = nil super.init(&context.uc) init_file_unpack_context(&context, 1024, descriptor) } init(from url:URL) throws { fh = try FileHandle(forReadingFrom: url) ownsChannel = true super.init(&context.uc) init_file_unpack_context(&context, 1024, fh!.fileDescriptor) } deinit { terminate_file_unpack_context(&context) // if ownsChannel {close(context.fileDescriptor)} } }
0a01a1de89bef9d3d27bb3484d899c50
25.081395
95
0.653143
false
false
false
false
Diuit/DUMessagingUIKit-iOS
refs/heads/develop
DUMessagingUIKit/DUMessageCellTextView.swift
mit
1
// // DUMessageCellTextView.swift // DUMessagingUIKit // // Created by Pofat Diuit on 2016/6/5. // Copyright © 2016年 duolC. All rights reserved. // import UIKit open class DUMessageCellTextView: UITextView { override open func awakeFromNib() { super.awakeFromNib() isEditable = false isSelectable = true isUserInteractionEnabled = true dataDetectorTypes = UIDataDetectorTypes() showsHorizontalScrollIndicator = false showsVerticalScrollIndicator = false isScrollEnabled = false backgroundColor = UIColor.clear textContainerInset = UIEdgeInsets.zero textContainer.lineFragmentPadding = 0 contentInset = UIEdgeInsets.zero scrollIndicatorInsets = UIEdgeInsets.zero contentOffset = CGPoint.zero let underline = NSUnderlineStyle.styleSingle.rawValue | NSUnderlineStyle.patternSolid.rawValue linkTextAttributes = [ NSForegroundColorAttributeName : GlobalUISettings.tintColor, NSUnderlineStyleAttributeName: underline] } override open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { // ignore double tap to prevent unrelevatn menu showing if let gr = gestureRecognizer as? UITapGestureRecognizer { if gr.numberOfTapsRequired == 2 { return false } } return true } }
da9ed516bd1b060f13685251737b602a
32.204545
103
0.673511
false
false
false
false
yanif/circator
refs/heads/master
MetabolicCompass/View Controller/Analysis/AnalysisViewController.swift
apache-2.0
1
// // AnalysisViewController.swift // MetabolicCompass // // Created by Artem Usachov on 8/10/16. // Copyright © 2016 Yanif Ahmad, Tom Woolf. All rights reserved. // import UIKit // Enums enum AnalysisType : Int { case Correlate = 0 case Fasting case OurStudy } class AnalysisViewController: UIViewController { var currentViewController: UIViewController? @IBOutlet weak var containerView: UIView! override func viewDidLoad() { let correlateController = UIStoryboard(name: "TabScreens", bundle: nil).instantiateViewControllerWithIdentifier("correlatePlaceholder") as! CorrelationChartsViewController self.addChildViewController(correlateController) correlateController.view.translatesAutoresizingMaskIntoConstraints = false self.addSubview(correlateController.view, toView: self.containerView) self.currentViewController = correlateController; super.viewDidLoad() } func switchToScatterPlotViewController() { let newViewController = UIStoryboard(name: "TabScreens", bundle: nil).instantiateViewControllerWithIdentifier("correlatePlaceholder") as! CorrelationChartsViewController newViewController.view.translatesAutoresizingMaskIntoConstraints = false cycleFromViewController(self.currentViewController!, toViewController: newViewController) self.currentViewController = newViewController; } func switchToFastingViewController() { let fastingViewController = UIStoryboard(name: "TabScreens", bundle: nil).instantiateViewControllerWithIdentifier("fastingController"); fastingViewController.view.translatesAutoresizingMaskIntoConstraints = false cycleFromViewController(self.currentViewController!, toViewController: fastingViewController); self.currentViewController = fastingViewController; } func switchToOurStudyViewController() { let ourStudyViewController = UIStoryboard(name: "TabScreens", bundle: nil).instantiateViewControllerWithIdentifier("ourStudyController"); ourStudyViewController.view.translatesAutoresizingMaskIntoConstraints = false cycleFromViewController(self.currentViewController!, toViewController: ourStudyViewController); self.currentViewController = ourStudyViewController; } @IBAction func segmentSelectedAction(segment: UISegmentedControl) { switch segment.selectedSegmentIndex { case AnalysisType.Correlate.rawValue: switchToScatterPlotViewController() case AnalysisType.OurStudy.rawValue: switchToOurStudyViewController() default://by default show fastings switchToFastingViewController() } } func cycleFromViewController(oldViewController: UIViewController, toViewController newViewController: UIViewController) { oldViewController.willMoveToParentViewController(nil) oldViewController.view.removeFromSuperview() oldViewController.removeFromParentViewController() self.addChildViewController(newViewController) self.addSubview(newViewController.view, toView:self.containerView!) newViewController.view.layoutIfNeeded() newViewController.didMoveToParentViewController(self) } func addSubview(subView:UIView, toView parentView:UIView) { parentView.addSubview(subView) var viewBindingsDict = [String: AnyObject]() viewBindingsDict["subView"] = subView parentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[subView]|", options: [], metrics: nil, views: viewBindingsDict)) parentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[subView]|", options: [], metrics: nil, views: viewBindingsDict)) } }
a0451abd314258ab12578b61ce9c7d2e
44.571429
179
0.750261
false
false
false
false
wvteijlingen/Spine
refs/heads/master
Spine/Serializing.swift
mit
1
// // Serializing.swift // Spine // // Created by Ward van Teijlingen on 23-08-14. // Copyright (c) 2014 Ward van Teijlingen. All rights reserved. // import Foundation /// Serializer (de)serializes according to the JSON:API specification. public class Serializer { /// The resource factory used for dispensing resources. fileprivate var resourceFactory = ResourceFactory() /// The transformers used for transforming to and from the serialized representation. fileprivate var valueFormatters = ValueFormatterRegistry.defaultRegistry() /// The key formatter used for formatting field names to keys. public var keyFormatter: KeyFormatter = AsIsKeyFormatter() public init() {} /// Deserializes the given data into a JSONAPIDocument. /// /// - parameter data: The data to deserialize. /// - parameter mappingTargets: Optional resources onto which data will be deserialized. /// /// - throws: SerializerError that can occur in the deserialization. /// /// - returns: A JSONAPIDocument public func deserializeData(_ data: Data, mappingTargets: [Resource]? = nil) throws -> JSONAPIDocument { let deserializeOperation = DeserializeOperation(data: data, resourceFactory: resourceFactory, valueFormatters: valueFormatters, keyFormatter: keyFormatter) if let mappingTargets = mappingTargets { deserializeOperation.addMappingTargets(mappingTargets) } deserializeOperation.start() switch deserializeOperation.result! { case .failure(let error): throw error case .success(let document): return document } } /// Serializes the given JSON:API document into NSData. Only the main data is serialized. /// /// - parameter document: The JSONAPIDocument to serialize. /// - parameter options: Serialization options to use. /// /// - throws: SerializerError that can occur in the serialization. /// /// - returns: Serialized data public func serializeDocument(_ document: JSONAPIDocument, options: SerializationOptions = [.IncludeID]) throws -> Data { let serializeOperation = SerializeOperation(document: document, valueFormatters: valueFormatters, keyFormatter: keyFormatter) serializeOperation.options = options serializeOperation.start() switch serializeOperation.result! { case .failure(let error): throw error case .success(let data): return data } } /// Serializes the given Resources into NSData. /// /// - parameter resources: The resources to serialize. /// - parameter options: The serialization options to use. /// /// - throws: SerializerError that can occur in the serialization. /// /// - returns: Serialized data. public func serializeResources(_ resources: [Resource], options: SerializationOptions = [.IncludeID]) throws -> Data { let document = JSONAPIDocument(data: resources, included: nil, errors: nil, meta: nil, links: nil, jsonapi: nil) return try serializeDocument(document, options: options) } /// Converts the given resource to link data, and serializes it into NSData. /// `{"data": { "type": "people", "id": "12" }}` /// /// If no resource is passed, `null` is used: /// `{ "data": null }` /// /// - parameter resource: The resource to serialize link data for. /// /// - throws: SerializerError that can occur in the serialization. /// /// - returns: Serialized data. public func serializeLinkData(_ resource: Resource?) throws -> Data { let payloadData: Any if let resource = resource { assert(resource.id != nil, "Attempt to convert resource without id to linkage. Only resources with ids can be converted to linkage.") payloadData = ["type": resource.resourceType, "id": resource.id!] } else { payloadData = NSNull() } do { return try JSONSerialization.data(withJSONObject: ["data": payloadData], options: JSONSerialization.WritingOptions(rawValue: 0)) } catch let error as NSError { throw SerializerError.jsonSerializationError(error) } } /// Converts the given resources to link data, and serializes it into NSData. /// ```json /// { /// "data": [ /// { "type": "comments", "id": "12" }, /// { "type": "comments", "id": "13" } /// ] /// } /// ``` /// /// - parameter resources: The resource to serialize link data for. /// /// - throws: SerializerError that can occur in the serialization. /// /// - returns: Serialized data. public func serializeLinkData(_ resources: [Resource]) throws -> Data { let payloadData: Any if resources.isEmpty { payloadData = [] } else { payloadData = resources.map { resource in return ["type": resource.resourceType, "id": resource.id!] } } do { return try JSONSerialization.data(withJSONObject: ["data": payloadData], options: JSONSerialization.WritingOptions(rawValue: 0)) } catch let error as NSError { throw SerializerError.jsonSerializationError(error) } } /// Registers a resource class. /// /// - parameter resourceClass: The resource class to register. public func registerResource(_ resourceClass: Resource.Type) { resourceFactory.registerResource(resourceClass) } /// Registers transformer `transformer`. /// /// - parameter transformer: The Transformer to register. public func registerValueFormatter<T: ValueFormatter>(_ formatter: T) { valueFormatters.registerFormatter(formatter) } } /// A JSONAPIDocument represents a JSON API document containing /// resources, errors, metadata, links and jsonapi data. public struct JSONAPIDocument { /// Primary resources extracted from the response. public var data: [Resource]? /// Included resources extracted from the response. public var included: [Resource]? /// Errors extracted from the response. public var errors: [APIError]? /// Metadata extracted from the reponse. public var meta: Metadata? /// Links extracted from the response. public var links: [String: URL]? /// JSONAPI information extracted from the response. public var jsonapi: JSONAPIData? } public struct SerializationOptions: OptionSet { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } /// Whether to include the resource ID in the serialized representation. public static let IncludeID = SerializationOptions(rawValue: 1 << 1) /// Whether to only serialize fields that are dirty. public static let DirtyFieldsOnly = SerializationOptions(rawValue: 1 << 2) /// Whether to include to-many linked resources in the serialized representation. public static let IncludeToMany = SerializationOptions(rawValue: 1 << 3) /// Whether to include to-one linked resources in the serialized representation. public static let IncludeToOne = SerializationOptions(rawValue: 1 << 4) /// If set, then attributes with null values will not be serialized. public static let OmitNullValues = SerializationOptions(rawValue: 1 << 5) }
08f214ae8231bc82c68175167ef5c461
32.816832
157
0.717904
false
false
false
false
rainedAllNight/RNScrollPageView
refs/heads/master
RNScrollPageView-Example/RNScrollPageView/HKCell.swift
mit
1
// // HKCell.swift // TableView // // Created by 罗伟 on 2017/5/15. // Copyright © 2017年 罗伟. All rights reserved. // import UIKit class HKCell: UITableViewCell { @IBOutlet weak var bgImageView: UIImageView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } func updateBgImageViewFrame() { let toWindowFrame = self.convert(self.bounds, to: self.window) let superViewCenter = self.superview!.center let cellOffSetY = toWindowFrame.midY - superViewCenter.y let ratio = cellOffSetY/self.superview!.frame.height let offSetY = -self.frame.height * ratio let transY = CGAffineTransform(translationX: 0, y: offSetY) self.bgImageView.transform = transY } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
2bea72b08d1e4040e95baf35d147c9e0
25.459459
70
0.650664
false
false
false
false
daniel-beard/2049
refs/heads/main
2049/Vector.swift
mit
1
// // Vector.swift // 2049 // // Created by Daniel Beard on 12/6/14. // Copyright (c) 2014 DanielBeard. All rights reserved. // import Foundation final class Vector { var x = 0 var y = 0 init(x: Int, y: Int) { self.x = x self.y = y } class func getVector(_ direction: Int) -> Vector { let map: [Int: Vector] = [ 0: Vector(x: 0, y: -1), // Up 1: Vector(x: 1, y: 0), // Right 2: Vector(x: 0, y: 1), // Down 3: Vector(x: -1, y: 0) // Left ] return map[direction]! } }
82006a18344dc46f8f6f8b0f7b8cd448
19.551724
56
0.466443
false
false
false
false
shhuangtwn/ProjectLynla
refs/heads/master
DataCollectionTool/RatingControl.swift
mit
1
// // RatingControl.swift // DataCollectionTool // // Created by Bryan Huang on 2016/11/3. // Copyright © 2016年 freelance. All rights reserved. // import UIKit class RatingControl: UIView { // MARK: Properties var rating = 3 { didSet { setNeedsLayout() } } var ratingButtons = [UIButton]() var spacing = 5 var stars = 5 // MARK: Initialization required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) let filledStarImage = UIImage(named: "starIcon24") let emptyStarImage = UIImage(named: "emptyStar") for _ in 0..<5 { let button = UIButton() button.setImage(emptyStarImage, forState: .Normal) button.setImage(filledStarImage, forState: .Selected) button.setImage(filledStarImage, forState: [.Highlighted, .Selected]) button.adjustsImageWhenHighlighted = false button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(_:)), forControlEvents: .TouchDown) ratingButtons += [button] addSubview(button) } } override func layoutSubviews() { // Set the button's width and height to a square the size of the frame's height. let buttonSize = Int(frame.size.height) var buttonFrame = CGRect(x: 0, y: 0, width: buttonSize, height: buttonSize) // Offset each button's origin by the length of the button plus spacing. for (index, button) in ratingButtons.enumerate() { buttonFrame.origin.x = CGFloat(index * (buttonSize + spacing)) button.frame = buttonFrame } updateButtonSelectionStates() } override func intrinsicContentSize() -> CGSize { let buttonSize = Int(frame.size.height) let width = (buttonSize + spacing) * stars return CGSize(width: width, height: buttonSize) } // MARK: Button Action func ratingButtonTapped(button: UIButton) { rating = ratingButtons.indexOf(button)! + 1 updateButtonSelectionStates() } func updateButtonSelectionStates() { for (index, button) in ratingButtons.enumerate() { // If the index of a button is less than the rating, that button should be selected. button.selected = index < rating } } }
d8586005d13462b213eec66c928539e4
29.9125
121
0.596442
false
false
false
false
noppoMan/aws-sdk-swift
refs/heads/main
Sources/Soto/Services/IoTThingsGraph/IoTThingsGraph_Error.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for IoTThingsGraph public struct IoTThingsGraphErrorType: AWSErrorType { enum Code: String { case internalFailureException = "InternalFailureException" case invalidRequestException = "InvalidRequestException" case limitExceededException = "LimitExceededException" case resourceAlreadyExistsException = "ResourceAlreadyExistsException" case resourceInUseException = "ResourceInUseException" case resourceNotFoundException = "ResourceNotFoundException" case throttlingException = "ThrottlingException" } private let error: Code public let context: AWSErrorContext? /// initialize IoTThingsGraph public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } public static var internalFailureException: Self { .init(.internalFailureException) } public static var invalidRequestException: Self { .init(.invalidRequestException) } public static var limitExceededException: Self { .init(.limitExceededException) } public static var resourceAlreadyExistsException: Self { .init(.resourceAlreadyExistsException) } public static var resourceInUseException: Self { .init(.resourceInUseException) } public static var resourceNotFoundException: Self { .init(.resourceNotFoundException) } public static var throttlingException: Self { .init(.throttlingException) } } extension IoTThingsGraphErrorType: Equatable { public static func == (lhs: IoTThingsGraphErrorType, rhs: IoTThingsGraphErrorType) -> Bool { lhs.error == rhs.error } } extension IoTThingsGraphErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
8039fbc30159cd2ec2ce819888fa567b
38.25
117
0.685275
false
false
false
false
ashfurrow/RxSwift
refs/heads/master
RxTests/RxSwiftTests/TestImplementations/Mocks/PrimitiveHotObservable.swift
mit
2
// // PrimitiveHotObservable.swift // RxTests // // Created by Krunoslav Zaher on 6/4/15. // // import Foundation import RxSwift let SubscribedToHotObservable = Subscription(0) let UnsunscribedFromHotObservable = Subscription(0, 0) class PrimitiveHotObservable<ElementType : Equatable> : ObservableType { typealias E = ElementType typealias Events = Recorded<E> typealias Observer = AnyObserver<E> var subscriptions: [Subscription] var observers: Bag<AnyObserver<E>> let lock = NSRecursiveLock() init() { self.subscriptions = [] self.observers = Bag() } func on(event: Event<E>) { lock.lock() defer { lock.unlock() } observers.on(event) } func subscribe<O : ObserverType where O.E == E>(observer: O) -> Disposable { lock.lock() defer { lock.unlock() } let key = observers.insert(AnyObserver(observer)) subscriptions.append(SubscribedToHotObservable) let i = self.subscriptions.count - 1 return AnonymousDisposable { self.lock.lock() defer { self.lock.unlock() } let removed = self.observers.removeKey(key) assert(removed != nil) self.subscriptions[i] = UnsunscribedFromHotObservable } } }
3147a148215733dbff05f343cd2ec3bf
22.982456
80
0.603511
false
false
false
false
ericmarkmartin/Nightscouter2
refs/heads/master
Common/Extensions/Double-Extension.swift
mit
1
// // ApplicationExtensions.swift // Nightscout // // Created by Peter Ina on 5/18/15. // Copyright (c) 2015 Peter Ina. All rights reserved. // import Foundation public extension Range { public var randomInt: Int { get { var offset = 0 if (startIndex as! Int) < 0 // allow negative ranges { offset = abs(startIndex as! Int) } let mini = UInt32(startIndex as! Int + offset) let maxi = UInt32(endIndex as! Int + offset) return Int(mini + arc4random_uniform(maxi - mini)) - offset } } } public extension MgdlValue { public var toMmol: Double { get{ return (self / 18) } } public var toMgdl: Double { get{ return floor(self * 18) } } internal var mgdlFormatter: NSNumberFormatter { let numberFormat = NSNumberFormatter() numberFormat.numberStyle = .NoStyle return numberFormat } public var formattedForMgdl: String { if let reserved = ReservedValues(mgdl: self) { return reserved.description } return self.mgdlFormatter.stringFromNumber(self)! } internal var mmolFormatter: NSNumberFormatter { let numberFormat = NSNumberFormatter() numberFormat.numberStyle = .DecimalStyle numberFormat.minimumFractionDigits = 1 numberFormat.maximumFractionDigits = 1 numberFormat.secondaryGroupingSize = 1 return numberFormat } public var formattedForMmol: String { if let reserved = ReservedValues(mgdl: self) { return reserved.description } return self.mmolFormatter.stringFromNumber(self.toMmol)! } } public extension MgdlValue { internal var bgDeltaFormatter: NSNumberFormatter { let numberFormat = NSNumberFormatter() numberFormat.numberStyle = .DecimalStyle numberFormat.positivePrefix = numberFormat.plusSign numberFormat.negativePrefix = numberFormat.minusSign return numberFormat } public func formattedBGDelta(forUnits units: Units, appendString: String? = nil) -> String { var formattedNumber: String = "" switch units { case .Mmol: let numberFormat = bgDeltaFormatter numberFormat.minimumFractionDigits = 1 numberFormat.maximumFractionDigits = 1 numberFormat.secondaryGroupingSize = 1 formattedNumber = numberFormat.stringFromNumber(self) ?? "?" case .Mgdl: formattedNumber = self.bgDeltaFormatter.stringFromNumber(self) ?? "?" } var unitMarker: String = units.description if let appendString = appendString { unitMarker = appendString } return formattedNumber + " " + unitMarker } public var formattedForBGDelta: String { return self.bgDeltaFormatter.stringFromNumber(self)! } } public extension Double { var isInteger: Bool { return rint(self) == self } } public extension Double { public func millisecondsToSecondsTimeInterval() -> NSTimeInterval { return round(self/1000) } public var inThePast: NSTimeInterval { return -self } public func toDateUsingMilliseconds() -> NSDate { let date = NSDate(timeIntervalSince1970:millisecondsToSecondsTimeInterval()) return date } } extension NSTimeInterval { var minuteSecondMS: String { return String(format:"%d:%02d.%03d", minute , second, millisecond ) } var minute: Double { return (self/60.0)%60 } var second: Double { return self % 60 } var millisecond: Double { return self*1000 } } extension Int { var msToSeconds: Double { return Double(self) / 1000 } }
db2af920be2fe62471f001e75ee34311
24.643312
96
0.599006
false
false
false
false
mikaelbo/MBFacebookImagePicker
refs/heads/master
MBFacebookImagePicker/Views/MBFacebookPickerEmptyView.swift
mit
1
// // MBFacebookPickerEmptyView.swift // FacebookImagePicker // // Copyright © 2017 Mikaelbo. All rights reserved. // import UIKit class MBFacebookPickerEmptyView: UIView { let titleLabel = UILabel() override init(frame: CGRect) { super.init(frame: frame) configureLabel() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configureLabel() } fileprivate func configureLabel() { titleLabel.numberOfLines = 2 let wantedSize = CGSize(width: 205, height: 40) titleLabel.textAlignment = .center titleLabel.frame = CGRect(x: (bounds.size.width - wantedSize.width) / 2, y: (bounds.size.height - wantedSize.height) / 2, width: wantedSize.width, height: wantedSize.height) titleLabel.font = UIFont.systemFont(ofSize: 15) titleLabel.textColor = UIColor(red: 85 / 255, green: 85 / 255, blue: 85 / 255, alpha: 0.5) titleLabel.autoresizingMask = [.flexibleTopMargin, .flexibleBottomMargin, .flexibleLeftMargin, .flexibleRightMargin] addSubview(titleLabel) } }
a6e124945f94a3bddabb9e5fcc82bd5a
32.025
98
0.561696
false
true
false
false
edwin123chen/NSData-GZIP
refs/heads/master
Sources/NSData+GZIP.swift
mit
2
// // NSData+GZIP.swift // // Version 1.1.0 /* The MIT License (MIT) © 2014-2015 1024jp <wolfrosch.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation private let CHUNK_SIZE : Int = 2 ^ 14 private let STREAM_SIZE : Int32 = Int32(sizeof(z_stream)) public extension NSData { /// Return gzip-compressed data object or nil. public func gzippedData() -> NSData? { if self.length == 0 { return NSData() } var stream = self.createZStream() var status : Int32 status = deflateInit2_(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY, ZLIB_VERSION, STREAM_SIZE) if status != Z_OK { if let errorMessage = String.fromCString(stream.msg) { println(String(format: "Compression failed: %@", errorMessage)) } return nil } var data = NSMutableData(length: CHUNK_SIZE)! while stream.avail_out == 0 { if Int(stream.total_out) >= data.length { data.length += CHUNK_SIZE } stream.next_out = UnsafeMutablePointer<Bytef>(data.mutableBytes).advancedBy(Int(stream.total_out)) stream.avail_out = uInt(data.length) - uInt(stream.total_out) deflate(&stream, Z_FINISH) } deflateEnd(&stream) data.length = Int(stream.total_out) return data } /// Return gzip-decompressed data object or nil. public func gunzippedData() -> NSData? { if self.length == 0 { return NSData() } var stream = self.createZStream() var status : Int32 status = inflateInit2_(&stream, 47, ZLIB_VERSION, STREAM_SIZE) if status != Z_OK { if let errorMessage = String.fromCString(stream.msg) { println(String(format: "Decompression failed: %@", errorMessage)) } return nil } var data = NSMutableData(length: self.length * 2)! do { if Int(stream.total_out) >= data.length { data.length += self.length / 2; } stream.next_out = UnsafeMutablePointer<Bytef>(data.mutableBytes).advancedBy(Int(stream.total_out)) stream.avail_out = uInt(data.length) - uInt(stream.total_out) status = inflate(&stream, Z_SYNC_FLUSH) } while status == Z_OK if inflateEnd(&stream) != Z_OK || status != Z_STREAM_END { if let errorMessage = String.fromCString(stream.msg) { println(String(format: "Decompression failed: %@", errorMessage)) } return nil } data.length = Int(stream.total_out) return data } private func createZStream() -> z_stream { return z_stream( next_in: UnsafeMutablePointer<Bytef>(self.bytes), avail_in: uint(self.length), total_in: 0, next_out: nil, avail_out: 0, total_out: 0, msg: nil, state: nil, zalloc: nil, zfree: nil, opaque: nil, data_type: 0, adler: 0, reserved: 0 ) } }
aee51fca8b434cbd796acfb36546670f
30.65
128
0.578199
false
false
false
false
JaSpa/swift
refs/heads/master
stdlib/private/SwiftReflectionTest/SwiftReflectionTest.swift
apache-2.0
22
//===--- SwiftReflectionTest.swift ----------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file provides infrastructure for introspecting type information in a // remote swift executable by swift-reflection-test, using pipes and a // request-response protocol to communicate with the test tool. // //===----------------------------------------------------------------------===// // FIXME: Make this work with Linux import MachO import Darwin let RequestInstanceKind = "k" let RequestInstanceAddress = "i" let RequestReflectionInfos = "r" let RequestReadBytes = "b" let RequestSymbolAddress = "s" let RequestStringLength = "l" let RequestDone = "d" let RequestPointerSize = "p" internal func debugLog(_ message: String) { #if DEBUG_LOG fputs("Child: \(message)\n", stderr) fflush(stderr) #endif } public enum InstanceKind : UInt8 { case None case Object case Existential case ErrorExistential case Closure } /// Represents a section in a loaded image in this process. internal struct Section { /// The absolute start address of the section's data in this address space. let startAddress: UnsafeRawPointer /// The size of the section in bytes. let size: UInt } /// Holds the addresses and sizes of sections related to reflection internal struct ReflectionInfo : Sequence { /// The name of the loaded image internal let imageName: String /// Reflection metadata sections internal let fieldmd: Section? internal let assocty: Section? internal let builtin: Section? internal let capture: Section? internal let typeref: Section? internal let reflstr: Section? internal func makeIterator() -> AnyIterator<Section?> { return AnyIterator([ fieldmd, assocty, builtin, capture, typeref, reflstr ].makeIterator()) } } #if arch(x86_64) || arch(arm64) typealias MachHeader = mach_header_64 #else typealias MachHeader = mach_header #endif /// Get the location and size of a section in a binary. /// /// - Parameter name: The name of the section /// - Parameter imageHeader: A pointer to the Mach header describing the /// image. /// - Returns: A `Section` containing the address and size, or `nil` if there /// is no section by the given name. internal func getSectionInfo(_ name: String, _ imageHeader: UnsafePointer<MachHeader>) -> Section? { debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") } var size: UInt = 0 let address = getsectiondata(imageHeader, "__TEXT", name, &size) guard let nonNullAddress = address else { return nil } guard size != 0 else { return nil } return Section(startAddress: nonNullAddress, size: size) } /// Get the Swift Reflection section locations for a loaded image. /// /// An image of interest must have the following sections in the __DATA /// segment: /// - __swift3_fieldmd /// - __swift3_assocty /// - __swift3_builtin /// - __swift3_capture /// - __swift3_typeref /// - __swift3_reflstr (optional, may have been stripped out) /// /// - Parameter i: The index of the loaded image as reported by Dyld. /// - Returns: A `ReflectionInfo` containing the locations of all of the /// needed sections, or `nil` if the image doesn't contain all of them. internal func getReflectionInfoForImage(atIndex i: UInt32) -> ReflectionInfo? { debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") } let header = unsafeBitCast(_dyld_get_image_header(i), to: UnsafePointer<MachHeader>.self) let imageName = _dyld_get_image_name(i)! let fieldmd = getSectionInfo("__swift3_fieldmd", header) let assocty = getSectionInfo("__swift3_assocty", header) let builtin = getSectionInfo("__swift3_builtin", header) let capture = getSectionInfo("__swift3_capture", header) let typeref = getSectionInfo("__swift3_typeref", header) let reflstr = getSectionInfo("__swift3_reflstr", header) return ReflectionInfo(imageName: String(validatingUTF8: imageName)!, fieldmd: fieldmd, assocty: assocty, builtin: builtin, capture: capture, typeref: typeref, reflstr: reflstr) } internal func sendBytes<T>(from address: UnsafePointer<T>, count: Int) { var source = address var bytesLeft = count debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") } while bytesLeft > 0 { let bytesWritten = fwrite(source, 1, bytesLeft, stdout) fflush(stdout) guard bytesWritten > 0 else { fatalError("Couldn't write to parent pipe") } bytesLeft -= bytesWritten source = source.advanced(by: bytesWritten) } } /// Send the address of an object to the parent. internal func sendAddress(of instance: AnyObject) { debugLog("BEGIN \(#function)") defer { debugLog("END \(#function)") } var address = Unmanaged.passUnretained(instance).toOpaque() sendBytes(from: &address, count: MemoryLayout<UInt>.size) } /// Send the `value`'s bits to the parent. internal func sendValue<T>(_ value: T) { debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") } var value = value sendBytes(from: &value, count: MemoryLayout<T>.size) } /// Read a word-sized unsigned integer from the parent. internal func readUInt() -> UInt { debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") } var value: UInt = 0 fread(&value, MemoryLayout<UInt>.size, 1, stdin) return value } /// Send all known `ReflectionInfo`s for all images loaded in the current /// process. internal func sendReflectionInfos() { debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") } let infos = (0..<_dyld_image_count()).flatMap(getReflectionInfoForImage) var numInfos = infos.count debugLog("\(numInfos) reflection info bundles.") precondition(numInfos >= 1) sendBytes(from: &numInfos, count: MemoryLayout<UInt>.size) for info in infos { debugLog("Sending info for \(info.imageName)") for section in info { sendValue(section?.startAddress) sendValue(section?.size ?? 0) } } } internal func printErrnoAndExit() { debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") } let errorCString = strerror(errno)! let message = String(validatingUTF8: errorCString)! + "\n" let bytes = Array(message.utf8) fwrite(bytes, 1, bytes.count, stderr) fflush(stderr) exit(EXIT_FAILURE) } /// Retrieve the address and count from the parent and send the bytes back. internal func sendBytes() { debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") } let address = readUInt() let count = Int(readUInt()) debugLog("Parent requested \(count) bytes from \(address)") var totalBytesWritten = 0 var pointer = UnsafeMutableRawPointer(bitPattern: address) while totalBytesWritten < count { let bytesWritten = Int(fwrite(pointer, 1, Int(count), stdout)) fflush(stdout) if bytesWritten == 0 { printErrnoAndExit() } totalBytesWritten += bytesWritten pointer = pointer?.advanced(by: bytesWritten) } } /// Send the address of a symbol loaded in this process. internal func sendSymbolAddress() { debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") } let name = readLine()! name.withCString { let handle = UnsafeMutableRawPointer(bitPattern: Int(-2))! let symbol = dlsym(handle, $0) let symbolAddress = unsafeBitCast(symbol, to: UInt.self) sendValue(symbolAddress) } } /// Send the length of a string to the parent. internal func sendStringLength() { debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") } let address = readUInt() let cString = UnsafePointer<CChar>(bitPattern: address)! let count = String(validatingUTF8: cString)!.utf8.count sendValue(count) } /// Send the size of this architecture's pointer type. internal func sendPointerSize() { debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") } let pointerSize = UInt8(MemoryLayout<UnsafeRawPointer>.size) sendValue(pointerSize) } /// Hold an `instance` and wait for the parent to query for information. /// /// This is the main "run loop" of the test harness. /// /// The parent will necessarily need to: /// - Get the addresses of all of the reflection sections for any swift dylibs /// that are loaded, where applicable. /// - Get the address of the `instance` /// - Get the pointer size of this process, which affects assumptions about the /// the layout of runtime structures with pointer-sized fields. /// - Read raw bytes out of this process's address space. /// /// The parent sends a Done message to indicate that it's done /// looking at this instance. It will continue to ask for instances, /// so call doneReflecting() when you don't have any more instances. internal func reflect(instanceAddress: UInt, kind: InstanceKind) { while let command = readLine(strippingNewline: true) { switch command { case String(validatingUTF8: RequestInstanceKind)!: sendValue(kind.rawValue) case String(validatingUTF8: RequestInstanceAddress)!: sendValue(instanceAddress) case String(validatingUTF8: RequestReflectionInfos)!: sendReflectionInfos() case String(validatingUTF8: RequestReadBytes)!: sendBytes() case String(validatingUTF8: RequestSymbolAddress)!: sendSymbolAddress() case String(validatingUTF8: RequestStringLength)!: sendStringLength() case String(validatingUTF8: RequestPointerSize)!: sendPointerSize() case String(validatingUTF8: RequestDone)!: return default: fatalError("Unknown request received: '\(Array(command.utf8))'!") } } } /// Reflect a class instance. /// /// This reflects the stored properties of the immediate class. /// The superclass is not (yet?) visited. public func reflect(object: AnyObject) { defer { _fixLifetime(object) } let address = Unmanaged.passUnretained(object).toOpaque() let addressValue = UInt(bitPattern: address) reflect(instanceAddress: addressValue, kind: .Object) } /// Reflect any type at all by boxing it into an existential container (an `Any`) /// /// Given a class, this will reflect the reference value, and not the contents /// of the instance. Use `reflect(object:)` for that. /// /// This function serves to exercise the projectExistential function of the /// SwiftRemoteMirror API. /// /// It tests the three conditions of existential layout: /// /// ## Class existentials /// /// For example, a `MyClass as Any`: /// ``` /// [Pointer to class instance] /// [Witness table 1] /// [Witness table 2] /// ... /// [Witness table n] /// ``` /// /// ## Existentials whose contained type fits in the 3-word buffer /// /// For example, a `(1, 2) as Any`: /// ``` /// [Tuple element 1: Int] /// [Tuple element 2: Int] /// [-Empty_] /// [Metadata Pointer] /// [Witness table 1] /// [Witness table 2] /// ... /// [Witness table n] /// ``` /// /// ## Existentials whose contained type has to be allocated into a /// heap buffer. /// /// For example, a `LargeStruct<T> as Any`: /// ``` /// [Pointer to unmanaged heap container] --> [Large struct] /// [-Empty-] /// [-Empty-] /// [Metadata Pointer] /// [Witness table 1] /// [Witness table 2] /// ... /// [Witness table n] /// ``` /// /// The test doesn't care about the witness tables - we only care /// about what's in the buffer, so we always put these values into /// an Any existential. public func reflect<T>(any: T) { let any: Any = any let anyPointer = UnsafeMutablePointer<Any>.allocate(capacity: MemoryLayout<Any>.size) anyPointer.initialize(to: any) let anyPointerValue = UInt(bitPattern: anyPointer) reflect(instanceAddress: anyPointerValue, kind: .Existential) anyPointer.deallocate(capacity: MemoryLayout<Any>.size) } // Reflect an `Error`, a.k.a. an "error existential". // // These are always boxed on the heap, with the following layout: // // - Word 0: Metadata Pointer // - Word 1: 2x 32-bit reference counts // // If Objective-C interop is available, an Error is also an // `NSError`, and so has: // // - Word 2: code (NSInteger) // - Word 3: domain (NSString *) // - Word 4: userInfo (NSDictionary *) // // Then, always follow: // // - Word 2 or 5: Instance type metadata pointer // - Word 3 or 6: Instance witness table for conforming // to `Swift.Error`. // // Following that is the instance that conforms to `Error`, // rounding up to its alignment. public func reflect<T: Error>(error: T) { let error: Error = error let errorPointerValue = unsafeBitCast(error, to: UInt.self) reflect(instanceAddress: errorPointerValue, kind: .ErrorExistential) } /// Wraps a thick function with arity 0. struct ThickFunction0 { var function: () -> Void } /// Wraps a thick function with arity 1. struct ThickFunction1 { var function: (Int) -> Void } /// Wraps a thick function with arity 2. struct ThickFunction2 { var function: (Int, String) -> Void } /// Wraps a thick function with arity 3. struct ThickFunction3 { var function: (Int, String, AnyObject?) -> Void } struct ThickFunctionParts { var function: UnsafeRawPointer var context: Optional<UnsafeRawPointer> } /// Reflect a closure context. The given function must be a Swift-native /// @convention(thick) function value. public func reflect(function: @escaping () -> Void) { let fn = UnsafeMutablePointer<ThickFunction0>.allocate( capacity: MemoryLayout<ThickFunction0>.size) fn.initialize(to: ThickFunction0(function: function)) let contextPointer = fn.withMemoryRebound( to: ThickFunctionParts.self, capacity: 1) { UInt(bitPattern: $0.pointee.context) } reflect(instanceAddress: contextPointer, kind: .Object) fn.deallocate(capacity: MemoryLayout<ThickFunction0>.size) } /// Reflect a closure context. The given function must be a Swift-native /// @convention(thick) function value. public func reflect(function: @escaping (Int) -> Void) { let fn = UnsafeMutablePointer<ThickFunction1>.allocate( capacity: MemoryLayout<ThickFunction1>.size) fn.initialize(to: ThickFunction1(function: function)) let contextPointer = fn.withMemoryRebound( to: ThickFunctionParts.self, capacity: 1) { UInt(bitPattern: $0.pointee.context) } reflect(instanceAddress: contextPointer, kind: .Object) fn.deallocate(capacity: MemoryLayout<ThickFunction1>.size) } /// Reflect a closure context. The given function must be a Swift-native /// @convention(thick) function value. public func reflect(function: @escaping (Int, String) -> Void) { let fn = UnsafeMutablePointer<ThickFunction2>.allocate( capacity: MemoryLayout<ThickFunction2>.size) fn.initialize(to: ThickFunction2(function: function)) let contextPointer = fn.withMemoryRebound( to: ThickFunctionParts.self, capacity: 1) { UInt(bitPattern: $0.pointee.context) } reflect(instanceAddress: contextPointer, kind: .Object) fn.deallocate(capacity: MemoryLayout<ThickFunction2>.size) } /// Reflect a closure context. The given function must be a Swift-native /// @convention(thick) function value. public func reflect(function: @escaping (Int, String, AnyObject?) -> Void) { let fn = UnsafeMutablePointer<ThickFunction3>.allocate( capacity: MemoryLayout<ThickFunction3>.size) fn.initialize(to: ThickFunction3(function: function)) let contextPointer = fn.withMemoryRebound( to: ThickFunctionParts.self, capacity: 1) { UInt(bitPattern: $0.pointee.context) } reflect(instanceAddress: contextPointer, kind: .Object) fn.deallocate(capacity: MemoryLayout<ThickFunction3>.size) } /// Call this function to indicate to the parent that there are /// no more instances to look at. public func doneReflecting() { reflect(instanceAddress: UInt(InstanceKind.None.rawValue), kind: .None) } /* Example usage public protocol P { associatedtype Index var startIndex: Index { get } } public struct Thing : P { public let startIndex = 1010 } public enum E<T: P> { case B(T) case C(T.Index) } public class A<T: P> : P { public let x: T? public let y: T.Index public let b = true public let t = (1, 1.0) private let type: NSObject.Type public let startIndex = 1010 public init(x: T) { self.x = x self.y = x.startIndex self.type = NSObject.self } } let instance = A(x: A(x: Thing())) reflect(A(x: Thing())) */
09b2e79488c9fed986fb24a556bf9700
30.796964
87
0.689205
false
false
false
false
jeevanRao7/Swift_Playgrounds
refs/heads/master
Swift Playgrounds/Design Patterns/Interpreter.playground/Contents.swift
mit
1
/* ********************************************* Interpreter Pattern Reference: http://www.oodesign.com/interpreter-pattern.html ********************************************* Problem Statement : SENTENCE: ((true * k) + h) GRAMMER : BooleanExp ::= Constant | Variable | OrExp | AndExp | NotExp AndExp ::= BooleanExp ’*’ BooleanExp OrExp ::= BooleanExp ’+’ BooleanExp NotExp ::= ’~’ BooleanExp Variable ::= [A-z][A-z]* Constant ::= ’true’ | ’false’ *********************************************/ //Protocol + Extension = Abstract class. protocol BooleanExpression { func interpret(ctx:Context) -> Bool; } extension BooleanExpression { func interpret(ctx:Context) -> Bool { assertionFailure("Expression must be implemented in Concrete Class") return false; } } //Context - Concrete Class public class Context { var hash:Dictionary<String, Bool> = Dictionary() public func lookUp(variable:Variable) -> Bool { return hash[variable.localVariable]! } public func assignValue(variable:Variable , value:Bool) { self.hash.updateValue(value, forKey: variable.localVariable) } } public class Constant : BooleanExpression { var booleanValue : Bool //Constructor init(booleanValue:Bool) { self.booleanValue = booleanValue; } //Concrete method public func interpret(ctx: Context) -> Bool { return self.booleanValue; } } public class Variable : BooleanExpression { var localVariable:String; //Constructor init(localVariable : String) { self.localVariable = localVariable; } public func interpret(ctx: Context) -> Bool{ return ctx.lookUp(variable:self); } } public class AndExpression : BooleanExpression { var leftExp:BooleanExpression; var rightExp:BooleanExpression; //constuctor init(leftExp:BooleanExpression, rightExp:BooleanExpression) { self.leftExp = leftExp; self.rightExp = rightExp; } public func interpret(ctx: Context) -> Bool { return (leftExp.interpret(ctx:ctx) && rightExp.interpret(ctx:ctx)) } } public class NotExpression : BooleanExpression { var exp:BooleanExpression; //constuctor init(exp:BooleanExpression) { self.exp = exp; } public func interpret(ctx: Context) -> Bool { return !(exp.interpret(ctx:ctx)) } } public class OrExpression : BooleanExpression { var leftExp:BooleanExpression; var rightExp:BooleanExpression; //constuctor init(leftExp:BooleanExpression, rightExp:BooleanExpression) { self.leftExp = leftExp; self.rightExp = rightExp; } public func interpret(ctx: Context) -> Bool { return (leftExp.interpret(ctx:ctx) || rightExp.interpret(ctx:ctx)) } } /********** Main **********/ let context = Context(); let exp1 = Constant.init(booleanValue: true); let exp2 = Variable.init(localVariable: "k"); let exp3 = Variable.init(localVariable: "h"); let exp4 = AndExpression.init(leftExp: exp1, rightExp: exp2); let finalExp = OrExpression.init(leftExp: exp4, rightExp: exp3); context.assignValue(variable: exp2 , value: false); context.assignValue(variable: exp3 , value: true); print("Final result of Expression : \(finalExp.interpret(ctx: context))") /* Simplified version let k = Variable.init(localVariable: "k"); let h = Variable.init(localVariable: "h"); let finalExp = AndExpression(leftExp: Constant.init(booleanValue: true), rightExp: OrExpression.init(leftExp: k, rightExp: h)) context.assignValue(variable: k, value: false) context.assignValue(variable: h, value: false) */
b6e12ac6ccfc16207999c22d6d4c8304
22.425926
127
0.627404
false
false
false
false
remirobert/Dotzu-Objective-c
refs/heads/master
Pods/Dotzu/Dotzu/LoggerNetwork.swift
mit
1
// // LoggerNetwork.swift // exampleWindow // // Created by Remi Robert on 24/01/2017. // Copyright © 2017 Remi Robert. All rights reserved. // import Foundation fileprivate var bodyValues = [String:Data]() extension NSMutableURLRequest { @objc class func httpBodyHackSwizzle() { let setHttpBody = class_getInstanceMethod(self, #selector(setter: NSMutableURLRequest.httpBody)) let httpBodyHackSetHttpBody = class_getInstanceMethod(self, #selector(self.httpBodyHackSetHttpBody(body:))) method_exchangeImplementations(setHttpBody, httpBodyHackSetHttpBody) } @objc func httpBodyHackSetHttpBody(body: NSData?) { let keyRequest = "\(hashValue)" guard let body = body, bodyValues[keyRequest] == nil else { return } bodyValues[keyRequest] = body as Data httpBodyHackSetHttpBody(body: body) } } class LoggerNetwork: URLProtocol { var connection: NSURLConnection? var sessionTask: URLSessionTask? var responseData: NSMutableData? var response: URLResponse? var newRequest: NSMutableURLRequest? var currentLog: LogRequest? let store = StoreManager<LogRequest>(store: .network) static let shared = LoggerNetwork() lazy var queue: OperationQueue = { var queue = OperationQueue() queue.name = "request.logger.queue" queue.maxConcurrentOperationCount = 1 return queue }() var session: URLSession? open class func register() { NSMutableURLRequest.httpBodyHackSwizzle() URLProtocol.registerClass(self) } open class func unregister() { URLProtocol.unregisterClass(self) } open override class func canInit(with request: URLRequest) -> Bool { if !LogsSettings.shared.network && self.property(forKey: "MyURLProtocolHandledKey", in: request) != nil { return false } return true } open override class func canonicalRequest(for request: URLRequest) -> URLRequest { return request } open override class func requestIsCacheEquivalent(_ reqA: URLRequest, to reqB: URLRequest) -> Bool { return super.requestIsCacheEquivalent(reqA, to: reqB) } open override func startLoading() { guard let req = (request as NSURLRequest).mutableCopy() as? NSMutableURLRequest, newRequest == nil else { return } LoggerNetwork.setProperty(true, forKey: "MyURLProtocolHandledKey", in: req) LoggerNetwork.setProperty(Date(), forKey: "MyURLProtocolDateKey", in: req) self.newRequest = req session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: queue) sessionTask = session?.dataTask(with: req as URLRequest) sessionTask?.resume() responseData = NSMutableData() currentLog = LogRequest(request: req) LogNotificationApp.newRequest.post(Void()) } open override func stopLoading() { sessionTask?.cancel() guard let log = currentLog else {return} let keyRequest = "\(newRequest?.hashValue ?? 0)" log.httpBody = bodyValues["\(keyRequest)"] bodyValues.removeValue(forKey: keyRequest) if let startDate = LoggerNetwork.property(forKey: "MyURLProtocolDateKey", in: newRequest! as URLRequest) as? Date { let difference = fabs(startDate.timeIntervalSinceNow) log.duration = difference } store.add(log: log) LogNotificationApp.stopRequest.post(Void()) } } extension LoggerNetwork: URLSessionDataDelegate, URLSessionTaskDelegate { public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { if let error = error { client?.urlProtocol(self, didFailWithError: error) let reason = (error as NSError).localizedDescription currentLog?.errorClientDescription = reason return } client?.urlProtocolDidFinishLoading(self) } public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { if let error = error { let error = (error as NSError).localizedDescription currentLog?.errorClientDescription = error return } } public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) completionHandler(.allow) currentLog?.initResponse(response: response) if let data = responseData { currentLog?.dataResponse = data as NSData } } public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { client?.urlProtocol(self, didLoad: data) responseData?.append(data) } }
ff79788427f118e9eda09f7d9e9202d3
34.454545
115
0.664103
false
false
false
false
adrfer/swift
refs/heads/master
stdlib/private/SwiftPrivatePthreadExtras/SwiftPrivatePthreadExtras.swift
apache-2.0
2
//===--- SwiftPrivatePthreadExtras.swift ----------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file contains wrappers for pthread APIs that are less painful to use // than the C APIs. // //===----------------------------------------------------------------------===// #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) import Darwin #elseif os(Linux) || os(FreeBSD) import Glibc #endif /// An abstract base class to encapsulate the context necessary to invoke /// a block from pthread_create. internal class PthreadBlockContext { /// Execute the block, and return an `UnsafeMutablePointer` to memory /// allocated with `UnsafeMutablePointer.alloc` containing the result of the /// block. func run() -> UnsafeMutablePointer<Void> { fatalError("abstract") } } internal class PthreadBlockContextImpl<Argument, Result>: PthreadBlockContext { let block: (Argument) -> Result let arg: Argument init(block: (Argument) -> Result, arg: Argument) { self.block = block self.arg = arg super.init() } override func run() -> UnsafeMutablePointer<Void> { let result = UnsafeMutablePointer<Result>.alloc(1) result.initialize(block(arg)) return UnsafeMutablePointer(result) } } /// Entry point for `pthread_create` that invokes a block context. internal func invokeBlockContext( contextAsVoidPointer: UnsafeMutablePointer<Void> ) -> UnsafeMutablePointer<Void> { // The context is passed in +1; we're responsible for releasing it. let contextAsOpaque = COpaquePointer(contextAsVoidPointer) let context = Unmanaged<PthreadBlockContext>.fromOpaque(contextAsOpaque) .takeRetainedValue() return context.run() } /// Block-based wrapper for `pthread_create`. public func _stdlib_pthread_create_block<Argument, Result>( attr: UnsafePointer<pthread_attr_t>, _ start_routine: (Argument) -> Result, _ arg: Argument ) -> (CInt, pthread_t?) { let context = PthreadBlockContextImpl(block: start_routine, arg: arg) // We hand ownership off to `invokeBlockContext` through its void context // argument. let contextAsOpaque = Unmanaged.passRetained(context) .toOpaque() let contextAsVoidPointer = UnsafeMutablePointer<Void>(contextAsOpaque) var threadID = pthread_t() let result = pthread_create(&threadID, attr, invokeBlockContext, contextAsVoidPointer) if result == 0 { return (result, threadID) } else { return (result, nil) } } /// Block-based wrapper for `pthread_join`. public func _stdlib_pthread_join<Result>( thread: pthread_t, _ resultType: Result.Type ) -> (CInt, Result?) { var threadResultPtr = UnsafeMutablePointer<Void>() let result = pthread_join(thread, &threadResultPtr) if result == 0 { let threadResult = UnsafeMutablePointer<Result>(threadResultPtr).memory threadResultPtr.destroy() threadResultPtr.dealloc(1) return (result, threadResult) } else { return (result, nil) } } public class _stdlib_Barrier { var _pthreadBarrier: _stdlib_pthread_barrier_t var _pthreadBarrierPtr: UnsafeMutablePointer<_stdlib_pthread_barrier_t> { return UnsafeMutablePointer(_getUnsafePointerToStoredProperties(self)) } public init(threadCount: Int) { self._pthreadBarrier = _stdlib_pthread_barrier_t() let ret = _stdlib_pthread_barrier_init( _pthreadBarrierPtr, nil, CUnsignedInt(threadCount)) if ret != 0 { fatalError("_stdlib_pthread_barrier_init() failed") } } deinit { _stdlib_pthread_barrier_destroy(_pthreadBarrierPtr) } public func wait() { let ret = _stdlib_pthread_barrier_wait(_pthreadBarrierPtr) if !(ret == 0 || ret == _stdlib_PTHREAD_BARRIER_SERIAL_THREAD) { fatalError("_stdlib_pthread_barrier_wait() failed") } } }
1f9a67650f33564b15bfcdddab2ae3e3
31.421875
80
0.681928
false
false
false
false
raulriera/Bike-Compass
refs/heads/master
App/Carthage/Checkouts/Alamofire/Tests/UploadTests.swift
mit
2
// // UploadTests.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Alamofire import Foundation import XCTest class UploadFileInitializationTestCase: BaseTestCase { func testUploadClassMethodWithMethodURLAndFile() { // Given let urlString = "https://httpbin.org/" let imageURL = URLForResource("rainbow", withExtension: "jpg") // When let request = Alamofire.upload(.POST, urlString, file: imageURL) // Then XCTAssertNotNil(request.request, "request should not be nil") XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST") XCTAssertEqual(request.request?.urlString ?? "", urlString, "request URL string should be equal") XCTAssertNil(request.response, "response should be nil") } func testUploadClassMethodWithMethodURLHeadersAndFile() { // Given let urlString = "https://httpbin.org/" let imageURL = URLForResource("rainbow", withExtension: "jpg") // When let request = Alamofire.upload(.POST, urlString, headers: ["Authorization": "123456"], file: imageURL) // Then XCTAssertNotNil(request.request, "request should not be nil") XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST") XCTAssertEqual(request.request?.urlString ?? "", urlString, "request URL string should be equal") let authorizationHeader = request.request?.value(forHTTPHeaderField: "Authorization") ?? "" XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect") XCTAssertNil(request.response, "response should be nil") } } // MARK: - class UploadDataInitializationTestCase: BaseTestCase { func testUploadClassMethodWithMethodURLAndData() { // Given let urlString = "https://httpbin.org/" // When let request = Alamofire.upload(.POST, urlString, data: Data()) // Then XCTAssertNotNil(request.request, "request should not be nil") XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST") XCTAssertEqual(request.request?.urlString ?? "", urlString, "request URL string should be equal") XCTAssertNil(request.response, "response should be nil") } func testUploadClassMethodWithMethodURLHeadersAndData() { // Given let urlString = "https://httpbin.org/" // When let request = Alamofire.upload(.POST, urlString, headers: ["Authorization": "123456"], data: Data()) // Then XCTAssertNotNil(request.request, "request should not be nil") XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST") XCTAssertEqual(request.request?.urlString ?? "", urlString, "request URL string should be equal") let authorizationHeader = request.request?.value(forHTTPHeaderField: "Authorization") ?? "" XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect") XCTAssertNil(request.response, "response should be nil") } } // MARK: - class UploadStreamInitializationTestCase: BaseTestCase { func testUploadClassMethodWithMethodURLAndStream() { // Given let urlString = "https://httpbin.org/" let imageURL = URLForResource("rainbow", withExtension: "jpg") let imageStream = InputStream(url: imageURL)! // When let request = Alamofire.upload(.POST, urlString, stream: imageStream) // Then XCTAssertNotNil(request.request, "request should not be nil") XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST") XCTAssertEqual(request.request?.urlString ?? "", urlString, "request URL string should be equal") XCTAssertNil(request.response, "response should be nil") } func testUploadClassMethodWithMethodURLHeadersAndStream() { // Given let urlString = "https://httpbin.org/" let imageURL = URLForResource("rainbow", withExtension: "jpg") let imageStream = InputStream(url: imageURL)! // When let request = Alamofire.upload(.POST, urlString, headers: ["Authorization": "123456"], stream: imageStream) // Then XCTAssertNotNil(request.request, "request should not be nil") XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST") XCTAssertEqual(request.request?.urlString ?? "", urlString, "request URL string should be equal") let authorizationHeader = request.request?.value(forHTTPHeaderField: "Authorization") ?? "" XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect") XCTAssertNil(request.response, "response should be nil") } } // MARK: - class UploadDataTestCase: BaseTestCase { func testUploadDataRequest() { // Given let urlString = "https://httpbin.org/post" let data = "Lorem ipsum dolor sit amet".data(using: String.Encoding.utf8, allowLossyConversion: false)! let expectation = self.expectation(withDescription: "Upload request should succeed: \(urlString)") var request: URLRequest? var response: HTTPURLResponse? var error: NSError? // When Alamofire.upload(.POST, urlString, data: data) .response { responseRequest, responseResponse, _, responseError in request = responseRequest response = responseResponse error = responseError expectation.fulfill() } waitForExpectations(withTimeout: timeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNil(error, "error should be nil") } func testUploadDataRequestWithProgress() { // Given let urlString = "https://httpbin.org/post" let data: Data = { var text = "" for _ in 1...3_000 { text += "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " } return text.data(using: String.Encoding.utf8, allowLossyConversion: false)! }() let expectation = self.expectation(withDescription: "Bytes upload progress should be reported: \(urlString)") var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = [] var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = [] var responseRequest: URLRequest? var responseResponse: HTTPURLResponse? var responseData: Data? var responseError: ErrorProtocol? // When let upload = Alamofire.upload(.POST, urlString, data: data) upload.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in let bytes = (bytes: bytesWritten, totalBytes: totalBytesWritten, totalBytesExpected: totalBytesExpectedToWrite) byteValues.append(bytes) let progress = ( completedUnitCount: upload.progress.completedUnitCount, totalUnitCount: upload.progress.totalUnitCount ) progressValues.append(progress) } upload.response { request, response, data, error in responseRequest = request responseResponse = response responseData = data responseError = error expectation.fulfill() } waitForExpectations(withTimeout: timeout, handler: nil) // Then XCTAssertNotNil(responseRequest, "response request should not be nil") XCTAssertNotNil(responseResponse, "response response should not be nil") XCTAssertNotNil(responseData, "response data should not be nil") XCTAssertNil(responseError, "response error should be nil") XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count") if byteValues.count == progressValues.count { for index in 0..<byteValues.count { let byteValue = byteValues[index] let progressValue = progressValues[index] XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0") XCTAssertEqual( byteValue.totalBytes, progressValue.completedUnitCount, "total bytes should be equal to completed unit count" ) XCTAssertEqual( byteValue.totalBytesExpected, progressValue.totalUnitCount, "total bytes expected should be equal to total unit count" ) } } if let lastByteValue = byteValues.last, lastProgressValue = progressValues.last { let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected) let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1) XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0") XCTAssertEqual( progressValueFractionalCompletion, 1.0, "progress value fractional completion should equal 1.0" ) } else { XCTFail("last item in bytesValues and progressValues should not be nil") } } } // MARK: - class UploadMultipartFormDataTestCase: BaseTestCase { // MARK: Tests func testThatUploadingMultipartFormDataSetsContentTypeHeader() { // Given let urlString = "https://httpbin.org/post" let uploadData = "upload_data".data(using: String.Encoding.utf8, allowLossyConversion: false)! let expectation = self.expectation(withDescription: "multipart form data upload should succeed") var formData: MultipartFormData? var request: URLRequest? var response: HTTPURLResponse? var data: Data? var error: NSError? // When Alamofire.upload( .POST, urlString, multipartFormData: { multipartFormData in multipartFormData.appendBodyPart(data: uploadData, name: "upload_data") formData = multipartFormData }, encodingCompletion: { result in switch result { case .success(let upload, _, _): upload.response { responseRequest, responseResponse, responseData, responseError in request = responseRequest response = responseResponse data = responseData error = responseError expectation.fulfill() } case .failure: expectation.fulfill() } } ) waitForExpectations(withTimeout: timeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNotNil(data, "data should not be nil") XCTAssertNil(error, "error should be nil") if let request = request, multipartFormData = formData, contentType = request.value(forHTTPHeaderField: "Content-Type") { XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match") } else { XCTFail("Content-Type header value should not be nil") } } func testThatUploadingMultipartFormDataSucceedsWithDefaultParameters() { // Given let urlString = "https://httpbin.org/post" let french = "français".data(using: String.Encoding.utf8, allowLossyConversion: false)! let japanese = "日本語".data(using: String.Encoding.utf8, allowLossyConversion: false)! let expectation = self.expectation(withDescription: "multipart form data upload should succeed") var request: URLRequest? var response: HTTPURLResponse? var data: Data? var error: NSError? // When Alamofire.upload( .POST, urlString, multipartFormData: { multipartFormData in multipartFormData.appendBodyPart(data: french, name: "french") multipartFormData.appendBodyPart(data: japanese, name: "japanese") }, encodingCompletion: { result in switch result { case .success(let upload, _, _): upload.response { responseRequest, responseResponse, responseData, responseError in request = responseRequest response = responseResponse data = responseData error = responseError expectation.fulfill() } case .failure: expectation.fulfill() } } ) waitForExpectations(withTimeout: timeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNotNil(data, "data should not be nil") XCTAssertNil(error, "error should be nil") } func testThatUploadingMultipartFormDataWhileStreamingFromMemoryMonitorsProgress() { executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: false) } func testThatUploadingMultipartFormDataWhileStreamingFromDiskMonitorsProgress() { executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: true) } func testThatUploadingMultipartFormDataBelowMemoryThresholdStreamsFromMemory() { // Given let urlString = "https://httpbin.org/post" let french = "français".data(using: String.Encoding.utf8, allowLossyConversion: false)! let japanese = "日本語".data(using: String.Encoding.utf8, allowLossyConversion: false)! let expectation = self.expectation(withDescription: "multipart form data upload should succeed") var streamingFromDisk: Bool? var streamFileURL: URL? // When Alamofire.upload( .POST, urlString, multipartFormData: { multipartFormData in multipartFormData.appendBodyPart(data: french, name: "french") multipartFormData.appendBodyPart(data: japanese, name: "japanese") }, encodingCompletion: { result in switch result { case let .success(upload, uploadStreamingFromDisk, uploadStreamFileURL): streamingFromDisk = uploadStreamingFromDisk streamFileURL = uploadStreamFileURL upload.response { _, _, _, _ in expectation.fulfill() } case .failure: expectation.fulfill() } } ) waitForExpectations(withTimeout: timeout, handler: nil) // Then XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil") XCTAssertNil(streamFileURL, "stream file URL should be nil") if let streamingFromDisk = streamingFromDisk { XCTAssertFalse(streamingFromDisk, "streaming from disk should be false") } } func testThatUploadingMultipartFormDataBelowMemoryThresholdSetsContentTypeHeader() { // Given let urlString = "https://httpbin.org/post" let uploadData = "upload data".data(using: String.Encoding.utf8, allowLossyConversion: false)! let expectation = self.expectation(withDescription: "multipart form data upload should succeed") var formData: MultipartFormData? var request: URLRequest? var streamingFromDisk: Bool? // When Alamofire.upload( .POST, urlString, multipartFormData: { multipartFormData in multipartFormData.appendBodyPart(data: uploadData, name: "upload_data") formData = multipartFormData }, encodingCompletion: { result in switch result { case let .success(upload, uploadStreamingFromDisk, _): streamingFromDisk = uploadStreamingFromDisk upload.response { responseRequest, _, _, _ in request = responseRequest expectation.fulfill() } case .failure: expectation.fulfill() } } ) waitForExpectations(withTimeout: timeout, handler: nil) // Then XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil") if let streamingFromDisk = streamingFromDisk { XCTAssertFalse(streamingFromDisk, "streaming from disk should be false") } if let request = request, multipartFormData = formData, contentType = request.value(forHTTPHeaderField: "Content-Type") { XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match") } else { XCTFail("Content-Type header value should not be nil") } } func testThatUploadingMultipartFormDataAboveMemoryThresholdStreamsFromDisk() { // Given let urlString = "https://httpbin.org/post" let french = "français".data(using: String.Encoding.utf8, allowLossyConversion: false)! let japanese = "日本語".data(using: String.Encoding.utf8, allowLossyConversion: false)! let expectation = self.expectation(withDescription: "multipart form data upload should succeed") var streamingFromDisk: Bool? var streamFileURL: URL? // When Alamofire.upload( .POST, urlString, multipartFormData: { multipartFormData in multipartFormData.appendBodyPart(data: french, name: "french") multipartFormData.appendBodyPart(data: japanese, name: "japanese") }, encodingMemoryThreshold: 0, encodingCompletion: { result in switch result { case let .success(upload, uploadStreamingFromDisk, uploadStreamFileURL): streamingFromDisk = uploadStreamingFromDisk streamFileURL = uploadStreamFileURL upload.response { _, _, _, _ in expectation.fulfill() } case .failure: expectation.fulfill() } } ) waitForExpectations(withTimeout: timeout, handler: nil) // Then XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil") XCTAssertNotNil(streamFileURL, "stream file URL should not be nil") if let streamingFromDisk = streamingFromDisk, streamFilePath = streamFileURL?.path { XCTAssertTrue(streamingFromDisk, "streaming from disk should be true") XCTAssertTrue( FileManager.default().fileExists(atPath: streamFilePath), "stream file path should exist" ) } } func testThatUploadingMultipartFormDataAboveMemoryThresholdSetsContentTypeHeader() { // Given let urlString = "https://httpbin.org/post" let uploadData = "upload data".data(using: String.Encoding.utf8, allowLossyConversion: false)! let expectation = self.expectation(withDescription: "multipart form data upload should succeed") var formData: MultipartFormData? var request: URLRequest? var streamingFromDisk: Bool? // When Alamofire.upload( .POST, urlString, multipartFormData: { multipartFormData in multipartFormData.appendBodyPart(data: uploadData, name: "upload_data") formData = multipartFormData }, encodingMemoryThreshold: 0, encodingCompletion: { result in switch result { case let .success(upload, uploadStreamingFromDisk, _): streamingFromDisk = uploadStreamingFromDisk upload.response { responseRequest, _, _, _ in request = responseRequest expectation.fulfill() } case .failure: expectation.fulfill() } } ) waitForExpectations(withTimeout: timeout, handler: nil) // Then XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil") if let streamingFromDisk = streamingFromDisk { XCTAssertTrue(streamingFromDisk, "streaming from disk should be true") } if let request = request, multipartFormData = formData, contentType = request.value(forHTTPHeaderField: "Content-Type") { XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match") } else { XCTFail("Content-Type header value should not be nil") } } // ⚠️ This test has been removed as a result of rdar://26870455 in Xcode 8 Seed 1 // func testThatUploadingMultipartFormDataOnBackgroundSessionWritesDataToFileToAvoidCrash() { // // Given // let manager: Manager = { // let identifier = "com.alamofire.uploadtests.\(UUID().uuidString)" // let configuration = URLSessionConfiguration.backgroundSessionConfigurationForAllPlatformsWithIdentifier(identifier) // // return Manager(configuration: configuration, serverTrustPolicyManager: nil) // }() // // let urlString = "https://httpbin.org/post" // let french = "français".data(using: String.Encoding.utf8, allowLossyConversion: false)! // let japanese = "日本語".data(using: String.Encoding.utf8, allowLossyConversion: false)! // // let expectation = self.expectation(withDescription: "multipart form data upload should succeed") // // var request: URLRequest? // var response: HTTPURLResponse? // var data: Data? // var error: NSError? // var streamingFromDisk: Bool? // // // When // manager.upload( // .POST, // urlString, // multipartFormData: { multipartFormData in // multipartFormData.appendBodyPart(data: french, name: "french") // multipartFormData.appendBodyPart(data: japanese, name: "japanese") // }, // encodingCompletion: { result in // switch result { // case let .success(upload, uploadStreamingFromDisk, _): // streamingFromDisk = uploadStreamingFromDisk // // upload.response { responseRequest, responseResponse, responseData, responseError in // request = responseRequest // response = responseResponse // data = responseData // error = responseError // // expectation.fulfill() // } // case .failure: // expectation.fulfill() // } // } // ) // // waitForExpectations(withTimeout: timeout, handler: nil) // // // Then // XCTAssertNotNil(request, "request should not be nil") // XCTAssertNotNil(response, "response should not be nil") // XCTAssertNotNil(data, "data should not be nil") // XCTAssertNil(error, "error should be nil") // // if let streamingFromDisk = streamingFromDisk { // XCTAssertTrue(streamingFromDisk, "streaming from disk should be true") // } else { // XCTFail("streaming from disk should not be nil") // } // } // MARK: Combined Test Execution private func executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: Bool) { // Given let urlString = "https://httpbin.org/post" let loremData1: Data = { var loremValues: [String] = [] for _ in 1...1_500 { loremValues.append("Lorem ipsum dolor sit amet, consectetur adipiscing elit.") } return loremValues.joined(separator: " ").data(using: String.Encoding.utf8, allowLossyConversion: false)! }() let loremData2: Data = { var loremValues: [String] = [] for _ in 1...1_500 { loremValues.append("Lorem ipsum dolor sit amet, nam no graeco recusabo appellantur.") } return loremValues.joined(separator: " ").data(using: String.Encoding.utf8, allowLossyConversion: false)! }() let expectation = self.expectation(withDescription: "multipart form data upload should succeed") var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = [] var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = [] var request: URLRequest? var response: HTTPURLResponse? var data: Data? var error: NSError? // When Alamofire.upload( .POST, urlString, multipartFormData: { multipartFormData in multipartFormData.appendBodyPart(data: loremData1, name: "lorem1") multipartFormData.appendBodyPart(data: loremData2, name: "lorem2") }, encodingMemoryThreshold: streamFromDisk ? 0 : 100_000_000, encodingCompletion: { result in switch result { case .success(let upload, _, _): upload.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in let bytes = ( bytes: bytesWritten, totalBytes: totalBytesWritten, totalBytesExpected: totalBytesExpectedToWrite ) byteValues.append(bytes) let progress = ( completedUnitCount: upload.progress.completedUnitCount, totalUnitCount: upload.progress.totalUnitCount ) progressValues.append(progress) } upload.response { responseRequest, responseResponse, responseData, responseError in request = responseRequest response = responseResponse data = responseData error = responseError expectation.fulfill() } case .failure: expectation.fulfill() } } ) waitForExpectations(withTimeout: timeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNotNil(data, "data should not be nil") XCTAssertNil(error, "error should be nil") XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count") if byteValues.count == progressValues.count { for index in 0..<byteValues.count { let byteValue = byteValues[index] let progressValue = progressValues[index] XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0") XCTAssertEqual( byteValue.totalBytes, progressValue.completedUnitCount, "total bytes should be equal to completed unit count" ) XCTAssertEqual( byteValue.totalBytesExpected, progressValue.totalUnitCount, "total bytes expected should be equal to total unit count" ) } } if let lastByteValue = byteValues.last, lastProgressValue = progressValues.last { let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected) let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1) XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0") XCTAssertEqual( progressValueFractionalCompletion, 1.0, "progress value fractional completion should equal 1.0" ) } else { XCTFail("last item in bytesValues and progressValues should not be nil") } } }
14974fee540a544f739b26b02ade9e80
38.957087
129
0.607772
false
false
false
false
benlangmuir/swift
refs/heads/master
test/SILGen/initializers.swift
apache-2.0
3
// RUN: %target-swift-emit-silgen -disable-objc-attr-requires-foundation-module -enable-objc-interop %s -module-name failable_initializers | %FileCheck %s // High-level tests that silgen properly emits code for failable and thorwing // initializers. //// // Structs with failable initializers //// protocol Pachyderm { init() } class Canary : Pachyderm { required init() {} } // <rdar://problem/20941576> SILGen crash: Failable struct init cannot delegate to another failable initializer struct TrivialFailableStruct { init?(blah: ()) { } init?(wibble: ()) { self.init(blah: wibble) } } struct FailableStruct { let x, y: Canary init(noFail: ()) { x = Canary() y = Canary() } init?(failBeforeInitialization: ()) { return nil } init?(failAfterPartialInitialization: ()) { x = Canary() return nil } init?(failAfterFullInitialization: ()) { x = Canary() y = Canary() return nil } init?(failAfterWholeObjectInitializationByAssignment: ()) { self = FailableStruct(noFail: ()) return nil } init?(failAfterWholeObjectInitializationByDelegation: ()) { self.init(noFail: ()) return nil } // Optional to optional init?(failDuringDelegation: ()) { self.init(failBeforeInitialization: ()) } // IUO to optional init!(failDuringDelegation2: ()) { self.init(failBeforeInitialization: ())! // unnecessary-but-correct '!' } // IUO to IUO init!(failDuringDelegation3: ()) { self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!' } // non-optional to optional init(failDuringDelegation4: ()) { self.init(failBeforeInitialization: ())! // necessary '!' } // non-optional to IUO init(failDuringDelegation5: ()) { self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!' } } extension FailableStruct { init?(failInExtension: ()) { self.init(failInExtension: failInExtension) } init?(assignInExtension: ()) { self = FailableStruct(noFail: ()) } } struct FailableAddrOnlyStruct<T : Pachyderm> { var x, y: T init(noFail: ()) { x = T() y = T() } init?(failBeforeInitialization: ()) { return nil } init?(failAfterPartialInitialization: ()) { x = T() return nil } init?(failAfterFullInitialization: ()) { x = T() y = T() return nil } init?(failAfterWholeObjectInitializationByAssignment: ()) { self = FailableAddrOnlyStruct(noFail: ()) return nil } init?(failAfterWholeObjectInitializationByDelegation: ()) { self.init(noFail: ()) return nil } // Optional to optional init?(failDuringDelegation: ()) { self.init(failBeforeInitialization: ()) } // IUO to optional init!(failDuringDelegation2: ()) { self.init(failBeforeInitialization: ())! // unnecessary-but-correct '!' } // non-optional to optional init(failDuringDelegation3: ()) { self.init(failBeforeInitialization: ())! // necessary '!' } // non-optional to IUO init(failDuringDelegation4: ()) { self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!' } } extension FailableAddrOnlyStruct { init?(failInExtension: ()) { self.init(failBeforeInitialization: failInExtension) } init?(assignInExtension: ()) { self = FailableAddrOnlyStruct(noFail: ()) } } //// // Structs with throwing initializers //// func unwrap(_ x: Int) throws -> Int { return x } struct ThrowStruct { var x: Canary init(throws: ()) throws { x = Canary() } init(noThrows: ()) { x = Canary() } init(throwsBeforeDelegation: Int) throws { try unwrap(throwsBeforeDelegation) self.init(noThrows: ()) } init(throwsBeforeOrDuringDelegation: Int) throws { try unwrap(throwsBeforeOrDuringDelegation) try self.init(throws: ()) } init(throwsBeforeOrDuringDelegation2: Int) throws { try self.init(throwsBeforeDelegation: unwrap(throwsBeforeOrDuringDelegation2)) } init(throwsDuringDelegation: Int) throws { try self.init(throws: ()) } init(throwsAfterDelegation: Int) throws { self.init(noThrows: ()) try unwrap(throwsAfterDelegation) } init(throwsDuringOrAfterDelegation: Int) throws { try self.init(throws: ()) try unwrap(throwsDuringOrAfterDelegation) } init(throwsBeforeOrAfterDelegation: Int) throws { try unwrap(throwsBeforeOrAfterDelegation) self.init(noThrows: ()) try unwrap(throwsBeforeOrAfterDelegation) } init(throwsBeforeSelfReplacement: Int) throws { try unwrap(throwsBeforeSelfReplacement) self = ThrowStruct(noThrows: ()) } init(throwsDuringSelfReplacement: Int) throws { try self = ThrowStruct(throws: ()) } init(throwsAfterSelfReplacement: Int) throws { self = ThrowStruct(noThrows: ()) try unwrap(throwsAfterSelfReplacement) } init(nonFailable: ()) { try! self.init(throws: ()) } init(nonFailable2: ()) throws { self.init(failable: ())! } init?(failableAndThrows: ()) throws { self.init(noThrows: ()) } // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers11ThrowStructV0A0ACSgyt_tcfC // CHECK: bb0([[SELF_META:%[0-9]+]] : $@thin ThrowStruct.Type): // CHECK: [[DELEG_INIT:%[0-9]+]] = function_ref @$s21failable_initializers11ThrowStructV6throwsACyt_tKcfC // CHECK-NEXT: try_apply [[DELEG_INIT]]([[SELF_META]]) : $@convention(method) (@thin ThrowStruct.Type) -> (@owned ThrowStruct, @error any Error), normal [[SUCC_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]] // // CHECK: [[SUCC_BB]]([[RESULT:%[0-9]+]] : @owned $ThrowStruct): // CHECK-NEXT: [[INJECT_INTO_OPT:%[0-9]+]] = enum $Optional<ThrowStruct>, #Optional.some!enumelt, [[RESULT]] // CHECK-NEXT: br bb2([[INJECT_INTO_OPT]] : $Optional<ThrowStruct>) // // CHECK: bb2([[OPT_RESULT:%[0-9]+]] : @owned $Optional<ThrowStruct>): // CHECK: [[SELECT:%[0-9]+]] = select_enum [[OPT_RESULT]] // CHECK-NEXT: cond_br [[SELECT]], [[SOME_BB:bb[0-9]+]], [[NONE_BB:bb[0-9]+]] // // CHECK: [[NONE_BB]]: // CHECK-NEXT: destroy_value [[OPT_RESULT]] // CHECK-NEXT: br bb5 // // CHECK: [[SOME_BB]]: // CHECK-NEXT: [[RESULT:%[0-9]+]] = unchecked_enum_data [[OPT_RESULT]] : {{.*}}, #Optional.some!enumelt // CHECK-NEXT: assign [[RESULT]] to [[DEST:%[0-9]+]] // CHECK-NEXT: [[RESULT_CP:%[0-9]+]] = load [copy] [[DEST]] // CHECK-NEXT: [[INJECT_INTO_OPT:%[0-9]+]] = enum $Optional<ThrowStruct>, #Optional.some!enumelt, [[RESULT_CP]] // CHECK: br bb6([[INJECT_INTO_OPT]] : $Optional<ThrowStruct>) // // CHECK: bb5: // CHECK: [[NIL:%[0-9]+]] = enum $Optional<ThrowStruct>, #Optional.none!enumelt // CHECK-NEXT: br bb6([[NIL]] : $Optional<ThrowStruct>) // // CHECK: bb6([[RET:%[0-9]+]] : @owned $Optional<ThrowStruct>): // CHECK-NEXT: return [[RET]] // // CHECK: bb7([[ERR:%[0-9]+]] : @owned $any Error): // CHECK-NEXT: destroy_value [[ERR]] // CHECK-NEXT: [[NIL:%[0-9]+]] = enum $Optional<ThrowStruct>, #Optional.none!enumelt // CHECK-NEXT: br bb2([[NIL]] : $Optional<ThrowStruct>) // // CHECK: [[ERROR_BB]]([[ERR:%[0-9]+]] : @owned $any Error): // CHECK-NEXT: br bb7([[ERR]] : $any Error) // CHECK-NEXT: } init?(failable: ()) { try? self.init(throws: ()) } // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers11ThrowStructV9failable2ACSgyt_tcfC // CHECK: bb0([[SELF_META:%[0-9]+]] : $@thin ThrowStruct.Type): // CHECK: [[DELEG_INIT:%[0-9]+]] = function_ref @$s21failable_initializers11ThrowStructV0A9AndThrowsACSgyt_tKcfC // CHECK-NEXT: try_apply [[DELEG_INIT]]([[SELF_META]]) : $@convention(method) (@thin ThrowStruct.Type) -> (@owned Optional<ThrowStruct>, @error any Error), normal [[SUCC_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]] // // CHECK: [[SUCC_BB]]([[OPT_RESULT:%[0-9]+]] : @owned $Optional<ThrowStruct>): // CHECK: [[SELECT:%[0-9]+]] = select_enum [[OPT_RESULT]] // CHECK-NEXT: cond_br [[SELECT]], [[SOME_BB:bb[0-9]+]], [[NONE_BB:bb[0-9]+]] // // CHECK: [[NONE_BB]]: // CHECK-NEXT: destroy_value [[OPT_RESULT]] // CHECK-NEXT: br bb4 // // CHECK: [[SOME_BB]]: // CHECK-NEXT: [[RESULT:%[0-9]+]] = unchecked_enum_data [[OPT_RESULT]] : $Optional<ThrowStruct>, #Optional.some!enumelt // CHECK-NEXT: assign [[RESULT]] to [[DEST:%[0-9]+]] // CHECK-NEXT: [[RESULT_CP:%[0-9]+]] = load [copy] [[DEST]] // CHECK-NEXT: [[INJECT_INTO_OPT:%[0-9]+]] = enum $Optional<ThrowStruct>, #Optional.some!enumelt, [[RESULT_CP]] // CHECK: br bb5([[INJECT_INTO_OPT]] : $Optional<ThrowStruct>) // // CHECK: bb4: // CHECK: [[NIL:%[0-9]+]] = enum $Optional<ThrowStruct>, #Optional.none!enumelt // CHECK-NEXT: br bb5([[NIL]] : $Optional<ThrowStruct>) // // CHECK: bb5([[RET:%[0-9]+]] : @owned $Optional<ThrowStruct>): // CHECK-NEXT: return [[RET]] // // CHECK: bb6([[ERR:%[0-9]+]] : @owned $any Error): // CHECK: unreachable // // CHECK: [[ERROR_BB]]([[ERR:%[0-9]+]] : @owned $any Error): // CHECK-NEXT: br bb6([[ERR]] : $any Error) // CHECK-NEXT: } init?(failable2: ()) { try! self.init(failableAndThrows: ()) } init?(failable3: ()) { try? self.init(failableAndThrows: ())! } // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers11ThrowStructV9failable4ACSgyt_tcfC // CHECK: bb0([[SELF_META:%[0-9]+]] : $@thin ThrowStruct.Type): // CHECK: [[DELEG_INIT:%[0-9]+]] = function_ref @$s21failable_initializers11ThrowStructV0A9AndThrowsACSgyt_tKcfC // CHECK-NEXT: try_apply [[DELEG_INIT]]([[SELF_META]]) : $@convention(method) (@thin ThrowStruct.Type) -> (@owned Optional<ThrowStruct>, @error any Error), normal [[SUCC_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]] // // CHECK: [[SUCC_BB]]([[OPT_RESULT:%[0-9]+]] : @owned $Optional<ThrowStruct>): // CHECK-NEXT: [[INJECT_INTO_OPT:%[0-9]+]] = enum {{.*}}, #Optional.some!enumelt, [[OPT_RESULT]] // CHECK-NEXT: br bb2([[INJECT_INTO_OPT]] : $Optional<Optional<ThrowStruct>>) // // CHECK: bb2([[OPT_OPT_RESULT:%[0-9]+]] : @owned $Optional<Optional<ThrowStruct>>): // CHECK-NEXT: switch_enum [[OPT_OPT_RESULT]] : {{.*}}, case #Optional.some!enumelt: [[OPT_OPT_SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[OPT_OPT_NONE_BB:bb[0-9]+]] // // CHECK: [[OPT_OPT_SOME_BB]]([[OPT_RESULT:%[0-9]+]] : @owned $Optional<ThrowStruct>): // CHECK-NEXT: br bb5([[OPT_RESULT]] : $Optional<ThrowStruct>) // // CHECK: [[OPT_OPT_NONE_BB]]: // CHECK-NEXT: [[NIL:%[0-9]+]] = enum $Optional<ThrowStruct>, #Optional.none!enumelt // CHECK-NEXT: br bb5([[NIL]] : $Optional<ThrowStruct>) // // CHECK: bb5([[OPT_RESULT:%[0-9]+]] : @owned $Optional<ThrowStruct>): // CHECK: [[SELECT:%[0-9]+]] = select_enum [[OPT_RESULT]] // CHECK-NEXT: cond_br [[SELECT]], [[OPT_SOME_BB:bb[0-9]+]], [[OPT_NONE_BB:bb[0-9]+]] // // CHECK: [[OPT_NONE_BB]]: // CHECK-NEXT: destroy_value [[OPT_RESULT]] // CHECK-NEXT: br bb8 // // CHECK: [[OPT_SOME_BB]]: // CHECK-NEXT: [[RESULT:%[0-9]+]] = unchecked_enum_data [[OPT_RESULT]] : {{.*}}, #Optional.some!enumelt // CHECK-NEXT: assign [[RESULT]] to [[DEST:%[0-9]+]] // CHECK-NEXT: [[RESULT_CP:%[0-9]+]] = load [copy] [[DEST]] // CHECK-NEXT: [[INJECT_INTO_OPT:%[0-9]+]] = enum $Optional<ThrowStruct>, #Optional.some!enumelt, [[RESULT_CP]] // CHECK: br bb9([[INJECT_INTO_OPT]] : $Optional<ThrowStruct>) // // CHECK: bb8: // CHECK: [[NIL:%[0-9]+]] = enum $Optional<ThrowStruct>, #Optional.none!enumelt // CHECK-NEXT: br bb9([[NIL]] : $Optional<ThrowStruct>) // // CHECK: bb9([[RET:%[0-9]+]] : @owned $Optional<ThrowStruct>): // CHECK-NEXT: return [[RET]] // // CHECK: bb10([[ERR:%[0-9]+]] : @owned $any Error): // CHECK-NEXT: destroy_value [[ERR]] // CHECK-NEXT: [[NIL:%[0-9]+]] = enum $Optional<Optional<ThrowStruct>>, #Optional.none!enumelt // CHECK-NEXT: br bb2([[NIL]] : $Optional<Optional<ThrowStruct>>) // // CHECK: [[ERROR_BB]]([[ERR:%[0-9]+]] : @owned $any Error): // CHECK-NEXT: br bb10([[ERR]] : $any Error) // CHECK-NEXT: } init?(failable4: ()) { try? self.init(failableAndThrows: ()) } } extension ThrowStruct { init(throwsInExtension: ()) throws { try self.init(throws: throwsInExtension) } init(assignInExtension: ()) throws { try self = ThrowStruct(throws: ()) } } struct ThrowAddrOnlyStruct<T : Pachyderm> { var x : T init(fail: ()) throws { x = T() } init(noFail: ()) { x = T() } init(failBeforeDelegation: Int) throws { try unwrap(failBeforeDelegation) self.init(noFail: ()) } init(failBeforeOrDuringDelegation: Int) throws { try unwrap(failBeforeOrDuringDelegation) try self.init(fail: ()) } init(failBeforeOrDuringDelegation2: Int) throws { try self.init(failBeforeDelegation: unwrap(failBeforeOrDuringDelegation2)) } init(failDuringDelegation: Int) throws { try self.init(fail: ()) } init(failAfterDelegation: Int) throws { self.init(noFail: ()) try unwrap(failAfterDelegation) } init(failDuringOrAfterDelegation: Int) throws { try self.init(fail: ()) try unwrap(failDuringOrAfterDelegation) } init(failBeforeOrAfterDelegation: Int) throws { try unwrap(failBeforeOrAfterDelegation) self.init(noFail: ()) try unwrap(failBeforeOrAfterDelegation) } init?(throwsToOptional: Int) { try? self.init(failDuringDelegation: throwsToOptional) } init(throwsToIUO: Int) { try! self.init(failDuringDelegation: throwsToIUO) } init?(throwsToOptionalThrows: Int) throws { try? self.init(fail: ()) } init(throwsOptionalToThrows: Int) throws { self.init(throwsToOptional: throwsOptionalToThrows)! } init?(throwsOptionalToOptional: Int) { try! self.init(throwsOptionalToThrows: throwsOptionalToOptional) } init(failBeforeSelfReplacement: Int) throws { try unwrap(failBeforeSelfReplacement) self = ThrowAddrOnlyStruct(noFail: ()) } init(failAfterSelfReplacement: Int) throws { self = ThrowAddrOnlyStruct(noFail: ()) try unwrap(failAfterSelfReplacement) } } extension ThrowAddrOnlyStruct { init(failInExtension: ()) throws { try self.init(fail: failInExtension) } init(assignInExtension: ()) throws { self = ThrowAddrOnlyStruct(noFail: ()) } } //// // Classes //// //// // Classes with failable initializers //// class FailableBaseClass { var member: Canary init(noFail: ()) { member = Canary() } init?(failBeforeFullInitialization: ()) { return nil } init?(failAfterFullInitialization: ()) { member = Canary() return nil } convenience init?(failBeforeDelegation: ()) { return nil } // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers17FailableBaseClassC19failAfterDelegationACSgyt_tcfC // CHECK: bb0([[SELF_META:%.*]] : $@thick FailableBaseClass.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var FailableBaseClass }, let, name "self" // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[SELF_LIFETIME:%.*]] = begin_borrow [lexical] [[MARKED_SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[SELF_LIFETIME]] // CHECK: [[NEW_SELF:%.*]] = apply {{.*}}([[SELF_META]]) // CHECK: destroy_value [[MARKED_SELF_BOX]] // CHECK: [[RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt // CHECK: br bb2([[RESULT]] : $Optional<FailableBaseClass>) // CHECK: bb2([[RESULT:%.*]] : @owned $Optional<FailableBaseClass>): // CHECK: return [[RESULT]] // CHECK-NEXT: } convenience init?(failAfterDelegation: ()) { self.init(noFail: ()) return nil } // Optional to optional // // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers17FailableBaseClassC20failDuringDelegationACSgyt_tcfC // CHECK: bb0([[SELF_META:%.*]] : $@thick FailableBaseClass.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var FailableBaseClass }, let, name "self" // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[SELF_LIFETIME:%.*]] = begin_borrow [lexical] [[MARKED_SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[SELF_LIFETIME]] // CHECK: [[NEW_SELF:%.*]] = apply {{.*}}([[SELF_META]]) // CHECK: cond_br {{.*}}, [[SUCC_BB:bb[0-9]+]], [[FAIL_BB:bb[0-9]+]] // // CHECK: [[FAIL_BB:bb[0-9]+]]: // CHECK: destroy_value [[NEW_SELF]] // CHECK: br [[FAIL_EPILOG_BB:bb[0-9]+]] // // CHECK: [[SUCC_BB]]: // CHECK: [[UNWRAPPED_NEW_SELF:%.*]] = unchecked_enum_data [[NEW_SELF]] : $Optional<FailableBaseClass>, #Optional.some!enumelt // CHECK: assign [[UNWRAPPED_NEW_SELF]] to [[PB_BOX]] // CHECK: [[RESULT:%.*]] = load [copy] [[PB_BOX]] // CHECK: [[WRAPPED_RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.some!enumelt, [[RESULT]] // CHECK: destroy_value [[MARKED_SELF_BOX]] // CHECK: br [[EPILOG_BB:bb[0-9]+]]([[WRAPPED_RESULT]] // // CHECK: [[FAIL_EPILOG_BB]]: // CHECK: destroy_value [[MARKED_SELF_BOX]] // CHECK: [[WRAPPED_RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt // CHECK: br [[EPILOG_BB]]([[WRAPPED_RESULT]] // // CHECK: [[EPILOG_BB]]([[WRAPPED_RESULT:%.*]] : @owned $Optional<FailableBaseClass>): // CHECK: return [[WRAPPED_RESULT]] convenience init?(failDuringDelegation: ()) { self.init(failBeforeFullInitialization: ()) } // IUO to optional // // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers17FailableBaseClassC21failDuringDelegation2ACSgyt_tcfC // CHECK: bb0([[SELF_META:%.*]] : $@thick FailableBaseClass.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var FailableBaseClass }, let, name "self" // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[SELF_LIFETIME:%.*]] = begin_borrow [lexical] [[MARKED_SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[SELF_LIFETIME]] // CHECK: [[NEW_SELF:%.*]] = apply {{.*}}([[SELF_META]]) // CHECK: switch_enum [[NEW_SELF]] : $Optional<FailableBaseClass>, case #Optional.some!enumelt: [[SUCC_BB:bb[0-9]+]], case #Optional.none!enumelt: [[FAIL_BB:bb[0-9]+]] // // CHECK: [[FAIL_BB]]: // CHECK: unreachable // // CHECK: [[SUCC_BB]]([[RESULT:%.*]] : @owned $FailableBaseClass): // CHECK: assign [[RESULT]] to [[PB_BOX]] // CHECK: [[RESULT:%.*]] = load [copy] [[PB_BOX]] // CHECK: [[WRAPPED_RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.some!enumelt, [[RESULT]] : $FailableBaseClass // CHECK: destroy_value [[MARKED_SELF_BOX]] // CHECK: br [[EPILOG_BB:bb[0-9]+]]([[WRAPPED_RESULT]] // // CHECK: [[EPILOG_BB]]([[WRAPPED_RESULT:%.*]] : @owned $Optional<FailableBaseClass>): // CHECK: return [[WRAPPED_RESULT]] // CHECK-NEXT: } convenience init!(failDuringDelegation2: ()) { self.init(failBeforeFullInitialization: ())! // unnecessary-but-correct '!' } // Optional to non-optional // // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers17FailableBaseClassC21failDuringDelegation3ACSgyt_tcfC // CHECK: bb0([[SELF_META:%[0-9]+]] : $@thick FailableBaseClass.Type): // CHECK-NEXT: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var FailableBaseClass }, let, name "self" // CHECK-NEXT: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK-NEXT: [[SELF_LIFETIME:%[0-9]+]] = begin_borrow [lexical] [[MARKED_SELF_BOX]] // CHECK-NEXT: [[PB_BOX:%[0-9]+]] = project_box [[SELF_LIFETIME]] // CHECK: [[DELEG_INIT:%[0-9]+]] = class_method [[SELF_META]] : $@thick FailableBaseClass.Type, #FailableBaseClass.init!allocator // CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[DELEG_INIT]]([[SELF_META]]) // CHECK-NEXT: assign [[RESULT]] to [[PB_BOX]] // CHECK-NEXT: [[RESULT_COPY:%[0-9]+]] = load [copy] [[PB_BOX]] // CHECK-NEXT: [[INJECT_INTO_OPT:%[0-9]+]] = enum $Optional<FailableBaseClass>, #Optional.some!enumelt, [[RESULT_COPY]] // CHECK-NEXT: end_borrow [[SELF_LIFETIME]] // CHECK-NEXT: destroy_value [[MARKED_SELF_BOX]] // CHECK-NEXT: br bb2([[INJECT_INTO_OPT]] : $Optional<FailableBaseClass>) // // FIXME: Dead block // CHECK: bb1: // // CHECK: bb2([[ARG:%[0-9]+]] : @owned $Optional<FailableBaseClass>): // CHECK-NEXT: return [[ARG]] // CHECK-NEXT: } convenience init?(failDuringDelegation3: ()) { self.init(noFail: ()) } // IUO to IUO convenience init!(noFailDuringDelegation: ()) { self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!' } // non-optional to optional convenience init(noFailDuringDelegation2: ()) { self.init(failBeforeFullInitialization: ())! // necessary '!' } } extension FailableBaseClass { convenience init?(failInExtension: ()) throws { self.init(failBeforeFullInitialization: failInExtension) } } // Chaining to failable initializers in a superclass class FailableDerivedClass : FailableBaseClass { var otherMember: Canary // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers20FailableDerivedClassC27derivedFailBeforeDelegationACSgyt_tcfc : $@convention(method) (@owned FailableDerivedClass) -> @owned Optional<FailableDerivedClass> { // CHECK: bb0([[OLD_SELF:%.*]] : @owned $FailableDerivedClass): // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var FailableDerivedClass }, let, name "self" // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [derivedself] [[SELF_BOX]] // CHECK: [[SELF_LIFETIME:%.*]] = begin_borrow [lexical] [[MARKED_SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[SELF_LIFETIME]] // CHECK: store [[OLD_SELF]] to [init] [[PB_BOX]] // CHECK-NEXT: br bb1 // // CHECK: bb1: // CHECK-NEXT: end_borrow [[SELF_LIFETIME]] // CHECK-NEXT: destroy_value [[MARKED_SELF_BOX]] // CHECK-NEXT: [[RESULT:%.*]] = enum $Optional<FailableDerivedClass>, #Optional.none!enumelt // CHECK-NEXT: br bb2([[RESULT]] // // CHECK: bb2([[RESULT:%.*]] : @owned $Optional<FailableDerivedClass>): // CHECK-NEXT: return [[RESULT]] init?(derivedFailBeforeDelegation: ()) { return nil } // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers20FailableDerivedClassC27derivedFailDuringDelegationACSgyt_tcfc : $@convention(method) (@owned FailableDerivedClass) -> @owned Optional<FailableDerivedClass> { // CHECK: bb0([[OLD_SELF:%.*]] : @owned $FailableDerivedClass): init?(derivedFailDuringDelegation: ()) { // First initialize the lvalue for self. // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var FailableDerivedClass }, let, name "self" // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [derivedself] [[SELF_BOX]] // CHECK: [[SELF_LIFETIME:%.*]] = begin_borrow [lexical] [[MARKED_SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[SELF_LIFETIME]] // CHECK: store [[OLD_SELF]] to [init] [[PB_BOX]] // // Then assign canary to other member using a borrow. // CHECK: [[BORROWED_SELF:%.*]] = load_borrow [[PB_BOX]] // CHECK: [[CANARY_VALUE:%.*]] = apply // CHECK: [[CANARY_GEP:%.*]] = ref_element_addr [[BORROWED_SELF]] // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[CANARY_GEP]] : $*Canary // CHECK: assign [[CANARY_VALUE]] to [[WRITE]] self.otherMember = Canary() // Finally, begin the super init sequence. // CHECK: [[LOADED_SELF:%.*]] = load [take] [[PB_BOX]] // CHECK: [[UPCAST_SELF:%.*]] = upcast [[LOADED_SELF]] // CHECK: [[OPT_NEW_SELF:%.*]] = apply {{.*}}([[UPCAST_SELF]]) : $@convention(method) (@owned FailableBaseClass) -> @owned Optional<FailableBaseClass> // CHECK: [[IS_NIL:%.*]] = select_enum [[OPT_NEW_SELF]] // CHECK: cond_br [[IS_NIL]], [[SUCC_BB:bb[0-9]+]], [[FAIL_BB:bb[0-9]+]] // // And then return nil making sure that we do not insert any extra values anywhere. // CHECK: [[SUCC_BB]]: // CHECK: [[NEW_SELF:%.*]] = unchecked_enum_data [[OPT_NEW_SELF]] // CHECK: [[DOWNCAST_NEW_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK: store [[DOWNCAST_NEW_SELF]] to [init] [[PB_BOX]] // CHECK: [[RESULT:%.*]] = load [copy] [[PB_BOX]] // CHECK: [[WRAPPED_RESULT:%.*]] = enum $Optional<FailableDerivedClass>, #Optional.some!enumelt, [[RESULT]] // CHECK: destroy_value [[MARKED_SELF_BOX]] // CHECK: br [[EPILOG_BB:bb[0-9]+]]([[WRAPPED_RESULT]] // // CHECK: [[FAIL_BB]]: // CHECK: destroy_value [[MARKED_SELF_BOX]] super.init(failBeforeFullInitialization: ()) } init?(derivedFailAfterDelegation: ()) { self.otherMember = Canary() super.init(noFail: ()) return nil } // non-optional to IUO init(derivedNoFailDuringDelegation: ()) { self.otherMember = Canary() super.init(failAfterFullInitialization: ())! // necessary '!' } // IUO to IUO init!(derivedFailDuringDelegation2: ()) { self.otherMember = Canary() super.init(failAfterFullInitialization: ())! // unnecessary-but-correct '!' } } extension FailableDerivedClass { convenience init?(derivedFailInExtension: ()) throws { self.init(derivedFailDuringDelegation: derivedFailInExtension) } } //// // Classes with throwing initializers //// class ThrowBaseClass { required init() throws {} required init(throwingCanary: Canary) throws {} init(canary: Canary) {} init(noFail: ()) {} init(fail: Int) throws {} init(noFail: Int) {} } class ThrowDerivedClass : ThrowBaseClass { var canary: Canary? required init(throwingCanary: Canary) throws { } required init() throws { try super.init() } override init(noFail: ()) { try! super.init() } override init(fail: Int) throws {} override init(noFail: Int) {} // ---- Delegating to super // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers17ThrowDerivedClassC30delegatingFailBeforeDelegationACSi_tKcfc : $@convention(method) (Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error any Error) { // CHECK: bb0( // First initialize. // CHECK: [[REF:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self" // CHECK: [[MARK_UNINIT:%.*]] = mark_uninitialized [derivedself] [[REF]] : ${ var ThrowDerivedClass } // CHECK: [[LIFETIME:%.*]] = begin_borrow [lexical] [[MARK_UNINIT]] // CHECK: [[PROJ:%.*]] = project_box [[LIFETIME]] // CHECK: store {{%.*}} to [init] [[PROJ]] // // Then initialize the canary with nil. We are able to borrow the initialized self to avoid retain/release overhead. // CHECK: [[SELF:%.*]] = load_borrow [[PROJ]] // CHECK: [[CANARY_ADDR:%.*]] = ref_element_addr [[SELF]] // CHECK: [[CANARY_FUNC:%.*]] = function_ref @$s21failable_initializers17ThrowDerivedClassC6canaryAA6CanaryCSgvpfi : // CHECK: [[OPT_CANARY:%.*]] = apply [[CANARY_FUNC]]() // CHECK: store [[OPT_CANARY]] to [init] [[CANARY_ADDR]] // CHECK: end_borrow [[SELF]] // // Now we perform the unwrap. // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s21failable_initializers6unwrapyS2iKF : $@convention(thin) // CHECK: try_apply [[UNWRAP_FN]]({{%.*}}) : $@convention(thin) (Int) -> (Int, @error any Error), normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]] // // CHECK: [[NORMAL_BB]]( // CHECK: [[SELF:%.*]] = load [take] [[PROJ]] // CHECK: [[SELF_BASE:%.*]] = upcast [[SELF]] : $ThrowDerivedClass to $ThrowBaseClass // CHECK: [[BASE_INIT_FN:%.*]] = function_ref @$s21failable_initializers14ThrowBaseClassC6noFailACyt_tcfc : $@convention(method) // CHECK: [[SELF_INIT_BASE:%.*]] = apply [[BASE_INIT_FN]]([[SELF_BASE]]) // CHECK: [[SELF:%.*]] = unchecked_ref_cast [[SELF_INIT_BASE]] : $ThrowBaseClass to $ThrowDerivedClass // CHECK: store [[SELF]] to [init] [[PROJ]] // CHECK: [[SELF:%.*]] = load [copy] [[PROJ]] // CHECK: destroy_value [[MARK_UNINIT]] // CHECK: return [[SELF]] // // Finally the error BB. We do not touch self since self is still in the // box implying that destroying MARK_UNINIT will destroy it for us. // CHECK: [[ERROR_BB]]([[ERROR:%.*]] : @owned $any Error): // CHECK: destroy_value [[MARK_UNINIT]] // CHECK: throw [[ERROR]] // CHECK: } // end sil function '$s21failable_initializers17ThrowDerivedClassC30delegatingFailBeforeDelegationACSi_tKcfc' init(delegatingFailBeforeDelegation : Int) throws { try unwrap(delegatingFailBeforeDelegation) super.init(noFail: ()) } // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers17ThrowDerivedClassC41delegatingFailDuringDelegationArgEmissionACSi_tKcfc : $@convention(method) (Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error any Error) { // CHECK: bb0( // First initialize. // CHECK: [[REF:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self" // CHECK: [[MARK_UNINIT:%.*]] = mark_uninitialized [derivedself] [[REF]] : ${ var ThrowDerivedClass } // CHECK: [[LIFETIME:%.*]] = begin_borrow [lexical] [[MARK_UNINIT]] // CHECK: [[PROJ:%.*]] = project_box [[LIFETIME]] // CHECK: store {{%.*}} to [init] [[PROJ]] // // Then initialize the canary with nil. We are able to borrow the initialized self to avoid retain/release overhead. // CHECK: [[SELF:%.*]] = load_borrow [[PROJ]] // CHECK: [[CANARY_ADDR:%.*]] = ref_element_addr [[SELF]] // CHECK: [[CANARY_FUNC:%.*]] = function_ref @$s21failable_initializers17ThrowDerivedClassC6canaryAA6CanaryCSgvpfi : // CHECK: [[OPT_CANARY:%.*]] = apply [[CANARY_FUNC]]() // CHECK: store [[OPT_CANARY]] to [init] [[CANARY_ADDR]] // CHECK: end_borrow [[SELF]] // // Now we begin argument emission where we perform the unwrap. // CHECK: [[SELF:%.*]] = load [take] [[PROJ]] // CHECK: [[BASE_SELF:%.*]] = upcast [[SELF]] : $ThrowDerivedClass to $ThrowBaseClass // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s21failable_initializers6unwrapyS2iKF : $@convention(thin) // CHECK: try_apply [[UNWRAP_FN]]({{%.*}}) : $@convention(thin) (Int) -> (Int, @error any Error), normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]] // // Now we emit the call to the initializer. Notice how we return self back to // its memory locatio nbefore any other work is done. // CHECK: [[NORMAL_BB]]( // CHECK: [[INIT_FN:%.*]] = function_ref @$s21failable_initializers14ThrowBaseClassC6noFailACSi_tcfc : $@convention(method) // CHECK: [[BASE_SELF_INIT:%.*]] = apply [[INIT_FN]]({{%.*}}, [[BASE_SELF]]) // CHECK: [[SELF:%.*]] = unchecked_ref_cast [[BASE_SELF_INIT]] : $ThrowBaseClass to $ThrowDerivedClass // CHECK: store [[SELF]] to [init] [[PROJ]] // // Handle the return value. // CHECK: [[SELF:%.*]] = load [copy] [[PROJ]] // CHECK: destroy_value [[MARK_UNINIT]] // CHECK: return [[SELF]] // // When the error is thrown, we need to: // 1. Store self back into the "conceptually" uninitialized box. // 2. destroy the box. // 3. Perform the rethrow. // CHECK: [[ERROR_BB]]([[ERROR:%.*]] : @owned $any Error): // CHECK: [[SELF:%.*]] = unchecked_ref_cast [[BASE_SELF]] : $ThrowBaseClass to $ThrowDerivedClass // CHECK: store [[SELF]] to [init] [[PROJ]] // CHECK: destroy_value [[MARK_UNINIT]] // CHECK: throw [[ERROR]] // CHECK: } // end sil function '$s21failable_initializers17ThrowDerivedClassC41delegatingFailDuringDelegationArgEmissionACSi_tKcfc' init(delegatingFailDuringDelegationArgEmission : Int) throws { super.init(noFail: try unwrap(delegatingFailDuringDelegationArgEmission)) } // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers17ThrowDerivedClassC34delegatingFailDuringDelegationCallACSi_tKcfc : $@convention(method) (Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error any Error) { // CHECK: bb0( // First initialize. // CHECK: [[REF:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self" // CHECK: [[MARK_UNINIT:%.*]] = mark_uninitialized [derivedself] [[REF]] : ${ var ThrowDerivedClass } // CHECK: [[LIFETIME:%.*]] = begin_borrow [lexical] [[MARK_UNINIT]] // CHECK: [[PROJ:%.*]] = project_box [[LIFETIME]] // CHECK: store {{%.*}} to [init] [[PROJ]] // // Call the initializer. // CHECK: [[SELF:%.*]] = load [take] [[PROJ]] // CHECK: [[BASE_SELF:%.*]] = upcast [[SELF]] : $ThrowDerivedClass to $ThrowBaseClass // CHECK: [[INIT_FN:%.*]] = function_ref @$s21failable_initializers14ThrowBaseClassCACyKcfc : $@convention(method) // CHECK: try_apply [[INIT_FN]]([[BASE_SELF]]) : $@convention(method) (@owned ThrowBaseClass) -> (@owned ThrowBaseClass, @error any Error), normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]] // // Insert the return statement into the normal block... // CHECK: [[NORMAL_BB]]([[BASE_SELF_INIT:%.*]] : @owned $ThrowBaseClass): // CHECK: [[OUT_SELF:%.*]] = unchecked_ref_cast [[BASE_SELF_INIT]] : $ThrowBaseClass to $ThrowDerivedClass // CHECK: store [[OUT_SELF]] to [init] [[PROJ]] // CHECK: [[RESULT:%.*]] = load [copy] [[PROJ]] // CHECK: destroy_value [[MARK_UNINIT]] // CHECK: return [[RESULT]] // // ... and destroy the box in the error block. // CHECK: [[ERROR_BB]]([[ERROR:%.*]] : @owned $any Error): // CHECK-NEXT: end_borrow [[LIFETIME]] // CHECK-NEXT: destroy_value [[MARK_UNINIT]] // CHECK-NEXT: throw [[ERROR]] // CHECK: } // end sil function '$s21failable_initializers17ThrowDerivedClassC34delegatingFailDuringDelegationCallACSi_tKcfc' init(delegatingFailDuringDelegationCall : Int) throws { try super.init() } // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers17ThrowDerivedClassC29delegatingFailAfterDelegationACSi_tKcfc : $@convention(method) (Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error any Error) { // CHECK: bb0( // First initialize. // CHECK: [[REF:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self" // CHECK: [[MARK_UNINIT:%.*]] = mark_uninitialized [derivedself] [[REF]] : ${ var ThrowDerivedClass } // CHECK: [[LIFETIME:%.*]] = begin_borrow [lexical] [[MARK_UNINIT]] // CHECK: [[PROJ:%.*]] = project_box [[LIFETIME]] // CHECK: store {{%.*}} to [init] [[PROJ]] // // Call the initializer and then store the new self back into its memory slot. // CHECK: [[SELF:%.*]] = load [take] [[PROJ]] // CHECK: [[BASE_SELF:%.*]] = upcast [[SELF]] : $ThrowDerivedClass to $ThrowBaseClass // CHECK: [[INIT_FN:%.*]] = function_ref @$s21failable_initializers14ThrowBaseClassC6noFailACyt_tcfc : $@convention(method) // CHECK: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[BASE_SELF]]) : $@convention(method) (@owned ThrowBaseClass) -> @owned ThrowBaseClass // CHECK: [[NEW_SELF_CAST:%.*]] = unchecked_ref_cast [[NEW_SELF]] : $ThrowBaseClass to $ThrowDerivedClass // CHECK: store [[NEW_SELF_CAST]] to [init] [[PROJ]] // // Finally perform the unwrap. // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s21failable_initializers6unwrapyS2iKF : $@convention(thin) (Int) -> (Int, @error any Error) // CHECK: try_apply [[UNWRAP_FN]]({{%.*}}) : $@convention(thin) (Int) -> (Int, @error any Error), normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]] // // Insert the return statement into the normal block... // CHECK: [[NORMAL_BB]]( // CHECK: [[RESULT:%.*]] = load [copy] [[PROJ]] // CHECK: destroy_value [[MARK_UNINIT]] // CHECK: return [[RESULT]] // // ... and destroy the box in the error block. // CHECK: [[ERROR_BB]]([[ERROR:%.*]] : @owned $any Error): // CHECK-NEXT: end_borrow [[LIFETIME]] // CHECK-NEXT: destroy_value [[MARK_UNINIT]] // CHECK-NEXT: throw [[ERROR]] // CHECK: } // end sil function '$s21failable_initializers17ThrowDerivedClassC29delegatingFailAfterDelegationACSi_tKcfc' init(delegatingFailAfterDelegation : Int) throws { super.init(noFail: ()) try unwrap(delegatingFailAfterDelegation) } // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers17ThrowDerivedClassC30delegatingFailBeforeDelegation0fg6DuringI11ArgEmissionACSi_SitKcfc : $@convention(method) (Int, Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error any Error) { // Create our box. // CHECK: [[REF:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self" // CHECK: [[MARK_UNINIT:%.*]] = mark_uninitialized [derivedself] [[REF]] : ${ var ThrowDerivedClass } // CHECK: [[MARK_UNINIT_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[MARK_UNINIT]] // CHECK: [[PROJ:%.*]] = project_box [[MARK_UNINIT_LIFETIME]] // // Perform the unwrap. // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s21failable_initializers6unwrapyS2iKF : $@convention(thin) (Int) -> (Int, @error any Error) // CHECK: try_apply [[UNWRAP_FN]]({{%.*}}) : $@convention(thin) (Int) -> (Int, @error any Error), normal [[UNWRAP_NORMAL_BB:bb[0-9]+]], error [[UNWRAP_ERROR_BB:bb[0-9]+]] // // Now we begin argument emission where we perform another unwrap. // CHECK: [[UNWRAP_NORMAL_BB]]( // CHECK: [[SELF:%.*]] = load [take] [[PROJ]] // CHECK: [[SELF_CAST:%.*]] = upcast [[SELF]] : $ThrowDerivedClass to $ThrowBaseClass // CHECK: [[UNWRAP_FN2:%.*]] = function_ref @$s21failable_initializers6unwrapyS2iKF : $@convention(thin) (Int) -> (Int, @error any Error) // CHECK: try_apply [[UNWRAP_FN2]]({{%.*}}) : $@convention(thin) (Int) -> (Int, @error any Error), normal [[UNWRAP_NORMAL_BB2:bb[0-9]+]], error [[UNWRAP_ERROR_BB2:bb[0-9]+]] // // Then since this example has a // CHECK: [[UNWRAP_NORMAL_BB2]]([[INT:%.*]] : $Int): // CHECK: [[INIT_FN2:%.*]] = function_ref @$s21failable_initializers14ThrowBaseClassC6noFailACSi_tcfc : $@convention(method) (Int, @owned ThrowBaseClass) -> @owned ThrowBaseClass // CHECK: [[NEW_SELF_CAST:%.*]] = apply [[INIT_FN2]]([[INT]], [[SELF_CAST]]) : $@convention(method) (Int, @owned ThrowBaseClass) -> @owned ThrowBaseClass // CHECK: [[NEW_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF_CAST]] : $ThrowBaseClass to $ThrowDerivedClass // CHECK: store [[NEW_SELF]] to [init] [[PROJ]] // CHECK: [[RESULT:%.*]] = load [copy] [[PROJ]] // CHECK: end_borrow [[MARK_UNINIT_LIFETIME]] // CHECK: destroy_value [[MARK_UNINIT]] // CHECK: return [[RESULT]] // // ... and destroy the box in the error block. // CHECK: [[UNWRAP_ERROR_BB]]([[ERROR:%.*]] : @owned $any Error): // CHECK: br [[ERROR_JOIN:bb[0-9]+]]([[ERROR]] // // CHECK: [[UNWRAP_ERROR_BB2]]([[ERROR:%.*]] : @owned $any Error): // CHECK: [[SELF_CASTED_BACK:%.*]] = unchecked_ref_cast [[SELF_CAST]] : $ThrowBaseClass to $ThrowDerivedClass // CHECK: store [[SELF_CASTED_BACK]] to [init] [[PROJ]] // CHECK: br [[ERROR_JOIN]]([[ERROR]] // // CHECK: [[ERROR_JOIN]]([[ERROR_PHI:%.*]] : @owned $any Error): // CHECK: end_borrow [[MARK_UNINIT_LIFETIME]] // CHECK: destroy_value [[MARK_UNINIT]] // CHECK: throw [[ERROR_PHI]] // CHECK: } // end sil function '$s21failable_initializers17ThrowDerivedClassC30delegatingFailBeforeDelegation0fg6DuringI11ArgEmissionACSi_SitKcfc' init(delegatingFailBeforeDelegation : Int, delegatingFailDuringDelegationArgEmission : Int) throws { try unwrap(delegatingFailBeforeDelegation) super.init(noFail: try unwrap(delegatingFailDuringDelegationArgEmission)) } init(delegatingFailBeforeDelegation : Int, delegatingFailDuringDelegationCall : Int) throws { try unwrap(delegatingFailBeforeDelegation) try super.init() } init(delegatingFailBeforeDelegation : Int, delegatingFailAfterDelegation : Int) throws { try unwrap(delegatingFailBeforeDelegation) super.init(noFail: ()) try unwrap(delegatingFailAfterDelegation) } init(delegatingFailDuringDelegationArgEmission : Int, delegatingFailDuringDelegationCall : Int) throws { try super.init(fail: try unwrap(delegatingFailDuringDelegationArgEmission)) } init(delegatingFailDuringDelegationArgEmission : Int, delegatingFailAfterDelegation : Int) throws { super.init(noFail: try unwrap(delegatingFailDuringDelegationArgEmission)) try unwrap(delegatingFailAfterDelegation) } init(delegatingFailDuringDelegationCall : Int, delegatingFailAfterDelegation : Int) throws { try super.init() try unwrap(delegatingFailAfterDelegation) } init(delegatingFailBeforeDelegation : Int, delegatingFailDuringDelegationArgEmission : Int, delegatingFailDuringDelegationCall : Int) throws { try unwrap(delegatingFailBeforeDelegation) try super.init(fail: try unwrap(delegatingFailDuringDelegationArgEmission)) } init(delegatingFailBeforeDelegation : Int, delegatingFailDuringDelegationArgEmission : Int, delegatingFailAfterDelegation : Int) throws { try unwrap(delegatingFailBeforeDelegation) super.init(noFail: try unwrap(delegatingFailDuringDelegationArgEmission)) try unwrap(delegatingFailAfterDelegation) } init(delegatingFailBeforeDelegation : Int, delegatingFailDuringDelegationCall : Int, delegatingFailAfterDelegation : Int) throws { try unwrap(delegatingFailBeforeDelegation) try super.init() try unwrap(delegatingFailAfterDelegation) } init(delegatingFailDuringDelegationArgEmission : Int, delegatingFailDuringDelegationCall : Int, delegatingFailAfterDelegation : Int) throws { try super.init(fail: try unwrap(delegatingFailDuringDelegationArgEmission)) try unwrap(delegatingFailAfterDelegation) } init(delegatingFailBeforeDelegation : Int, delegatingFailDuringDelegationArgEmission : Int, delegatingFailDuringDelegationCall : Int, delegatingFailAfterDelegation : Int) throws { try unwrap(delegatingFailBeforeDelegation) try super.init(fail: try unwrap(delegatingFailDuringDelegationArgEmission)) try unwrap(delegatingFailAfterDelegation) } // ---- Delegating to other self method. convenience init(chainingFailBeforeDelegation : Int) throws { try unwrap(chainingFailBeforeDelegation) self.init(noFail: ()) } convenience init(chainingFailDuringDelegationArgEmission : Int) throws { self.init(noFail: try unwrap(chainingFailDuringDelegationArgEmission)) } convenience init(chainingFailDuringDelegationCall : Int) throws { try self.init() } convenience init(chainingFailAfterDelegation : Int) throws { self.init(noFail: ()) try unwrap(chainingFailAfterDelegation) } convenience init(chainingFailBeforeDelegation : Int, chainingFailDuringDelegationArgEmission : Int) throws { try unwrap(chainingFailBeforeDelegation) self.init(noFail: try unwrap(chainingFailDuringDelegationArgEmission)) } convenience init(chainingFailBeforeDelegation : Int, chainingFailDuringDelegationCall : Int) throws { try unwrap(chainingFailBeforeDelegation) try self.init() } convenience init(chainingFailBeforeDelegation : Int, chainingFailAfterDelegation : Int) throws { try unwrap(chainingFailBeforeDelegation) self.init(noFail: ()) try unwrap(chainingFailAfterDelegation) } // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers17ThrowDerivedClassC39chainingFailDuringDelegationArgEmission0fghI4CallACSi_SitKcfC // CHECK: bb0({{.*}}, [[SELF_META:%.*]] : $@thick ThrowDerivedClass.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self" // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[SELF_LIFETIME:%.*]] = begin_borrow [lexical] [[MARKED_SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[SELF_LIFETIME]] // CHECK: try_apply {{.*}}({{.*}}) : $@convention(thin) (Int) -> (Int, @error any Error), normal [[SUCC_BB1:bb[0-9]+]], error [[ERROR_BB1:bb[0-9]+]] // // CHECK: [[SUCC_BB1]]( // CHECK: try_apply {{.*}}({{.*}}, [[SELF_META]]) : {{.*}}, normal [[SUCC_BB2:bb[0-9]+]], error [[ERROR_BB2:bb[0-9]+]] // // CHECK: [[SUCC_BB2]]([[NEW_SELF:%.*]] : @owned $ThrowDerivedClass): // CHECK-NEXT: assign [[NEW_SELF]] to [[PB_BOX]] // CHECK-NEXT: [[RESULT:%.*]] = load [copy] [[PB_BOX]] // CHECK-NEXT: end_borrow [[SELF_LIFETIME]] // CHECK-NEXT: destroy_value [[MARKED_SELF_BOX]] // CHECK-NEXT: return [[RESULT]] // // CHECK: [[ERROR_BB1]]([[ERROR:%.*]] : @owned $any Error): // CHECK-NEXT: br [[THROWING_BB:bb[0-9]+]]([[ERROR]] // // CHECK: [[ERROR_BB2]]([[ERROR:%.*]] : @owned $any Error): // CHECK-NEXT: br [[THROWING_BB]]([[ERROR]] // // CHECK: [[THROWING_BB]]([[ERROR:%.*]] : @owned $any Error): // CHECK-NEXT: end_borrow [[SELF_LIFETIME]] // CHECK-NEXT: destroy_value [[MARKED_SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] convenience init(chainingFailDuringDelegationArgEmission : Int, chainingFailDuringDelegationCall : Int) throws { try self.init(fail: try unwrap(chainingFailDuringDelegationArgEmission)) } convenience init(chainingFailDuringDelegationArgEmission : Int, chainingFailAfterDelegation : Int) throws { self.init(noFail: try unwrap(chainingFailDuringDelegationArgEmission)) try unwrap(chainingFailAfterDelegation) } // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers17ThrowDerivedClassC32chainingFailDuringDelegationCall0fg5AfterI0ACSi_SitKcfC // CHECK: bb0({{.*}}, [[SELF_META:%.*]] : $@thick ThrowDerivedClass.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self" // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[SELF_LIFETIME:%.*]] = begin_borrow [lexical] [[MARKED_SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[SELF_LIFETIME]] // CHECK: try_apply {{.*}}([[SELF_META]]) : {{.*}}, normal [[SUCC_BB1:bb[0-9]+]], error [[ERROR_BB1:bb[0-9]+]] // // CHECK: [[SUCC_BB1]]([[NEW_SELF:%.*]] : @owned $ThrowDerivedClass): // CHECK-NEXT: assign [[NEW_SELF]] to [[PB_BOX]] // CHECK-NEXT: // function_ref // CHECK-NEXT: function_ref @ // CHECK-NEXT: try_apply {{.*}}({{.*}}) : $@convention(thin) (Int) -> (Int, @error any Error), normal [[SUCC_BB2:bb[0-9]+]], error [[ERROR_BB2:bb[0-9]+]] // // CHECK: [[SUCC_BB2]]( // CHECK-NEXT: [[RESULT:%.*]] = load [copy] [[PB_BOX]] // CHECK-NEXT: end_borrow [[SELF_LIFETIME]] // CHECK-NEXT: destroy_value [[MARKED_SELF_BOX]] // CHECK-NEXT: return [[RESULT]] // // CHECK: [[ERROR_BB1]]([[ERROR:%.*]] : @owned $any Error): // CHECK-NEXT: br [[THROWING_BB:bb[0-9]+]]([[ERROR]] // // CHECK: [[ERROR_BB2]]([[ERROR:%.*]] : @owned $any Error): // CHECK-NEXT: br [[THROWING_BB]]([[ERROR]] // // CHECK: [[THROWING_BB]]([[ERROR:%.*]] : @owned $any Error): // CHECK-NEXT: end_borrow [[SELF_LIFETIME]] // CHECK-NEXT: destroy_value [[MARKED_SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] // CHECK: } // end sil function '$s21failable_initializers17ThrowDerivedClassC28chainingFailBeforeDelegation0fg6DuringI11ArgEmission0fgjI4CallACSi_S2itKcfC' convenience init(chainingFailDuringDelegationCall : Int, chainingFailAfterDelegation : Int) throws { try self.init() try unwrap(chainingFailAfterDelegation) } convenience init(chainingFailBeforeDelegation : Int, chainingFailDuringDelegationArgEmission : Int, chainingFailDuringDelegationCall : Int) throws { try unwrap(chainingFailBeforeDelegation) try self.init(fail: try unwrap(chainingFailDuringDelegationArgEmission)) } convenience init(chainingFailBeforeDelegation : Int, chainingFailDuringDelegationArgEmission : Int, chainingFailAfterDelegation : Int) throws { try unwrap(chainingFailBeforeDelegation) self.init(noFail: try unwrap(chainingFailDuringDelegationArgEmission)) try unwrap(chainingFailAfterDelegation) } convenience init(chainingFailBeforeDelegation : Int, chainingFailDuringDelegationCall : Int, chainingFailAfterDelegation : Int) throws { try unwrap(chainingFailBeforeDelegation) try self.init() try unwrap(chainingFailAfterDelegation) } convenience init(chainingFailDuringDelegationArgEmission : Int, chainingFailDuringDelegationCall : Int, chainingFailAfterDelegation : Int) throws { try self.init(fail: try unwrap(chainingFailDuringDelegationArgEmission)) try unwrap(chainingFailAfterDelegation) } convenience init(chainingFailBeforeDelegation : Int, chainingFailDuringDelegationArgEmission : Int, chainingFailDuringDelegationCall : Int, chainingFailAfterDelegation : Int) throws { try unwrap(chainingFailBeforeDelegation) try self.init(fail: try unwrap(chainingFailDuringDelegationArgEmission)) try unwrap(chainingFailAfterDelegation) } } //// // Enums with failable initializers //// enum FailableEnum { case A init?(a: Int64) { self = .A } init!(b: Int64) { self.init(a: b)! // unnecessary-but-correct '!' } init(c: Int64) { self.init(a: c)! // necessary '!' } init(d: Int64) { self.init(b: d)! // unnecessary-but-correct '!' } } //// // Protocols and protocol extensions //// // Delegating to failable initializers from a protocol extension to a // protocol. protocol P1 { init?(p1: Int64) } extension P1 { init!(p1a: Int64) { self.init(p1: p1a)! // unnecessary-but-correct '!' } init(p1b: Int64) { self.init(p1: p1b)! // necessary '!' } } protocol P2 : class { init?(p2: Int64) } extension P2 { init!(p2a: Int64) { self.init(p2: p2a)! // unnecessary-but-correct '!' } init(p2b: Int64) { self.init(p2: p2b)! // necessary '!' } } @objc protocol P3 { init?(p3: Int64) } extension P3 { init!(p3a: Int64) { self.init(p3: p3a)! // unnecessary-but-correct '!' } init(p3b: Int64) { self.init(p3: p3b)! // necessary '!' } } // Delegating to failable initializers from a protocol extension to a // protocol extension. extension P1 { init?(p1c: Int64) { self.init(p1: p1c) } init!(p1d: Int64) { self.init(p1c: p1d)! // unnecessary-but-correct '!' } init(p1e: Int64) { self.init(p1c: p1e)! // necessary '!' } } extension P2 { init?(p2c: Int64) { self.init(p2: p2c) } init!(p2d: Int64) { self.init(p2c: p2d)! // unnecessary-but-correct '!' } init(p2e: Int64) { self.init(p2c: p2e)! // necessary '!' } } //// // type(of: self) with uninitialized self //// func use(_ a : Any) {} class DynamicTypeBase { var x: Int init() { use(type(of: self)) x = 0 } convenience init(a : Int) { use(type(of: self)) self.init() } } class DynamicTypeDerived : DynamicTypeBase { override init() { use(type(of: self)) super.init() } convenience init(a : Int) { use(type(of: self)) self.init() } } struct DynamicTypeStruct { var x: Int init() { use(type(of: self)) x = 0 } init(a : Int) { use(type(of: self)) self.init() } } class InOutInitializer { // CHECK-LABEL: sil hidden [exact_self_class] [ossa] @$s21failable_initializers16InOutInitializerC1xACSiz_tcfC : $@convention(method) (@inout Int, @thick InOutInitializer.Type) -> @owned InOutInitializer { // CHECK: bb0(%0 : $*Int, %1 : $@thick InOutInitializer.Type): init(x: inout Int) {} } // <rdar://problem/16331406> class SuperVariadic { init(ints: Int...) { } } class SubVariadic : SuperVariadic { } // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers11SubVariadicC4intsACSid_tcfc // CHECK: bb0(%0 : @owned $Array<Int>, %1 : @owned $SubVariadic): // CHECK: [[T0:%.*]] = begin_borrow [lexical] %0 : $Array<Int> // CHECK: [[SELF_UPCAST:%.*]] = upcast {{.*}} : $SubVariadic to $SuperVariadic // CHECK: [[T1:%.*]] = copy_value [[T0]] : $Array<Int> // CHECK: [[SUPER_INIT:%.*]] = function_ref @$s21failable_initializers13SuperVariadicC4intsACSid_tcfc // CHECK: apply [[SUPER_INIT]]([[T1]], [[SELF_UPCAST]]) // CHECK-LABEL: } // end sil function '$s21failable_initializers11SubVariadicC4intsACSid_tcfc' public struct MemberInits<Value : Equatable> { private var box: MemberInitsHelper<Value>? fileprivate var value: String = "default" } class MemberInitsHelper<T> { } extension MemberInits { // CHECK-LABEL: sil [ossa] @$s21failable_initializers11MemberInitsVyACySayqd__GGSayACyqd__GGcADRszSQRd__lufC : $@convention(method) <Value><T where Value == Array<T>, T : Equatable> (@owned Array<MemberInits<T>>, @thin MemberInits<Array<T>>.Type) -> @owned MemberInits<Array<T>> { public init<T>(_ array: Array<MemberInits<T>>) where Value == Array<T> { box = nil // CHECK: [[INIT_FN:%.*]] = function_ref @$s21failable_initializers11MemberInitsV5value33_4497B2E9306011E5BAC13C07BEAC2557LLSSvpfi : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> () -> @owned String // CHECK-NEXT: = apply [[INIT_FN]]<Array<T>>() : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> () -> @owned String } } // rdar://problem/51302498 class Butt { init(foo: inout (Int, Int)) { } }
9363b3f2bd0822baec19dab1045b79bb
38.387509
282
0.646468
false
false
false
false
iOS-mamu/SS
refs/heads/master
P/Potatso/Sync/PushLocalChangesOperation.swift
mit
1
// // PushLocalChangesOperation.swift // Potatso // // Created by LEI on 8/12/16. // Copyright © 2016 TouchingApp. All rights reserved. // import Foundation import PSOperations import CloudKit class PushLocalChangesOperation: PSOperations.Operation { let zoneID: CKRecordZoneID fileprivate let internalQueue = PSOperations.OperationQueue() var toSaveRecords: [CKRecord] = [] var toDeleteRecordIDs: [CKRecordID] = [] var maxRecordsPerRequest = 400 init(zoneID: CKRecordZoneID) { self.zoneID = zoneID super.init() internalQueue.maxConcurrentOperationCount = 15 } override func execute() { DDLogInfo(">>>>>> Start Push Local Changes...") let toSaveObjects = DBUtils.allObjectsToSyncModified() let toDeleteObjects = DBUtils.allObjectsToSyncDeleted() toSaveRecords = toSaveObjects.map { ($0 as! CloudKitRecord).toCloudKitRecord() } toDeleteRecordIDs = toDeleteObjects.map { ($0 as! CloudKitRecord).recordId } DDLogInfo("toSaveRecords: \(toSaveRecords.count), toDeleteRecordIDs: \(toDeleteRecordIDs.count)") let finishObserver = BlockObserver { operation, errors in self.finish(errors) return } let finishOp = PSOperations.BlockOperation {} finishOp.addObserver(finishObserver) if toSaveRecords.count > maxRecordsPerRequest { let total = toSaveRecords.count/maxRecordsPerRequest + 1 for i in 0..<total { let start = i * maxRecordsPerRequest let end = min((i + 1) * maxRecordsPerRequest, toSaveRecords.count) let records = Array(toSaveRecords[start..<end]) let op = addModifiedOperation("Push Local Modified Changes <\(i)/\(total), count: \(records.count)>", records: records) internalQueue.addOperation(op) finishOp.addDependency(op) } } else { let op = addModifiedOperation("Push Local Modified Changes<count: \(toSaveRecords.count)>", records: toSaveRecords) internalQueue.addOperation(op) finishOp.addDependency(op) } if toDeleteRecordIDs.count > maxRecordsPerRequest { let total = toDeleteRecordIDs.count/maxRecordsPerRequest + 1 for i in 0..<total { let start = i * maxRecordsPerRequest let end = min((i + 1) * maxRecordsPerRequest, toDeleteRecordIDs.count) let recordIDs = Array(toDeleteRecordIDs[start..<end]) let op = addDeletedOperation("Push Local Deleted Changes <\(i)/\(total), count: \(recordIDs.count)>", recordIDs: recordIDs) internalQueue.addOperation(op) finishOp.addDependency(op) } } else { let op = addDeletedOperation("Push Local Deleted Changes<count: \(toDeleteRecordIDs.count)>", recordIDs: toDeleteRecordIDs) internalQueue.addOperation(op) finishOp.addDependency(op) } internalQueue.addOperation(finishOp) } func addModifiedOperation(_ name: String, records: [CKRecord]) -> PSOperations.Operation { let op = PushLocalModifiedChangesOperation(zoneID: potatsoZoneId, name: name, modifiedRecords: records) return op } func addDeletedOperation(_ name: String, recordIDs: [CKRecordID]) -> PSOperations.Operation { let op = PushLocalDeletedChangesOperation(zoneID: potatsoZoneId, name: name, deletedRecordIDs: recordIDs) return op } }
2e76f5120f839fbba2892b679588c0a5
40.425287
139
0.642342
false
false
false
false
skylib/SnapImagePicker
refs/heads/master
SnapImagePicker/Categories/UIImage+square.swift
bsd-3-clause
1
import UIKit extension UIImage { func square() -> UIImage?{ let x = self.size.width <= self.size.height ? 0 : (self.size.width - self.size.height) / 2 let y = self.size.height <= self.size.width ? 0 : (self.size.height - self.size.width) / 2 let width = min(self.size.width, self.size.height) let height = width let cropRect = CGRect(x: x * self.scale, y: y * self.scale, width: width * self.scale, height: height * self.scale) if let cgImage = self.cgImage!.cropping(to: cropRect) { return UIImage(cgImage: cgImage) } return nil } } extension UIImage { func findZoomScaleForLargestFullSquare() -> CGFloat { return max(size.width, size.height)/min(size.width, size.height) } func findCenteredOffsetForImageWithZoomScale(_ zoomScale: CGFloat) -> CGFloat { return abs(size.height - size.width) * zoomScale / 2 } }
5621b8d659269ca15d66648ea2dac501
33.703704
123
0.6254
false
false
false
false
barbrobmich/linkbase
refs/heads/master
LinkBase/LinkBase/ProfileLanguageCell.swift
mit
1
// // ProfileLanguageCell.swift // LinkBase // // Created by Barbara Ristau on 4/7/17. // Copyright © 2017 barbrobmich. All rights reserved. // import UIKit class ProfileLanguageCell: UITableViewCell { @IBOutlet weak var languageNameLabel: UILabel! @IBOutlet weak var languageImageView: UIImageView! @IBOutlet weak var collectionView: UICollectionView! var retrievedAffiliations: [Affiliation] = [] var retrievedProjects: [Project] = [] var matchedItemsCount: Int! var projectIndex: Int = 0 override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) collectionView.dataSource = self collectionView.delegate = self } } extension ProfileLanguageCell: UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { //return 10 return matchedItemsCount } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ProfileLangCollectionCell", for: indexPath) as! ProfileLangCollectionCell if retrievedAffiliations.count != 0 && retrievedProjects.count == 0 { cell.affiliation = retrievedAffiliations[indexPath.item] cell.affProjNameLabel.text = retrievedAffiliations[indexPath.item].name } else if retrievedProjects.count != 0 && retrievedAffiliations.count == 0 { cell.project = retrievedProjects[indexPath.item] cell.affProjNameLabel.text = retrievedProjects[indexPath.item].name } else if retrievedAffiliations.count > 0 && retrievedProjects.count > 0 { if indexPath.item < retrievedAffiliations.count { cell.affiliation = retrievedAffiliations[indexPath.item] cell.affProjNameLabel.text = retrievedAffiliations[indexPath.item].name } if indexPath.item >= retrievedAffiliations.count && indexPath.item < matchedItemsCount { cell.project = retrievedProjects[projectIndex] cell.affProjNameLabel.text = retrievedProjects[projectIndex].name projectIndex += 1 } } return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { } }
933f6bdb76121c20385e758fb1ea65b0
34.039474
149
0.673676
false
false
false
false
guxx/paymentez-ios
refs/heads/master
PaymentezSDK/PaymentezCard.swift
mit
1
// // File.swift // PaymentezSDKSample // // Created by Gustavo Sotelo on 02/05/16. // Copyright © 2016 Paymentez. All rights reserved. // import Foundation public enum PaymentezCardType: String { case visa = "vi" case masterCard = "mc" case amex = "ax" case diners = "di" case discover = "dc" case jcb = "jb" case elo = "el" case credisensa = "cs" case solidario = "so" case exito = "ex" case alkosto = "ak" case notSupported = "" } let REGEX_AMEX = "^3[47][0-9]{5,}$" let REGEX_VISA = "^4[0-9]{6,}$" let REGEX_MASTERCARD = "^5[1-5][0-9]{5,}$" let REGEX_DINERS = "^3(?:0[0-5]|[68][0-9])[0-9]{4,}$" let REGEX_DISCOVER = "^65[4-9][0-9]{13}|64[4-9][0-9]{13}|6011[0-9]{12}|(622(?:12[6-9]|1[3-9][0-9]|[2-8][0-9][0-9]|9[01][0-9]|92[0-5])[0-9]{10})$" let REGEX_JCB = "^(?:2131|1800|35[0-9]{3})[0-9]{11}$" public typealias ValidationCallback = (_ cardType: PaymentezCardType, _ cardImageUrl:String?, _ cvvLength:Int?, _ maskString:String?, _ showOtp:Bool) -> Void @objcMembers open class PaymentezCard:NSObject { open var status:String? open var transactionId:String? open var token:String? open var cardHolder:String? open var fiscalNumber: String? open var termination:String? open var isDefault:Bool = false open var expiryMonth:String? open var expiryYear:String? open var bin:String? open var nip:String? open var msg:String? open var cardType:PaymentezCardType = .notSupported internal var cardNumber:String? { didSet { if cardNumber != nil { self.termination = String(self.cardNumber!.suffix(4)) } } } internal var cvc:String? open var type:String? { didSet { if self.type == "vi" { self.cardType = .visa } if self.type == "ax" { self.cardType = .amex } if self.type == "mc" { self.cardType = .masterCard } if self.type == "di" { self.cardType = .diners } if self.type == "al" { self.cardType = .alkosto } if self.type == "ex" { self.cardType = .exito } } } public static func createCard(cardHolder:String, cardNumber:String, expiryMonth:NSInteger, expiryYear:NSInteger, cvc:String) ->PaymentezCard? { let paymentezCard = PaymentezCard() if getTypeCard(cardNumber) == .notSupported { return nil } let today = Date() let calendar = NSCalendar.current let components = calendar.dateComponents([.month, .year], from: today) let todayMonth = components.month! let todayYear = components.year! if expiryYear < todayYear { return nil } if expiryMonth <= todayMonth && expiryYear == todayYear { return nil } paymentezCard.cardNumber = cardNumber paymentezCard.cardHolder = cardHolder paymentezCard.expiryMonth = "\(expiryMonth)" paymentezCard.expiryYear = "\(expiryYear)" paymentezCard.cvc = cvc return paymentezCard } static func validateExpDate(_ expDate:String) -> Bool { let today = Date() let calendar = NSCalendar.current let components = calendar.dateComponents([.month, .year], from: today) let todayMonth = components.month! let todayYear = components.year! - 2000 let valExp = expDate.components(separatedBy: "/") if valExp.count > 1 { let expYear = Int(valExp[1])! let expMonth = Int(valExp[0])! if expYear > todayYear { return true } else if expYear == todayYear && expMonth > todayMonth && expMonth <= 12 { return true } } return false } public func getJSONString() ->String? { var json:Any? = nil do{ json = try JSONSerialization.data(withJSONObject: self.getDict(), options: .prettyPrinted) } catch { } if json != nil { let theJSONText = String(data: json as! Data, encoding: .ascii) return theJSONText } return nil } public func getDict() -> NSDictionary { let dict = [ "bin" : self.bin, "status": self.status, "token": self.token, "expiry_year": self.expiryYear, "expiry_month": self.expiryMonth, "transaction_reference": self.transactionId, "holder_name": self.cardHolder, "type": self.type, "number": self.termination, "message": "" ] return dict as NSDictionary } public func getCardTypeAsset() ->UIImage? { let bundle = Bundle(for: PaymentezCard.self) if cardType == PaymentezCardType.amex { return UIImage(named:"stp_card_amex", in: bundle, compatibleWith: nil) } else if cardType == PaymentezCardType.masterCard { return UIImage(named:"stp_card_mastercard", in: bundle, compatibleWith: nil) } else if cardType == PaymentezCardType.visa { return UIImage(named:"stp_card_visa", in: bundle, compatibleWith: nil) } else if cardType == PaymentezCardType.diners { return UIImage(named:"stp_card_diners", in: bundle, compatibleWith: nil) } else if cardType == PaymentezCardType.discover { return UIImage(named:"stp_card_discover", in: bundle, compatibleWith: nil) } else if cardType == PaymentezCardType.jcb { return UIImage(named:"stp_card_jcb", in: bundle, compatibleWith: nil) } else { return UIImage(named: "stp_card_unknown", in: bundle, compatibleWith: nil) } } public static func getTypeCard(_ cardNumber:String) -> PaymentezCardType { if cardNumber.count < 15 || cardNumber.count > 16 { return PaymentezCardType.notSupported } let predicateAmex = NSPredicate(format: "SELF MATCHES %@", REGEX_AMEX) if predicateAmex.evaluate(with: cardNumber) { return PaymentezCardType.amex } let predicateVisa = NSPredicate(format: "SELF MATCHES %@", REGEX_VISA) if predicateVisa.evaluate(with: cardNumber) { return PaymentezCardType.visa } let predicateMC = NSPredicate(format: "SELF MATCHES %@", REGEX_MASTERCARD) if predicateMC.evaluate(with: cardNumber) { return PaymentezCardType.masterCard } let predicateDiners = NSPredicate(format: "SELF MATCHES %@", REGEX_DINERS) if predicateDiners.evaluate(with: cardNumber) { return PaymentezCardType.diners } let predicateDiscover = NSPredicate(format: "SELF MATCHES %@", REGEX_DISCOVER) if predicateDiscover.evaluate(with: cardNumber) { return PaymentezCardType.discover } let predicateJCB = NSPredicate(format: "SELF MATCHES %@", REGEX_JCB) if predicateJCB.evaluate(with: cardNumber) { return PaymentezCardType.jcb } return PaymentezCardType.notSupported } public static func validate(cardNumber:String, callback:@escaping ValidationCallback){ PaymentezSDKClient.validateCard(cardNumber: cardNumber) { (data, err) in if err == nil{ guard let dataDict = data else { callback(.notSupported, nil, nil, nil, false) print("Not supported") return } guard let cardType = dataDict["card_type"] as? String else{ callback(.notSupported, nil, nil, nil, false) print("Not card type") return } let urlLogo = dataDict["url_logo_png"] as? String guard let cvvLength = dataDict["cvv_length"] as? Int else{ callback(.notSupported, nil, nil, nil, false) print("Not cvv_length") return } guard let maskString = dataDict["card_mask"] as? String else{ callback(.notSupported, nil, nil, nil, false) print("Not mask") return } let showOtp = dataDict["otp"] as? Bool ?? false callback(PaymentezCardType(rawValue: cardType) ?? PaymentezCardType(rawValue: "")! , urlLogo, cvvLength, maskString, showOtp) } else{ callback(.notSupported, nil, nil, nil, false) } } } } @objcMembers open class PaymentezTransaction:NSObject { open var authorizationCode:NSNumber? open var amount:NSNumber? open var paymentDate: Date? open var status:String? open var carrierCode:String? open var message:String? open var statusDetail:NSNumber? open var transactionId:String? open var carrierData:[String:Any]? static func parseTransaction(_ data:Any?) ->PaymentezTransaction { let data = data as! [String:Any] let trx = PaymentezTransaction() trx.amount = data["amount"] as? NSNumber trx.status = data["status"] as? String trx.statusDetail = data["status_detail"] as? Int as NSNumber? trx.transactionId = data["transaction_id"] as? String trx.carrierData = data["carrier_data"] as? [String:Any] let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" if let paymentdate = (data["payment_date"] as? String) { trx.paymentDate = dateFormatter.date(from: paymentdate) } return trx } static func parseTransactionV2(_ data:Any?) ->PaymentezTransaction { let data = data as! [String:Any] let trx = PaymentezTransaction() trx.amount = data["amount"] as? NSNumber trx.status = data["status"] as? String trx.statusDetail = data["status_detail"] as? Int as NSNumber? trx.transactionId = data["id"] as? String trx.authorizationCode = data["authorization_code"] as? Int as NSNumber? trx.carrierCode = data["carrier_code"] as? String trx.message = data["message"] as? String let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" if let paymentdate = (data["payment_date"] as? String) { trx.paymentDate = dateFormatter.date(from: paymentdate) } return trx } }
fbbeebb5c2cf21bb9e0899213191a868
30.108696
157
0.543501
false
false
false
false
wojteklu/logo
refs/heads/master
Logo/Playground.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import Logo let code20 = "" + "to qcircle :size " + "repeat 90 [fd(:size) rt(1)] " + "end " + //"to petal :size " + //"qcircle(:size) " + //"rt(90) " + //"qcircle(:size) " + //"rt(90) " + //"end " + "qcircle(5) rt(90) qcircle(5)" let code = "fd(100) rt(90) fd(100)" //let code2 = "to wojtek fd(100) end wojtek() rt(90) wojtek()" let code13 = "" + "to qcircle :size " + "repeat 90 [fd(:size) rt(1)] " + "end " + "to petal :size " + "qcircle(:size) " + "rt(90) " + "qcircle(:size) " + "rt(90) " + "end " + "to flower :size " + "repeat 10 [petal(:size) rt(360/10)] " + "end " + "to plant :size " + "flower(:size) " + "bk(135 * :size) " + "petal(:size) " + "bk(65 * :size) " + "end " + "repeat 1 [ plant(2) ] " let code3 = "" + "to tree :size " + "if (:size < 5) [fd(:size) bk(:size) ] else [" + "fd(:size/3) " + "lt(30) tree(:size*2/3) rt(30) " + "fd(:size/6) " + "rt(25) tree(:size/2) lt(25) " + "fd(:size/3) " + "rt(25) tree(:size/2) lt(25) " + "fd(:size/6) " + "bk(:size) ]" + "end " + "to qcircle :size " + "repeat 90 [fd(:size) rt(1)] " + "end " + "bk(150) tree(250) " let code4 = "" + "to fern :size :sign " + "if (:size > 1) [" + "fd(:size) " + "rt(70 * :sign) fern(:size * 1/2, :sign * 1) lt(70 * :sign) " + "fd(:size) " + "lt(70 * :sign) fern(:size * 1/2, :sign) rt(70 * :sign) " + "rt(7 * :sign) fern(:size - 1, :sign) lt(7 * :sign) " + "bk(:size * 2) ] " + "end " + "fern(30, 1)" let code10 = "" + "to line :count :length " + "if (:count = 1) [fd(:length)] " + "else [ " + "line(:count-1, :length) " + "lt(60) line(:count-1, :length) " + "rt(120) line(:count-1, :length) " + "lt(60) line(:count-1, :length) " + " ] end " + "to koch :count :length " + "rt(30) line(:count, :length) " + "rt(120) line(:count, :length) " + "rt(120) line(:count, :length) " + "end " + "koch(5, 10)" let code100 = "" + "repeat 100 [" + "repeat 8 [" + "fd(80)" + "rt(80)" + "bk(80)" + "] " + "rt(45)" + "]" let code2 = "to square :length repeat 4 [ forward(:length) right(90) ] end repeat 220 [ square(random(200)) right(10) ]" let interpreter = Interpreter() interpreter.run(code: code2)
44cd54c04071b41b4bdcbb484b38703b
21.358491
120
0.467932
false
false
false
false
mgzf/MGAssociationMenuView
refs/heads/master
Sources/MGAssociationPeriferal.swift
mit
1
// // // _____ // / ___/____ ____ ____ _ // \__ \/ __ \/ __ \/ __ `/ // ___/ / /_/ / / / / /_/ / // /____/\____/_/ /_/\__, / // /____/ // // .-~~~~~~~~~-._ _.-~~~~~~~~~-. // __.' ~. .~ `.__ // .'// \./ \\`. // .'// | \\`. // .'// .-~"""""""~~~~-._ | _,-~~~~"""""""~-. \\`. // .'//.-" `-. | .-' "-.\\`. // .'//______.============-.. \ | / ..-============.______\\`. //.'______________________________\|/______________________________`. // // // BottomLineVisible.swift // MGAssociationMenuView // // Created by song on 2017/8/1. // Copyright © 2017年 song. All rights reserved. // import UIKit //MARK: - MenuView 高度控制 public enum MGAssociationFrameEnum: Int{ /*!根据高度自动计算出最多显示多少行 */ case autoLayout = 0 /*! 直接显示本身高度 */ case custom } //MARK: - view加线 Protocol public protocol BottomLineVisible : class { var lineColor: UIColor { get set } var lineHeight: CGFloat { get set } func addLineTo(view:UIView, edge:UIEdgeInsets?) func deleteLineTo(view:UIView) } extension BottomLineVisible{ public func addLineTo(view:UIView, edge:UIEdgeInsets?){ let lineEdge = edge ?? UIEdgeInsets.zero let lineView = UIView() lineView.tag = 135792 lineView.backgroundColor = lineColor view.addSubview(lineView) lineView.snp.makeConstraints { (make) in make.left.equalTo(view).offset(lineEdge.left) make.right.equalTo(view).offset(lineEdge.right) make.bottom.equalTo(view).offset(lineEdge.bottom) make.height.equalTo(lineHeight) } } public func deleteLineTo(view:UIView){ if let subView = view.viewWithTag(135792) { subView.removeFromSuperview() } } }
695edeb70df118b3f6f96933b127bea6
25.6875
69
0.392037
false
false
false
false
skyfe79/SwiftImageProcessing
refs/heads/master
06_SplitRGBColorSpace_2.playground/Sources/RGBAImage.swift
mit
1
import UIKit public struct Pixel { public var value: UInt32 //red public var R: UInt8 { get { return UInt8(value & 0xFF); } set { value = UInt32(newValue) | (value & 0xFFFFFF00) } } //green public var G: UInt8 { get { return UInt8((value >> 8) & 0xFF) } set { value = (UInt32(newValue) << 8) | (value & 0xFFFF00FF) } } //blue public var B: UInt8 { get { return UInt8((value >> 16) & 0xFF) } set { value = (UInt32(newValue) << 16) | (value & 0xFF00FFFF) } } //alpha public var A: UInt8 { get { return UInt8((value >> 24) & 0xFF) } set { value = (UInt32(newValue) << 24) | (value & 0x00FFFFFF) } } public var Rf: Double { get { return Double(self.R) / 255.0 } set { self.R = UInt8(newValue * 255.0) } } public var Gf: Double { get { return Double(self.G) / 255.0 } set { self.G = UInt8(newValue * 255.0) } } public var Bf: Double { get { return Double(self.B) / 255.0 } set { self.B = UInt8(newValue * 255.0) } } public var Af: Double { get { return Double(self.A) / 255.0 } set { self.A = UInt8(newValue * 255.0) } } } public struct RGBAImage { public var pixels: UnsafeMutableBufferPointer<Pixel> public var width: Int public var height: Int public init?(image: UIImage) { // CGImage로 변환이 가능해야 한다. guard let cgImage = image.cgImage else { return nil } // 주소 계산을 위해서 Float을 Int로 저장한다. width = Int(image.size.width) height = Int(image.size.height) // 4 * width * height 크기의 버퍼를 생성한다. let bytesPerRow = width * 4 let imageData = UnsafeMutablePointer<Pixel>.allocate(capacity: width * height) // 색상공간은 Device의 것을 따른다 let colorSpace = CGColorSpaceCreateDeviceRGB() // BGRA로 비트맵을 만든다 var bitmapInfo: UInt32 = CGBitmapInfo.byteOrder32Big.rawValue bitmapInfo = bitmapInfo | CGImageAlphaInfo.premultipliedLast.rawValue & CGBitmapInfo.alphaInfoMask.rawValue // 비트맵 생성 guard let imageContext = CGContext(data: imageData, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) else { return nil } // cgImage를 imageData에 채운다. imageContext.draw(cgImage, in: CGRect(origin: .zero, size: image.size)) pixels = UnsafeMutableBufferPointer<Pixel>(start: imageData, count: width * height) } public init(width: Int, height: Int) { let image = RGBAImage.newUIImage(width: width, height: height) self.init(image: image)! } public func clone() -> RGBAImage { let cloneImage = RGBAImage(width: self.width, height: self.height) for y in 0..<height { for x in 0..<width { let index = y * width + x cloneImage.pixels[index] = self.pixels[index] } } return cloneImage } public func toUIImage() -> UIImage? { let colorSpace = CGColorSpaceCreateDeviceRGB() var bitmapInfo: UInt32 = CGBitmapInfo.byteOrder32Big.rawValue let bytesPerRow = width * 4 bitmapInfo |= CGImageAlphaInfo.premultipliedLast.rawValue & CGBitmapInfo.alphaInfoMask.rawValue guard let imageContext = CGContext(data: pixels.baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo, releaseCallback: nil, releaseInfo: nil) else { return nil } guard let cgImage = imageContext.makeImage() else { return nil } let image = UIImage(cgImage: cgImage) return image } public func pixel(x : Int, _ y : Int) -> Pixel? { guard x >= 0 && x < width && y >= 0 && y < height else { return nil } let address = y * width + x return pixels[address] } public mutating func pixel(x : Int, _ y : Int, _ pixel: Pixel) { guard x >= 0 && x < width && y >= 0 && y < height else { return } let address = y * width + x pixels[address] = pixel } public mutating func process( functor : ((Pixel) -> Pixel) ) { for y in 0..<height { for x in 0..<width { let index = y * width + x let outPixel = functor(pixels[index]) pixels[index] = outPixel } } } public func enumerate( functor : (Int, Pixel) -> Void) { for y in 0..<height { for x in 0..<width { let index = y * width + x functor(index, pixels[index]) } } } private static func newUIImage(width: Int, height: Int) -> UIImage { let size = CGSize(width: CGFloat(width), height: CGFloat(height)); UIGraphicsBeginImageContextWithOptions(size, true, 0); UIColor.black.setFill() UIRectFill(CGRect(x: 0, y: 0, width: size.width, height: size.height)) let image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image! } }
30cd94d7c3dddd3e56e75c1aea64cdcb
30.865497
235
0.552762
false
false
false
false
eurofurence/ef-app_ios
refs/heads/release/4.0.0
Packages/EurofurenceApplication/Sources/EurofurenceApplication/Application/Components/Settings/App Icon Picker/View Model/Repository Adapter/RepositoryBackedAppIconsViewModel.swift
mit
1
import Combine public class RepositoryBackedAppIconsViewModel<IconState>: AppIconsViewModel where IconState: ApplicationIconState { public init(repository: any AppIconRepository, applicationIconState: IconState) { let repositoryIcons = repository.loadAvailableIcons() icons = repositoryIcons.map({ IconViewModel(icon: $0, applicationIconState: applicationIconState) }) } public typealias Icon = IconViewModel public private(set) var icons: [IconViewModel] public class IconViewModel: AppIconViewModel { private let icon: AppIcon private let applicationIconState: IconState private var subscriptions = Set<AnyCancellable>() init(icon: AppIcon, applicationIconState: IconState) { self.icon = icon self.applicationIconState = applicationIconState applicationIconState .alternateIconNamePublisher .map({ [icon] (alternateIconName) in icon.alternateIconName == alternateIconName }) .sink { [weak self] in self?.isCurrentAppIcon = $0 } .store(in: &subscriptions) } public var imageName: String { icon.imageFileName } public var displayName: String { icon.displayName } @Published public private(set) var isCurrentAppIcon: Bool = false public func selectAsAppIcon() { applicationIconState.updateApplicationIcon(alternateIconName: icon.alternateIconName) } } }
bf140376efae97311729ebbd0c5e7840
33.617021
116
0.630608
false
false
false
false
antitypical/Manifold
refs/heads/master
Manifold/Module+Prelude.swift
mit
1
// Copyright © 2015 Rob Rix. All rights reserved. extension Module { public static var prelude: Module { let identity = Declaration("identity", type: nil => { A in A --> A }, value: nil => { A in A => id }) let constant = Declaration("constant", type: (nil, nil) => { A, B in A --> B --> A }, value: (nil, nil) => { A, B in A => { B => const($0) } }) let flip = Declaration("flip", type: (nil, nil, nil) => { A, B, C in (A --> B --> C) --> (B --> A --> C) }, value: (nil, nil, nil) => { A, B, C in (A --> B --> C) => { f in (nil, nil) => { b, a in f[a, b] } } }) return Module("Prelude", [ identity, constant, flip ]) } } import Prelude
d7015b6111f72809ac8278badd339a1b
29.545455
106
0.50744
false
false
false
false
CodaFi/swift
refs/heads/main
validation-test/Sema/type_checker_perf/fast/rdar17077404.swift
apache-2.0
25
// RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1 // REQUIRES: tools-release,no_asan func memoize<A: Hashable, R>( f: @escaping ((A) -> R, A) -> R ) -> ((A) -> R) { var memo = Dictionary<A,R>() var recur: ((A) -> R)! recur = { (a: A) -> R in if let r = memo[a] { return r } let r = f(recur, a) memo[a] = r return r } return recur } let fibonacci = memoize { (fibonacci, n) in n < 2 ? n as Int : fibonacci(n - 1) + fibonacci(n - 2) }
b2c637efaf8b04235754210ab8192149
20.478261
74
0.554656
false
false
false
false
LoveAlwaysYoung/EnjoyUniversity
refs/heads/master
EnjoyUniversity/EnjoyUniversity/Classes/Tools/SwiftyControl/SwiftySpinner.swift
mit
1
// // SwiftySpinner.swift // EnjoyUniversity // // Created by lip on 17/4/15. // Copyright © 2017年 lip. All rights reserved. // import UIKit protocol SwiftySpinnerDelegate { /// 选中 func swiftySpinnerDidSelectRowAt(cell:SwiftySpinnerCell,row:Int) /// 显示状态变化 func swiftySpinnerDidChangeStatus(isOnView:Bool) } class SwiftySpinner: UIView { /// 下拉选择列表 lazy var spinnertableview = UITableView() /// 下拉选择数组 var datalist = [String]() /// 是否显示 var isOnView: Bool = false{ didSet{ delegate?.swiftySpinnerDidChangeStatus(isOnView: isOnView) } } /// 代理 var delegate:SwiftySpinnerDelegate? override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.6) spinnertableview.layer.masksToBounds = true spinnertableview.layer.cornerRadius = 10 spinnertableview.separatorStyle = .none spinnertableview.delegate = self spinnertableview.dataSource = self spinnertableview.backgroundColor = UIColor.white addSubview(spinnertableview) let tapgesture = UITapGestureRecognizer(target: self, action: #selector(removeSpinner)) tapgesture.delegate = self addGestureRecognizer(tapgesture) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func reloadData(){ let tbheight:CGFloat = CGFloat(datalist.count > 3 ? 4 : datalist.count)*44.0 spinnertableview.frame = CGRect(x: 10, y: -tbheight , width: UIScreen.main.bounds.width - 20, height: tbheight) spinnertableview.reloadData() } } // MARK: - 动画方法 extension SwiftySpinner{ func showSpinner(){ isOnView = true self.alpha = 1 UIView.animate(withDuration: 0.5) { self.spinnertableview.frame.origin = CGPoint(x: 10, y: 64 + 10) } } func removeSpinner(){ isOnView = false UIView.animate(withDuration: 0.5, animations: { self.alpha = 0 self.spinnertableview.frame.origin = CGPoint(x: 5, y: -self.spinnertableview.frame.height) }) { (_) in self.removeFromSuperview() } } } // MARK: - 代理方法 extension SwiftySpinner:UIGestureRecognizerDelegate,UITableViewDelegate,UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return datalist.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = SwiftySpinnerCell(title: datalist[indexPath.row], font: 15, textcolor: UIColor.darkText) if indexPath.row == 0{ cell.textlabel.textColor = UIColor.init(red: 18/255, green: 150/255, blue: 219/255, alpha: 1) cell.indicatorview.isHidden = false } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { for cell in tableView.visibleCells{ let cell = cell as? SwiftySpinnerCell cell?.textlabel.textColor = UIColor.darkText cell?.indicatorview.isHidden = true } guard let cell = tableView.cellForRow(at: indexPath) as? SwiftySpinnerCell else{ return } cell.textlabel.textColor = UIColor.init(red: 18/255, green: 150/255, blue: 219/255, alpha: 1) cell.indicatorview.isHidden = false removeSpinner() delegate?.swiftySpinnerDidSelectRowAt(cell: cell, row: indexPath.row) } // 解决手势和 tableview 响应冲突 func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { if NSStringFromClass((touch.view?.classForCoder)!) == "UITableViewCellContentView"{ return false } return true } } /// 自定义 Cell class SwiftySpinnerCell:UITableViewCell{ let textlabel = UILabel() let indicatorview = UIImageView(image: UIImage(named: "community_select")) init(title:String,font:CGFloat = 15,textcolor:UIColor = UIColor.darkText) { super.init(style: .default, reuseIdentifier: nil) selectionStyle = .none textlabel.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width - 20, height: self.frame.height) textlabel.text = title textlabel.textAlignment = .center textlabel.font = UIFont.boldSystemFont(ofSize: font) textlabel.textColor = textcolor textlabel.backgroundColor = UIColor.clear addSubview(textlabel) indicatorview.frame = CGRect(x: 5, y: 5, width: 5, height: frame.height - 10) indicatorview.isHidden = true addSubview(indicatorview) self.backgroundColor = UIColor.clear } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
3f4dc5a57d298230d5cab695474ca5f0
28.384181
119
0.620265
false
false
false
false
fnazarios/weather-app
refs/heads/dev
Carthage/Checkouts/Moya/Carthage/Checkouts/RxSwift/RxTests/RxSwiftTests/TestImplementations/Mocks/PrimitiveHotObservable.swift
apache-2.0
4
// // PrimitiveHotObservable.swift // RxTests // // Created by Krunoslav Zaher on 6/4/15. // // import Foundation import RxSwift let SubscribedToHotObservable = Subscription(0) let UnsunscribedFromHotObservable = Subscription(0, 0) class PrimitiveHotObservable<ElementType : Equatable> : ObservableType { typealias E = ElementType typealias Events = Recorded<E> typealias Observer = AnyObserver<E> var subscriptions: [Subscription] var observers: Bag<AnyObserver<E>> let lock = NSRecursiveLock() init() { self.subscriptions = [] self.observers = Bag() } func on(event: Event<E>) { observers.on(event) } func subscribe<O : ObserverType where O.E == E>(observer: O) -> Disposable { lock.lock() defer { lock.unlock() } let key = observers.insert(AnyObserver(observer)) subscriptions.append(SubscribedToHotObservable) let i = self.subscriptions.count - 1 return AnonymousDisposable { self.lock.lock() defer { self.lock.unlock() } let removed = self.observers.removeKey(key) assert(removed != nil) self.subscriptions[i] = UnsunscribedFromHotObservable } } }
af0c9c583815609e0bb24793a12311dc
22.909091
80
0.609886
false
false
false
false
ymkim50/MFImageSlider
refs/heads/master
MFImageSlider/Classes/ImageSlider.swift
mit
1
// // ImageSlider.swift // Pods // // Created by Youngmin Kim on 2016. 12. 19.. // // import UIKit public protocol FImageSliderDelegate: class { func sliderValueChanged(slider: FImageSlider) // call when user is swiping slider func sliderValueChangeEnded(slider: FImageSlider) // calls when user touchUpInside or touchUpOutside slider } let handleWidth: CGFloat = 14.0 let borderWidth: CGFloat = 2.0 let viewCornerRadius: CGFloat = 5.0 let animationDuration: TimeInterval = 0.1// speed when slider change position on tap public class FImageSlider: UIView { public enum Orientation { case vertical case horizontal } public weak var delegate: FImageSliderDelegate? = nil lazy var imageView: UIImageView = { var imageView = UIImageView() imageView.backgroundColor = .red imageView.frame = self.bounds imageView.isHidden = true return imageView }() public var backgroundImage: UIImage? { get { return imageView.image } set { if let image = newValue { imageView.image = image imageView.isHidden = false } else { imageView.image = nil imageView.isHidden = true } } } lazy var foregroundView: UIView = { var view = UIView() return view }() lazy var handleView: UIView = { var view = UIView() view.layer.cornerRadius = viewCornerRadius view.layer.masksToBounds = true return view }() lazy var label: UILabel = { var label = UILabel() switch self.orientation { case .vertical: label.transform = CGAffineTransform(rotationAngle: CGFloat(-M_PI / 2.0)) label.frame = self.bounds case .horizontal: label.frame = self.bounds } label.textAlignment = .center label.font = UIFont(name: "Helvetica", size: 24) return label }() var _value: Float = 0.0 public var value: Float { get { return _value } set { _value = newValue self.setValue(value: _value, animated: false, completion: nil) } } var orientation: Orientation = .vertical public var isCornersHidden: Bool = false { didSet { if isCornersHidden { self.layer.cornerRadius = 0.0 self.layer.masksToBounds = true } else { self.layer.cornerRadius = viewCornerRadius self.layer.masksToBounds = true } } } public var isBordersHidden: Bool = false { didSet { if isBordersHidden { self.layer.borderWidth = 0.0 } else { self.layer.borderWidth = borderWidth } } } public var isHandleHidden: Bool = false { didSet { if isHandleHidden { handleView.isHidden = true handleView.removeFromSuperview() } else { insertSubview(handleView, aboveSubview: label) handleView.isHidden = false } } } public var foregroundColor: UIColor? { get { return foregroundView.backgroundColor } set { foregroundView.backgroundColor = newValue } } public var handleColor: UIColor? { get { return handleView.backgroundColor } set { handleView.backgroundColor = newValue } } public var borderColor: UIColor? { get { if let cgColor = self.layer.borderColor { return UIColor(cgColor: cgColor) } else { return nil } } set { return self.layer.borderColor = newValue?.cgColor } } public var text: String? { get { return self.label.text } set { self.label.text = newValue } } public var font: UIFont! { get { return self.label.font } set { self.label.font = newValue } } public var textColor: UIColor! { get { return self.label.textColor } set { self.label.textColor = newValue } } public init(frame: CGRect, orientation: Orientation) { super.init(frame: frame) self.orientation = orientation initSlider() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) if self.frame.width > self.frame.height { orientation = .horizontal } else { orientation = .vertical } initSlider() } } extension FImageSlider { func initSlider() { addSubview(imageView) addSubview(foregroundView) addSubview(label) addSubview(handleView) self.layer.cornerRadius = viewCornerRadius self.layer.masksToBounds = true self.layer.borderWidth = borderWidth // set default value for slider. Value should be between 0 and 1 self.setValue(value: 0.0, animated: false, completion: nil) } func setValue(value: Float, animated: Bool, completion: ((Bool) -> Void)? = nil) { assert(value >= 0.0 && value <= 1.0, "Value must between 0 and 1") let calcValue = max(0, min(value, 1)) var point: CGPoint = .zero switch orientation { case .vertical: point = CGPoint(x: 0, y: CGFloat(1 - calcValue) * self.frame.height) case .horizontal: point = CGPoint(x: CGFloat(calcValue) * self.frame.width, y: 0) } if animated { UIView.animate(withDuration: animationDuration, animations: { self.changeStartForegroundView(withPoint: point) }, completion: { (completed) in if completed { completion?(completed) } }) } else { changeStartForegroundView(withPoint: point) } } } // MARK: - Change slider forground with point extension FImageSlider { func changeStartForegroundView(withPoint point: CGPoint) { var calcPoint = point switch orientation { case .vertical: calcPoint.y = max(0, min(calcPoint.y, self.frame.height)) self._value = Float(1.0 - (calcPoint.y / self.frame.height)) self.foregroundView.frame = CGRect(x: 0.0, y: self.frame.height, width: self.frame.width, height: calcPoint.y - self.frame.height) if !isHandleHidden { if foregroundView.frame.origin.y <= 0 { handleView.frame = CGRect(x: borderWidth, y: 0.0, width: self.frame.width - borderWidth * 2, height: handleWidth) } else if foregroundView.frame.origin.y >= self.frame.height { handleView.frame = CGRect(x: borderWidth, y: self.frame.height - handleWidth, width: self.frame.width - borderWidth * 2, height: handleWidth) } else { handleView.frame = CGRect(x: borderWidth, y: foregroundView.frame.origin.y - handleWidth / 2, width: self.frame.width - borderWidth * 2, height: handleWidth) } } case .horizontal: calcPoint.x = max(0, min(calcPoint.x, self.frame.width)) self._value = Float(calcPoint.x / self.frame.width) self.foregroundView.frame = CGRect(x: 0, y: 0, width: calcPoint.x, height: self.frame.height) if !isHandleHidden { if foregroundView.frame.width <= 0 { handleView.frame = CGRect(x: 0, y: borderWidth, width: handleWidth, height: foregroundView.frame.height - borderWidth) self.delegate?.sliderValueChanged(slider: self) // or use sliderValueChangeEnded method } else if foregroundView.frame.width >= self.frame.width { handleView.frame = CGRect(x: foregroundView.frame.width - handleWidth, y: borderWidth, width: handleWidth, height: foregroundView.frame.height - borderWidth * 2) self.delegate?.sliderValueChanged(slider: self) // or use sliderValueChangeEnded method } else { handleView.frame = CGRect(x: foregroundView.frame.width - handleWidth / 2, y: borderWidth, width: handleWidth, height: foregroundView.frame.height - borderWidth * 2) } } } } } // MARK: - Touch events extension FImageSlider { public override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { guard let touch = touches.first else { return } let point = touch.location(in: self) switch orientation { case .vertical: if !(point.y < 0) && !(point.y > self.frame.height) { changeStartForegroundView(withPoint: point) } case .horizontal: if !(point.x < 0) && !(point.x > self.frame.width) { changeStartForegroundView(withPoint: point) } } if point.x > 0 && point.x <= self.frame.width - handleWidth { delegate?.sliderValueChanged(slider: self) } } public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { guard let touch = touches.first else { return } let point = touch.location(in: self) UIView.animate(withDuration: animationDuration, animations: { self.changeStartForegroundView(withPoint: point) }) { (completed) in self.delegate?.sliderValueChangeEnded(slider: self) } } }
26756bea65a27d3b7fff933291ad13ae
23.396694
133
0.630759
false
false
false
false
zhangao0086/DKImageBrowserVC
refs/heads/master
DKPhotoGallery/Preview/DKPhotoContentAnimationView.swift
mit
1
// // DKPhotoContentAnimationView.swift // DKPhotoGallery // // Created by ZhangAo on 07/11/2017. // Copyright © 2017 ZhangAo. All rights reserved. // // Inspired by: https://github.com/patrickbdev/PBImageView/blob/master/PBImageView/Classes/PBImageView.swift // import UIKit open class DKPhotoContentAnimationView: UIView { let contentView: UIView let contentSize: CGSize init(image: UIImage?) { self.contentView = UIImageView(image: image) if let image = image { self.contentSize = image.size } else { self.contentSize = CGSize.zero } super.init(frame: CGRect.zero) self.addSubview(self.contentView) } init(view: UIView, contentSize: CGSize = CGSize.zero) { self.contentView = view if contentSize == CGSize.zero { self.contentSize = view.bounds.size } else { self.contentSize = contentSize } super.init(frame: CGRect.zero) self.addSubview(self.contentView) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } #if swift(>=4.2) open override var contentMode: UIView.ContentMode { didSet { self.layoutContentView() } } #else open override var contentMode: UIViewContentMode { didSet { self.layoutContentView() } } #endif override open func layoutSubviews() { super.layoutSubviews() self.layoutContentView() } open override var backgroundColor: UIColor? { get { return self.contentView.backgroundColor } set { self.contentView.backgroundColor = newValue } } private func layoutContentView() { guard self.contentSize != CGSize.zero else { return } // MARK: - Layout Helpers func imageToBoundsWidthRatio(size: CGSize) -> CGFloat { return size.width / bounds.size.width } func imageToBoundsHeightRatio(size: CGSize) -> CGFloat { return size.height / bounds.size.height } func centerImageViewToPoint(point: CGPoint) { self.contentView.center = point } func imageViewBoundsToImageSize() { imageViewBoundsToSize(size: self.contentSize) } func imageViewBoundsToSize(size: CGSize) { self.contentView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height) } func centerImageView() { self.contentView.center = CGPoint(x: bounds.size.width / 2, y: bounds.size.height / 2) } // MARK: - Layouts func layoutAspectFit() { let widthRatio = imageToBoundsWidthRatio(size: self.contentSize) let heightRatio = imageToBoundsHeightRatio(size: self.contentSize) imageViewBoundsToSize(size: CGSize(width: self.contentSize.width / max(widthRatio, heightRatio), height: self.contentSize.height / max(widthRatio, heightRatio))) centerImageView() } func layoutAspectFill() { let widthRatio = imageToBoundsWidthRatio(size: self.contentSize) let heightRatio = imageToBoundsHeightRatio(size: self.contentSize) imageViewBoundsToSize(size: CGSize(width: self.contentSize.width / min(widthRatio, heightRatio), height: self.contentSize.height / min(widthRatio, heightRatio))) centerImageView() } func layoutFill() { imageViewBoundsToSize(size: CGSize(width: bounds.size.width, height: bounds.size.height)) } func layoutCenter() { imageViewBoundsToImageSize() centerImageView() } func layoutTop() { imageViewBoundsToImageSize() centerImageViewToPoint(point: CGPoint(x: bounds.size.width / 2, y: self.contentSize.height / 2)) } func layoutBottom() { imageViewBoundsToImageSize() centerImageViewToPoint(point: CGPoint(x: bounds.size.width / 2, y: bounds.size.height - self.contentSize.height / 2)) } func layoutLeft() { imageViewBoundsToImageSize() centerImageViewToPoint(point: CGPoint(x: self.contentSize.width / 2, y: bounds.size.height / 2)) } func layoutRight() { imageViewBoundsToImageSize() centerImageViewToPoint(point: CGPoint(x: bounds.size.width - self.contentSize.width / 2, y: bounds.size.height / 2)) } func layoutTopLeft() { imageViewBoundsToImageSize() centerImageViewToPoint(point: CGPoint(x: self.contentSize.width / 2, y: self.contentSize.height / 2)) } func layoutTopRight() { imageViewBoundsToImageSize() centerImageViewToPoint(point: CGPoint(x: bounds.size.width - self.contentSize.width / 2, y: self.contentSize.height / 2)) } func layoutBottomLeft() { imageViewBoundsToImageSize() centerImageViewToPoint(point: CGPoint(x: self.contentSize.width / 2, y: bounds.size.height - self.contentSize.height / 2)) } func layoutBottomRight() { imageViewBoundsToImageSize() centerImageViewToPoint(point: CGPoint(x: bounds.size.width - self.contentSize.width / 2, y: bounds.size.height - self.contentSize.height / 2)) } switch contentMode { case .scaleAspectFit: layoutAspectFit() case .scaleAspectFill: layoutAspectFill() case .scaleToFill: layoutFill() case .redraw: break case .center: layoutCenter() case .top: layoutTop() case .bottom: layoutBottom() case .left: layoutLeft() case .right: layoutRight() case .topLeft: layoutTopLeft() case .topRight: layoutTopRight() case .bottomLeft: layoutBottomLeft() case .bottomRight: layoutBottomRight() } } }
541375acc63419fceb06e21061e2e966
37.018072
155
0.589764
false
false
false
false
BridgeTheGap/KRWalkThrough
refs/heads/master
KRWalkThrough/Classes/TutorialManager.swift
mit
1
// // TutorialManager.swift // Tutorial // // Created by Joshua Park on 5/27/16. // Copyright © 2016 Knowre. All rights reserved. // import UIKit open class TutorialManager: NSObject { open static let shared = TutorialManager() open var shouldShowTutorial = true open private(set) var items = [String: TutorialItem]() open private(set) var currentItem: TutorialItem? fileprivate let blankItem: TutorialItem fileprivate let transparentItem: TutorialItem fileprivate override init() { let blankView = TutorialView(frame: UIScreen.main.bounds) blankItem = TutorialItem(view: blankView, identifier: "blankItem") let transparentView = TutorialView(frame: UIScreen.main.bounds) transparentView.backgroundColor = UIColor.clear transparentItem = TutorialItem(view: transparentView, identifier: "transparentItem") } open func register(item: TutorialItem) { items[item.identifier] = item } open func deregister(item: TutorialItem) { items[item.identifier] = nil } open func deregisterAllItems() { for key in items.keys { items[key] = nil } } open func performNextAction() { currentItem?.nextAction?() } open func showTutorial(withIdentifier identifier: String) { guard shouldShowTutorial else { print("TutorialManager.shouldShowTutorial = false\nTutorial Manager will return without showing tutorial.") return } guard let window = UIApplication.shared.delegate?.window else { fatalError("UIApplication delegate's window is missing.") } guard let item = items[identifier] else { print("ERROR: \(TutorialManager.self) line #\(#line) - \(#function)\n** Reason: No registered item with identifier: \(identifier)") return } if blankItem.view.superview != nil { blankItem.view.removeFromSuperview() } if transparentItem.view.superview != nil { transparentItem.view.removeFromSuperview() } window?.addSubview(item.view) window?.setNeedsLayout() if currentItem?.view.superview != nil { currentItem?.view.removeFromSuperview() } currentItem = item } open func showBlankItem(withAction action: Bool = false) { UIApplication.shared.delegate!.window!!.addSubview(blankItem.view) UIApplication.shared.delegate!.window!!.setNeedsLayout() if action { currentItem?.nextAction?() } currentItem?.view.removeFromSuperview() currentItem = nil } open func showTransparentItem(withAction action: Bool = false) { UIApplication.shared.delegate!.window!!.addSubview(transparentItem.view) UIApplication.shared.delegate!.window!!.setNeedsLayout() if action { currentItem?.nextAction?() } currentItem?.view.removeFromSuperview() currentItem = nil } open func hideTutorial(withAction action: Bool = false) { if action { currentItem?.nextAction?() } currentItem?.view.removeFromSuperview() currentItem = nil } }
56d25d18d577a807bcd7746fed70ddaf
32.84375
143
0.643583
false
false
false
false
Egibide-DAM/swift
refs/heads/master
02_ejemplos/06_tipos_personalizados/03_propiedades/05_sintaxis_abreviada_setter.playground/Contents.swift
apache-2.0
1
struct Point { var x = 0.0, y = 0.0 } struct Size { var width = 0.0, height = 0.0 } struct AlternativeRect { var origin = Point() var size = Size() var center: Point { get { let centerX = origin.x + (size.width / 2) let centerY = origin.y + (size.height / 2) return Point(x: centerX, y: centerY) } set { origin.x = newValue.x - (size.width / 2) origin.y = newValue.y - (size.height / 2) } } }
62609f00667fe9347f8a9e6b5c924063
21.217391
54
0.48728
false
false
false
false
WangWenzhuang/ZKProgressHUD
refs/heads/master
Demo/Demo/ViewController.swift
mit
1
// // ViewController.swift // Demo // // Created by 王文壮 on 2017/3/10. // Copyright © 2017年 WangWenzhuang. All rights reserved. // import UIKit class ViewController: UITableViewController { var screenWidth: CGFloat { return UIScreen.main.bounds.size.width } let cellIdentifier = "cell" lazy var actionTexts = ["show", "show with status", "showProgress", "showProgress with status", "shwoImage", "showImage with status", "showInfo", "showSuccess", "showError", "showMessage", "showGif", "showGif with status"] lazy var headerTexts = ["动画显示/隐藏样式","遮罩样式", "加载样式", "方法", "其它"] var progressValue: CGFloat = 0 lazy var animationShowStyles = [(text: "fade", animationShowStyle: ZKProgressHUDAnimationShowStyle.fade), (text: "zoom", animationShowStyle: ZKProgressHUDAnimationShowStyle.zoom), (text: "flyInto", animationShowStyle: ZKProgressHUDAnimationShowStyle.flyInto)] var currentAnimationShowStyleIndex = 0 lazy var maskStyles = [(text: "visible", maskStyle: ZKProgressHUDMaskStyle.visible), (text: "hide", maskStyle: ZKProgressHUDMaskStyle.hide)] var currentMaskStyleIndex = 0 lazy var animationStyles = [(text: "circle", animationStyle: ZKProgressHUDAnimationStyle.circle), (text: "system", animationStyle: ZKProgressHUDAnimationStyle.system)] var currentAnimationStyleIndex = 0 override func viewDidLoad() { super.viewDidLoad() let backBarButtonItem = UIBarButtonItem() backBarButtonItem.title = "" self.navigationItem.backBarButtonItem = backBarButtonItem self.title = "ZKProgressHUD" self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: self.cellIdentifier) } override func numberOfSections(in tableView: UITableView) -> Int { return self.headerTexts.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 3: return self.actionTexts.count case 4: return 2 default: return 1 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = self.tableView.dequeueReusableCell(withIdentifier: self.cellIdentifier) cell?.accessoryType = .none if indexPath.section == 0 { cell?.textLabel?.text = self.animationShowStyles[self.currentAnimationShowStyleIndex].text cell?.accessoryType = .disclosureIndicator } else if indexPath.section == 1 { cell?.textLabel?.text = self.maskStyles[self.currentMaskStyleIndex].text cell?.accessoryType = .disclosureIndicator } else if indexPath.section == 2 { cell?.textLabel?.text = self.animationStyles[self.currentAnimationStyleIndex].text cell?.accessoryType = .disclosureIndicator } else if indexPath.section == 3 { cell?.textLabel?.text = self.actionTexts[indexPath.row] } else { if indexPath.row == 0 { cell?.textLabel?.text = "临时使用一次字体" } else { cell?.textLabel?.text = "临时使用一次自动消失时间" } } return cell! } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 50 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) if indexPath.section == 0 { self.pushSelectView(tag: 0, title: "选择动画显示/隐藏样式", data: self.animationShowStyles) } else if indexPath.section == 1 { self.pushSelectView(tag: 1, title: "选择遮罩样式", data: self.maskStyles) } else if indexPath.section == 2 { self.pushSelectView(tag: 2, title: "选择加载样式", data: self.animationStyles) } else if indexPath.section == 3 { if indexPath.row > 9 { ZKProgressHUD.setEffectStyle(.extraLight) } else { ZKProgressHUD.setEffectStyle(.dark) } if indexPath.row == 0 { ZKProgressHUD.show() ZKProgressHUD.dismiss(2.5) } else if indexPath.row == 1 { ZKProgressHUD.show("正在拼命的加载中🏃🏃🏃") DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + .seconds(2), execute: { DispatchQueue.main.async { ZKProgressHUD.dismiss() ZKProgressHUD.showInfo("加载完成😁😁😁") } }) } else if indexPath.row == 2 { Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(ViewController.showProgressTimerHandler(timer:)), userInfo: nil, repeats: true) } else if indexPath.row == 3 { Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(ViewController.showProgressTimerHandler(timer:)), userInfo: "上传中...", repeats: true) } else if indexPath.row == 4 { ZKProgressHUD.showImage(UIImage(named: "image")) } else if indexPath.row == 5 { ZKProgressHUD.showImage(UIImage(named: "image"), status: "图片会自动消失😏😏😏") } else if indexPath.row == 6 { ZKProgressHUD.showInfo("Star 一下吧😙😙😙") } else if indexPath.row == 7 { ZKProgressHUD.showSuccess("操作成功👏👏👏") } else if indexPath.row == 8 { ZKProgressHUD.showError("出现错误了😢😢😢") } else if indexPath.row == 9 { ZKProgressHUD.showMessage("开始使用 ZKProgressHUD 吧") } else if indexPath.row == 10 { ZKProgressHUD.showGif(gifUrl: Bundle.main.url(forResource: "loding", withExtension: "gif"), gifSize: 80) ZKProgressHUD.dismiss(2) } else if indexPath.row == 11 { ZKProgressHUD.showGif(gifUrl: Bundle.main.url(forResource: "loding", withExtension: "gif"), gifSize: 80, status: "正在拼命的加载中🏃🏃🏃") ZKProgressHUD.dismiss(2) } } else if indexPath.section == 4 { if indexPath.row == 0 { ZKProgressHUD.showMessage("临时使用一次字体", onlyOnceFont: UIFont.boldSystemFont(ofSize: 20)) } else { ZKProgressHUD.showMessage("临时使用一次自动消失时间:10秒", autoDismissDelay: 10) } } } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return self.headerTexts[section] } @objc func showProgressTimerHandler(timer: Timer) { if self.progressValue >= 100 { if timer.isValid { timer.invalidate() } ZKProgressHUD.dismiss() self.progressValue = 0 } else { self.progressValue += 5 if let status = timer.userInfo { ZKProgressHUD.showProgress(self.progressValue / 100, status: status as? String) } else { ZKProgressHUD.showProgress(self.progressValue / 100) } } } func pushSelectView(tag: Int, title: String, data: [Any]) { let selectViewController = SelectViewController() selectViewController.tag = tag selectViewController.title = title selectViewController.data = data selectViewController.delegate = self self.navigationController?.pushViewController(selectViewController, animated: true) } } extension ViewController: SelectViewControllerDelegate { func selected(selectViewController: SelectViewController, selectIndex: Int) { if selectViewController.tag == 0 { self.currentAnimationShowStyleIndex = selectIndex ZKProgressHUD.setAnimationShowStyle(self.animationShowStyles[self.currentAnimationShowStyleIndex].animationShowStyle) } else if selectViewController.tag == 1 { self.currentMaskStyleIndex = selectIndex ZKProgressHUD.setMaskStyle(self.maskStyles[self.currentMaskStyleIndex].maskStyle) } else { self.currentAnimationStyleIndex = selectIndex ZKProgressHUD.setAnimationStyle(self.animationStyles[self.currentAnimationStyleIndex].animationStyle) } self.tableView.reloadData() } func tableViewCellValue(selectViewController: SelectViewController, obj: Any) -> (text: String, isCheckmark: Bool) { if selectViewController.tag == 0 { let animationShowStyle = obj as! (text: String, animationShowStyle: ZKProgressHUDAnimationShowStyle) return (text: animationShowStyle.text, isCheckmark: animationShowStyle.text == self.animationShowStyles[self.currentAnimationShowStyleIndex].text) } else if selectViewController.tag == 1 { let maskStyle = obj as! (text: String, maskStyle: ZKProgressHUDMaskStyle) return (text: maskStyle.text, isCheckmark: maskStyle.text == self.maskStyles[self.currentMaskStyleIndex].text) } else { let animationStyle = obj as! (text: String, animationStyle: ZKProgressHUDAnimationStyle) return (text: animationStyle.text, isCheckmark: animationStyle.text == self.animationStyles[self.currentAnimationStyleIndex].text) } } }
4d47abe4dc9e563a56d74b73d16e40e4
45.960199
263
0.632164
false
false
false
false
firebase/firebase-ios-sdk
refs/heads/master
scripts/health_metrics/generate_code_coverage_report/Sources/BinarySizeReportGenerator/BinarySizeReportGeneration.swift
apache-2.0
1
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import ArgumentParser import Foundation import Utils private enum Constants {} extension Constants { // Binary Size Metrics flag for the Metrics Service. static let metric = "BinarySize" static let cocoapodSizeReportFile = "binary_report.json" } /// Pod Config struct PodConfigs: Codable { let pods: [Pod] } struct Pod: Codable { let sdk: String let path: String } /// Cocoapods-size tool report, struct SDKBinaryReport: Codable { let combinedPodsExtraSize: Int enum CodingKeys: String, CodingKey { case combinedPodsExtraSize = "combined_pods_extra_size" } } /// Metrics Service API request data public struct BinaryMetricsReport: Codable { let metric: String let results: [Result] let log: String } public struct Result: Codable { let sdk, type: String let value: Int } extension BinaryMetricsReport { func toData() -> Data { let jsonData = try! JSONEncoder().encode(self) return jsonData } } func CreatePodConfigJSON(of sdks: [String], from sdk_dir: URL) throws { var pods: [Pod] = [] for sdk in sdks { let pod = Pod(sdk: sdk, path: sdk_dir.path) pods.append(pod) } let podConfigs = PodConfigs(pods: pods) try JSONParser.writeJSON(of: podConfigs, to: "./cocoapods_source_config.json") } // Create a JSON format data prepared to send to the Metrics Service. func CreateMetricsRequestData(of sdks: [String], type: String, log: String) throws -> BinaryMetricsReport { var reports: [Result] = [] // Create a report for each individual SDK and collect all of them into reports. for sdk in sdks { // Create a report, generated by cocoapods-size, for each SDK. `.stdout` is used // since `pipe` could cause the tool to hang. That is probably caused by cocopod-size // is using pipe and a pipe is shared by multiple parent/child process and cause // deadlock. `.stdout` is a quick way to resolve at the moment. The difference is // that `.stdout` will print out logs in the console while pipe can assign logs a // variable. Shell.run( "cd cocoapods-size && python3 measure_cocoapod_size.py --cocoapods \(sdk) --spec_repos specsstaging master --cocoapods_source_config ../cocoapods_source_config.json --json \(Constants.cocoapodSizeReportFile)", stdout: .stdout ) let SDKBinarySize = try JSONParser.readJSON( of: SDKBinaryReport.self, from: "cocoapods-size/\(Constants.cocoapodSizeReportFile)" ) // Append reports for data for API request to the Metrics Service. reports.append(Result(sdk: sdk, type: type, value: SDKBinarySize.combinedPodsExtraSize)) } let metricsRequestReport = BinaryMetricsReport( metric: Constants.metric, results: reports, log: log ) return metricsRequestReport } public func CreateMetricsRequestData(SDK: [String], SDKRepoDir: URL, logPath: String) throws -> BinaryMetricsReport? { try CreatePodConfigJSON(of: SDK, from: SDKRepoDir) let data = try CreateMetricsRequestData( of: SDK, type: "CocoaPods", log: logPath ) return data }
6a37a28ed60d67ef9ca8dd988e68137b
30.649573
215
0.704294
false
true
false
false
narner/AudioKit
refs/heads/master
Playgrounds/AudioKitPlaygrounds/Playgrounds/Effects.playground/Pages/Flat Frequency Response Reverb.xcplaygroundpage/Contents.swift
mit
1
//: ## Flat Frequency Response Reverb //: import AudioKitPlaygrounds import AudioKit let file = try AKAudioFile(readFileName: playgroundAudioFiles[0]) let player = try AKAudioPlayer(file: file) player.looping = true var reverb = AKFlatFrequencyResponseReverb(player, loopDuration: 0.1) reverb.reverbDuration = 1 AudioKit.output = reverb AudioKit.start() player.play() //: User Interface Set up import AudioKitUI class LiveView: AKLiveViewController { override func viewDidLoad() { addTitle("Flat Frequency Response Reverb") addView(AKResourcesAudioFileLoaderView(player: player, filenames: playgroundAudioFiles)) addView(AKSlider(property: "Duration", value: reverb.reverbDuration, range: 0 ... 5) { sliderValue in reverb.reverbDuration = sliderValue }) } } import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true PlaygroundPage.current.liveView = LiveView()
e424eb989300897a6778fbe4f8d875dd
25.25
109
0.752381
false
false
false
false
laurentVeliscek/AudioKit
refs/heads/master
AudioKit/Common/Playgrounds/Synthesis.playground/Pages/Noise Generators.xcplaygroundpage/Contents.swift
mit
2
//: ## Pink and White Noise Generators //: import XCPlayground import AudioKit var white = AKWhiteNoise(amplitude: 0.1) var pink = AKPinkNoise(amplitude: 0.1) var whitePinkMixer = AKDryWetMixer(white, pink, balance: 0.5) AudioKit.output = whitePinkMixer AudioKit.start() pink.start() white.start() //: User Interface Set up class PlaygroundView: AKPlaygroundView { override func setup() { addTitle("Pink and White Noise") addSubview(AKPropertySlider( property: "Volume", format: "%0.2f", value: pink.amplitude, color: AKColor.cyanColor() ) { amplitude in pink.amplitude = amplitude white.amplitude = amplitude }) addSubview(AKPropertySlider( property: "White to Pink Balance", format: "%0.2f", value: whitePinkMixer.balance, color: AKColor.magentaColor() ) { balance in whitePinkMixer.balance = balance }) } } XCPlaygroundPage.currentPage.needsIndefiniteExecution = true XCPlaygroundPage.currentPage.liveView = PlaygroundView()
beb32c0fbdc81ee830b056572be01526
24.355556
61
0.629273
false
false
false
false
oisdk/ProtocolTester
refs/heads/master
ProtocolTesterTests/RangeReplaceableCollectionType.swift
mit
1
import XCTest import Foundation extension RangeReplaceableCollectionType where Self : SameOrder, Self : MutableSliceable, Generator.Element == Int, SubSequence.Generator.Element == Int, SubSequence : FlexibleInitable { static func test() { testMultiPass() testCount() testSeqInit() testSameEls() testIndexing() testFirst() testRangeIndexing() testSplit() testMutIndexing() testMutIndexSlicing() testEmptyInit() testReplaceRange() } static internal func testEmptyInit() { let empty = Self() XCTAssert(empty.isEmpty, "Empty initializer did not yield empty self.\nReceived: \(Array(empty))") } static internal func testReplaceRange() { for randAr in randArs() { let seq = Self(randAr) for (iA, iS) in zip(randAr.indices, seq.indices) { for (jA, jS) in zip(iA..<randAr.endIndex, iS..<seq.endIndex) { var mutAr = randAr var mutSe = seq let replacement = (0..<arc4random_uniform(10)).map { _ in Int(arc4random_uniform(10000)) } mutAr.replaceRange(iA...jA, with: replacement) mutSe.replaceRange(iS...jS, with: replacement) XCTAssert(mutAr.elementsEqual(mutSe), "Range subscript replacement did not produce expected result.\nInitialized from array: \(randAr)\nTried to replace range: \(iA...jA) with \(replacement)\nExpected: \(mutAr)\nReceived: \(Array(mutSe))") XCTAssert(mutSe.invariantPassed, "Invariant broken: \(Array(mutSe))") } } } } }
cf7d3f5b2559330ba4825d3231387b66
33.704545
249
0.661861
false
true
false
false
jengelsma/cis657-summer2016-class-demos
refs/heads/master
Lecture12-PuppyFlixDemoWithUnitTests/PuppyFlix/VideoInfo.swift
mit
1
// // VideoInfo.swift // PuppyFlix // // Created by Jonathan Engelsma on 11/20/15. // Copyright © 2015 Jonathan Engelsma. All rights reserved. // import Foundation class VideoInfo : Equatable { let id:String let title:String let description:String let smallImageUrl:String? let mediumImageUrl:String? init(id: String, title: String, description: String, smallImageUrl: String?, mediumImageUrl: String?) { self.id = id; self.title = title; self.description = description self.smallImageUrl = smallImageUrl self.mediumImageUrl = mediumImageUrl } } func ==(lhs: VideoInfo, rhs: VideoInfo) -> Bool { return lhs.id == rhs.id && lhs.title == rhs.title && lhs.description == rhs.description && lhs.smallImageUrl == rhs.smallImageUrl && lhs.mediumImageUrl == rhs.mediumImageUrl }
7fec3d9261c5cbad4b06f0def956938e
23.324324
107
0.642222
false
false
false
false
zhangjk4859/MyWeiBoProject
refs/heads/master
sinaWeibo/sinaWeibo/Classes/Compose/表情选择器/EmoticonTextAttachment.swift
mit
1
// // EmoticonTextAttachment.swift // sinaWeibo // // Created by 张俊凯 on 16/7/27. // Copyright © 2016年 张俊凯. All rights reserved. // import UIKit class EmoticonTextAttachment: NSTextAttachment { // 保存对应表情的文字 var chs: String? /// 根据表情模型, 创建表情字符串 class func imageText(emoticon: Emoticon, font: UIFont) -> NSAttributedString{ // 1.创建附件 let attachment = EmoticonTextAttachment() attachment.chs = emoticon.chs attachment.image = UIImage(contentsOfFile: emoticon.imagePath!) // 设置了附件的大小 let s = font.lineHeight attachment.bounds = CGRectMake(0, -4, s, s) // 2. 根据附件创建属性字符串 return NSAttributedString(attachment: attachment) } }
7111fa6d32d5f8e88d661d4804558a0e
24.517241
81
0.632432
false
false
false
false
tryswift/TryParsec
refs/heads/swift/4.0
excludedTests/TryParsec/Specs/HelperSpec.swift
mit
1
@testable import TryParsec import Result import Quick import Nimble class HelperSpec: QuickSpec { override func spec() { describe("splitAt") { it("splitAt(1)") { let (heads, tails) = splitAt(1)("abc" as USV) expect(String(heads).unicodeScalars) == ["a"] expect(String(tails).unicodeScalars) == ["b", "c"] } it("splitAt(0)") { let (heads, tails) = splitAt(0)("abc" as USV) expect(String(heads).unicodeScalars) == [] expect(String(tails).unicodeScalars) == ["a", "b", "c"] } it("splitAt(999)") { let (heads, tails) = splitAt(999)("abc" as USV) expect(String(heads).unicodeScalars) == ["a", "b", "c"] expect(String(tails).unicodeScalars) == [] } it("splitAt(0)(\"\")") { let (heads, tails) = splitAt(0)("" as USV) expect(String(heads).unicodeScalars) == [] expect(String(tails).unicodeScalars) == [] } } describe("trim") { it("trims head & tail whitespaces") { let trimmed = trim(" Trim me! ") expect(trimmed) == "Trim me!" } it("doesn't trim middle whitespaces") { let trimmed = trim("Dooooon't trrrrrim meeeee!") expect(trimmed) == "Dooooon't trrrrrim meeeee!" } } describe("RangeReplaceableCollectionType (RRC)") { it("any RRC e.g. `ArraySlice` can initialize with SequenceType") { let arr = ArraySlice<UnicodeScalar>("abc" as USV) expect(Array(arr)) == Array(["a", "b", "c"]) } } } }
6dfd4bdefe907c11ad32e3e37552f1e7
29.032787
78
0.465611
false
false
false
false
Elm-Tree-Island/Shower
refs/heads/master
Carthage/Checkouts/ReactiveCocoa/ReactiveCocoaTests/AppKit/NSCollectionViewSpec.swift
gpl-3.0
7
import Quick import Nimble import ReactiveCocoa import ReactiveSwift import Result import AppKit @available(macOS 10.11, *) final class NSCollectionViewSpec: QuickSpec { override func spec() { var collectionView: TestCollectionView! beforeEach { collectionView = TestCollectionView() } describe("reloadData") { var bindingSignal: Signal<(), NoError>! var bindingObserver: Signal<(), NoError>.Observer! var reloadDataCount = 0 beforeEach { let (signal, observer) = Signal<(), NoError>.pipe() (bindingSignal, bindingObserver) = (signal, observer) reloadDataCount = 0 collectionView.reloadDataSignal.observeValues { reloadDataCount += 1 } } it("invokes reloadData whenever the bound signal sends a value") { collectionView.reactive.reloadData <~ bindingSignal bindingObserver.send(value: ()) bindingObserver.send(value: ()) expect(reloadDataCount) == 2 } } } } @available(macOS 10.11, *) private final class TestCollectionView: NSCollectionView { let reloadDataSignal: Signal<(), NoError> private let reloadDataObserver: Signal<(), NoError>.Observer override init(frame: CGRect) { (reloadDataSignal, reloadDataObserver) = Signal.pipe() super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { (reloadDataSignal, reloadDataObserver) = Signal.pipe() super.init(coder: aDecoder) } override func reloadData() { super.reloadData() reloadDataObserver.send(value: ()) } }
8f7d041465795aa6a9997732a543870c
21.846154
69
0.717845
false
false
false
false
material-motion/motion-transitioning-objc
refs/heads/develop
examples/PhotoAlbumTransition.swift
apache-2.0
2
/* Copyright 2017-present The Material Motion Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import UIKit import MotionTransitioning protocol PhotoAlbumTransitionForeDelegate: class { func foreContextView(for transition: PhotoAlbumTransition) -> UIImageView? func toolbar(for transition: PhotoAlbumTransition) -> UIToolbar? } protocol PhotoAlbumTransitionBackDelegate: class { func backContextView(for transition: PhotoAlbumTransition, with foreViewController: UIViewController) -> UIImageView? } final class PhotoAlbumTransition: NSObject, Transition, TransitionWithFeasibility { weak var backDelegate: PhotoAlbumTransitionBackDelegate? weak var foreDelegate: PhotoAlbumTransitionForeDelegate? init(backDelegate: PhotoAlbumTransitionBackDelegate, foreDelegate: PhotoAlbumTransitionForeDelegate) { self.backDelegate = backDelegate self.foreDelegate = foreDelegate } func canPerformTransition(with context: TransitionContext) -> Bool { guard let backDelegate = backDelegate else { return false } return backDelegate.backContextView(for: self, with: context.foreViewController) != nil } func start(with context: TransitionContext) { guard let backDelegate = backDelegate, let foreDelegate = foreDelegate else { return } guard let contextView = backDelegate.backContextView(for: self, with: context.foreViewController) else { return } guard let foreImageView = foreDelegate.foreContextView(for: self) else { return } let snapshotter = TransitionViewSnapshotter(containerView: context.containerView) context.defer { snapshotter.removeAllSnapshots() } foreImageView.isHidden = true context.defer { foreImageView.isHidden = false } let imageSize = foreImageView.image!.size let fitScale = min(foreImageView.bounds.width / imageSize.width, foreImageView.bounds.height / imageSize.height) let fitSize = CGSize(width: fitScale * imageSize.width, height: fitScale * imageSize.height) let snapshotContextView = snapshotter.snapshot(of: contextView, isAppearing: context.direction == .backward) context.compose(with: FadeTransition(target: .foreView, style: .fadeIn)) context.compose(with: SpringFrameTransition(target: .target(snapshotContextView), size: fitSize)) if let toolbar = foreDelegate.toolbar(for: self) { context.compose(with: SlideUpTransition(target: .target(toolbar))) } // This transition doesn't directly produce any animations, so we inform the context that it is // complete here, otherwise the transition would never complete: context.transitionDidEnd() } }
360e65041b7fc3abe776826529219cde
37.366667
99
0.706922
false
false
false
false
remirobert/Dotzu
refs/heads/master
Framework/Dotzu/Dotzu/StoreManager.swift
mit
2
// // LogManager.swift // exampleWindow // // Created by Remi Robert on 17/01/2017. // Copyright © 2017 Remi Robert. All rights reserved. // import Foundation enum StoreManagerType: String { case log = "logs" case network = "network" case crash = "crashs" } class StoreManager<T> where T: NSCoding { private let store: StoreManagerType init(store: StoreManagerType) { self.store = store } private func archiveLogs(logs: [T]) { let dataArchive = NSKeyedArchiver.archivedData(withRootObject: logs) UserDefaults.standard.set(dataArchive, forKey: store.rawValue) UserDefaults.standard.synchronize() } func add(log: T) { var logs = self.logs() logs.append(log) archiveLogs(logs: logs) } func save(logs: [T]) { archiveLogs(logs: logs) } func logs() -> [T] { guard let data = UserDefaults.standard.object(forKey: store.rawValue) as? NSData else {return []} do { let dataArchive = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) return dataArchive as? [T] ?? [] } catch { return [] } } func reset() { UserDefaults.standard.removeObject(forKey: store.rawValue) UserDefaults.standard.synchronize() } }
ff98d2864f015f8bf68856eb31713095
23.181818
105
0.618045
false
false
false
false
ntnmrndn/R.swift
refs/heads/master
Sources/RswiftCore/SwiftTypes/Struct.swift
mit
2
// // Struct.swift // R.swift // // Created by Mathijs Kadijk on 10-12-15. // From: https://github.com/mac-cain13/R.swift // License: MIT License // import Foundation struct Struct: UsedTypesProvider, SwiftCodeConverible { let availables: [String] let comments: [String] let accessModifier: AccessLevel let type: Type var implements: [TypePrinter] let typealiasses: [Typealias] var properties: [Let] var functions: [Function] var structs: [Struct] var classes: [Class] var isEmpty: Bool { return properties.isEmpty && functions.isEmpty && (structs.isEmpty || structs.all { $0.isEmpty }) && classes.isEmpty } var usedTypes: [UsedType] { return [ type.usedTypes, implements.flatMap(getUsedTypes), typealiasses.flatMap(getUsedTypes), properties.flatMap(getUsedTypes), functions.flatMap(getUsedTypes), structs.flatMap(getUsedTypes), ] .joined() .array() } var swiftCode: String { let commentsString = comments.map { "/// \($0)\n" }.joined(separator: "") let availablesString = availables.map { "@available(\($0))\n" }.joined(separator: "") let accessModifierString = accessModifier.swiftCode let implementsString = implements.count > 0 ? ": " + implements.map { $0.swiftCode }.joined(separator: ", ") : "" let typealiasString = typealiasses .sorted { $0.alias < $1.alias } .map { $0.description } .joined(separator: "\n") let varsString = properties .map { $0.swiftCode } .sorted() .map { $0.description } .joined(separator: "\n") let functionsString = functions .map { $0.swiftCode } .sorted() .map { $0.description } .joined(separator: "\n\n") let structsString = structs .map { $0.swiftCode } .sorted() .map { $0.description } .joined(separator: "\n\n") let classesString = classes .map { $0.swiftCode } .sorted() .map { $0.description } .joined(separator: "\n\n") // File private `init`, so that struct can't be initialized from the outside world let fileprivateInit = "fileprivate init() {}" let bodyComponents = [typealiasString, varsString, functionsString, structsString, classesString, fileprivateInit].filter { $0 != "" } let bodyString = bodyComponents.joined(separator: "\n\n").indent(with: " ") return "\(commentsString)\(availablesString)\(accessModifierString)struct \(type)\(implementsString) {\n\(bodyString)\n}" } }
29ec0db92bb63814b56a28b84bec22d6
28.275862
138
0.632116
false
false
false
false
banxi1988/Staff
refs/heads/master
Staff/AppDelegate.swift
mit
1
// // AppDelegate.swift // Staff // // Created by Haizhen Lee on 16/2/29. // Copyright © 2016年 banxi1988. All rights reserved. // import UIKit import BXiOSUtils import SwiftyBeaver let log = SwiftyBeaver.self let Images = UIImage.Asset.self @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. window = UIWindow(frame: UIScreen.mainScreen().bounds) setupLog() setUpAppearanceProxy() AppUserDefaults.registerDefaults() setupLocalNotification() start() return true } func start(){ log.debug("start") window?.rootViewController = startEntry() window?.makeKeyAndVisible() log.debug("makeKeyAndVisible Down") } func startEntry() -> UIViewController{ #if DEBUG // return currentDebugEntry() #endif let vc = MainViewController() return UINavigationController(rootViewController: vc) } func currentDebugEntry() -> UIViewController{ // let vc = CompanyGeoRegionPickerViewController() // let vc = SettingsViewController() let vc = ArtClockViewController() return UINavigationController(rootViewController: vc) } func setupLocalNotification(){ let app = UIApplication.sharedApplication() let settings = UIUserNotificationSettings(forTypes: [.Sound,.Alert,.Badge], categories: nil) app.registerUserNotificationSettings(settings) app.cancelAllLocalNotifications() } func setupLog(){ let file = FileDestination() // log to default swiftybeaver.log file #if DEBUG // add log destinations. at least one is needed! let console = ConsoleDestination() // log to Xcode Console log.addDestination(console) file.minLevel = .Debug #else file.minLevel = .Info #endif log.addDestination(file) } func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) { log.info("notification:\(notification)") } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
0693992a2c9ce50952775ac1da3646d0
34.111111
281
0.743935
false
false
false
false
imzyf/99-projects-of-swift
refs/heads/master
021-marslink/Marslink/SectionControllers/MessageSectionController.swift
mit
1
// // MessageSectionController.swift // Marslink // // Created by moma on 2017/11/23. // Copyright © 2017年 Ray Wenderlich. All rights reserved. // import UIKit import IGListKit class MessageSectionController: IGListSectionController { var message: Message! override init() { super.init() inset = UIEdgeInsets(top: 0, left: 0, bottom: 15, right: 0) } } extension MessageSectionController: IGListSectionType { func numberOfItems() -> Int { return 1 } func sizeForItem(at index: Int) -> CGSize { guard let context = collectionContext else { return .zero } return MessageCell.cellSize(width: context.containerSize.width, text: message.text) } func cellForItem(at index: Int) -> UICollectionViewCell { let cell = collectionContext?.dequeueReusableCell(of: MessageCell.self, for: self, at: index) as! MessageCell cell.messageLabel.text = message.text cell.titleLabel.text = message.user.name.uppercased() return cell } func didUpdate(to object: Any) { message = object as? Message } func didSelectItem(at index: Int) {} }
329ab2c6f23020e703cdb3145b619e23
25.863636
117
0.653976
false
false
false
false
witekbobrowski/Stanford-CS193p-Winter-2017
refs/heads/master
Faceit/Faceit/EmotionsViewController.swift
mit
1
// // EmotionsViewController.swift // Faceit // // Created by Witek on 24/04/2017. // Copyright © 2017 Witek Bobrowski. All rights reserved. // import UIKit class EmotionsViewController: UITableViewController { fileprivate var emotionalFaces: [(name: String, expression: FacialExpression)] = [ ("sad", FacialExpression(eyes: .closed, mouth: .frown)), ("happy", FacialExpression(eyes: .open, mouth: .smile)), ("worried", FacialExpression(eyes: .open, mouth: .smirk)) ] @IBAction func addEmotionalFace(from segue: UIStoryboardSegue) { if let editor = segue.source as? ExpressionEditorViewController { emotionalFaces.append((editor.name, editor.expression)) tableView.reloadData() } } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { var destinationViewController = segue.destination if let navigationController = destinationViewController as? UINavigationController { destinationViewController = navigationController.visibleViewController ?? destinationViewController } if let faceViewController = destinationViewController as? FaceViewController, let cell = sender as? UITableViewCell, let indexPath = tableView.indexPath(for: cell) { faceViewController.expression = emotionalFaces[indexPath.row].expression faceViewController.navigationItem.title = (sender as? UIButton)?.currentTitle } else if destinationViewController is ExpressionEditorViewController { if let popoverPresentationController = segue.destination.popoverPresentationController { popoverPresentationController.delegate = self } } } } extension EmotionsViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return emotionalFaces.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Emotion Cell", for: indexPath) cell.textLabel?.text = emotionalFaces[indexPath.row].name return cell } } extension EmotionsViewController: UIPopoverPresentationControllerDelegate { func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { if traitCollection.verticalSizeClass == .compact { return .none } else if traitCollection.horizontalSizeClass == .compact { return .overFullScreen } else { return .none } } }
12536200dcc4c04300bedaee49e75657
37.164384
142
0.685212
false
false
false
false
ymkjp/NewsPlayer
refs/heads/master
NewsPlayer/VideoTableViewCell.swift
mit
1
// // VideoTableViewCell.swift // NewsPlayer // // Created by YAMAMOTOKenta on 9/19/15. // Copyright © 2015 ymkjp. All rights reserved. // import UIKit import FLAnimatedImage class VideoTableViewCell: UITableViewCell { @IBOutlet weak var thumbnail: UIImageView! @IBOutlet weak var abstract: UILabel! @IBOutlet weak var indicator: UIView! let animatedImageView = FLAnimatedImageView() override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } // :param: index Let them know the indexPath.row, cell does not remember wchich indexPath it belongs func render(index: Int) -> VideoTableViewCell { if let video = ChannelModel.sharedInstance.getVideoByIndex(index) { abstract?.numberOfLines = 0 abstract?.text = "\(video.title)\n\(video.description)" thumbnail?.sd_setImageWithURL(NSURL(string: video.thumbnail.url)) } else { abstract.text = "textLabel #\(index)" } return self } func addPlayingIndicator() { indicator?.addSubview(createIndicationView()) } func removeAllIndicator() { guard let subviews = indicator?.subviews else { return } for subview in subviews { subview.removeFromSuperview() } } func startPlayingAnimation() { animatedImageView.startAnimating() } func stopPlayingAnimation() { animatedImageView.stopAnimating() } private func createIndicationView() -> UIImageView { let path = NSBundle.mainBundle().pathForResource("equalizer", ofType: "gif")! let url = NSURL(fileURLWithPath: path) let animatedImage = FLAnimatedImage(animatedGIFData: NSData(contentsOfURL: url)) animatedImageView.animatedImage = animatedImage animatedImageView.frame = indicator.bounds animatedImageView.contentMode = UIViewContentMode.ScaleAspectFit return animatedImageView } }
3dd4dbbab722f13cbf469170f8455bb7
29.39726
104
0.653898
false
false
false
false
apatronl/Left
refs/heads/master
Left/Services/FavoritesManager.swift
mit
1
// // FavoritesManager.swift // Left // // Created by Alejandrina Patron on 3/4/16. // Copyright © 2016 Ale Patrón. All rights reserved. // import Foundation class FavoritesManager { // Singleton static let shared = FavoritesManager() private var favoriteRecipes = [RecipeItem]() func addRecipe(recipe: RecipeItem) { favoriteRecipes.append(recipe) save() } func deleteRecipeAtIndex(index: Int) { favoriteRecipes.remove(at: index) save() } func recipeAtIndex(index: Int) -> RecipeItem? { return favoriteRecipes[index] } func recipeCount() -> Int { return favoriteRecipes.count } func archivePath() -> String? { let directoryList = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) if let documentsPath = directoryList.first { return documentsPath + "/Favorites" } assertionFailure("Could not determine where to save file.") return nil } func save() { if let theArchivePath = archivePath() { if NSKeyedArchiver.archiveRootObject(favoriteRecipes, toFile: theArchivePath) { print("We saved!") } else { assertionFailure("Could not save to \(theArchivePath)") } } } func unarchivedSavedItems() { if let theArchivePath = archivePath() { if FileManager.default.fileExists(atPath: theArchivePath) { favoriteRecipes = NSKeyedUnarchiver.unarchiveObject(withFile: theArchivePath) as! [RecipeItem] } } } init() { unarchivedSavedItems() } }
9b80d897e5ec638db8a2df7bde68969f
25.30303
110
0.599078
false
false
false
false
OscarSwanros/swift
refs/heads/master
test/SwiftSyntax/SyntaxFactory.swift
apache-2.0
2
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: OS=macosx // REQUIRES: sdk_overlay import Foundation import StdlibUnittest import SwiftSyntax func cannedStructDecl() -> StructDeclSyntax { let fooID = SyntaxFactory.makeIdentifier("Foo", trailingTrivia: .spaces(1)) let structKW = SyntaxFactory.makeStructKeyword(trailingTrivia: .spaces(1)) let rBrace = SyntaxFactory.makeRightBraceToken(leadingTrivia: .newlines(1)) return StructDeclSyntax { $0.useStructKeyword(structKW) $0.useIdentifier(fooID) $0.useLeftBrace(SyntaxFactory.makeLeftBraceToken()) $0.useRightBrace(rBrace) } } var SyntaxFactoryAPI = TestSuite("SyntaxFactoryAPI") SyntaxFactoryAPI.test("Generated") { let structDecl = cannedStructDecl() expectEqual("\(structDecl)", """ struct Foo { } """) let forType = SyntaxFactory.makeIdentifier("for", leadingTrivia: .backticks(1), trailingTrivia: [ .backticks(1), .spaces(1) ]) let newBrace = SyntaxFactory.makeRightBraceToken(leadingTrivia: .newlines(2)) let renamed = structDecl.withIdentifier(forType) .withRightBrace(newBrace) expectEqual("\(renamed)", """ struct `for` { } """) expectNotEqual(structDecl.leftBrace, renamed.leftBrace) expectEqual(structDecl, structDecl.root) expectNil(structDecl.parent) expectNotNil(structDecl.leftBrace.parent) expectEqual(structDecl.leftBrace.parent, structDecl) // Ensure that accessing children via named identifiers is exactly the // same as accessing them as their underlying data. expectEqual(structDecl.leftBrace, structDecl.child(at: 7)) expectEqual("\(structDecl.rightBrace)", """ } """) } SyntaxFactoryAPI.test("TokenSyntax") { let tok = SyntaxFactory.makeStructKeyword() expectEqual("\(tok)", "struct") expectTrue(tok.isPresent) let preSpacedTok = tok.withLeadingTrivia(.spaces(3)) expectEqual("\(preSpacedTok)", " struct") let postSpacedTok = tok.withTrailingTrivia(.spaces(6)) expectEqual("\(postSpacedTok)", "struct ") let prePostSpacedTok = preSpacedTok.withTrailingTrivia(.spaces(4)) expectEqual("\(prePostSpacedTok)", " struct ") } SyntaxFactoryAPI.test("FunctionCallSyntaxBuilder") { let string = SyntaxFactory.makeStringLiteralExpr("Hello, world!") let printID = SyntaxFactory.makeVariableExpr("print") let arg = FunctionCallArgumentSyntax { $0.useExpression(string) } let call = FunctionCallExprSyntax { $0.useCalledExpression(printID) $0.useLeftParen(SyntaxFactory.makeLeftParenToken()) $0.addFunctionCallArgument(arg) $0.useRightParen(SyntaxFactory.makeRightParenToken()) } expectEqual("\(call)", "print(\"Hello, world!\")") let terminatorArg = FunctionCallArgumentSyntax { $0.useLabel(SyntaxFactory.makeIdentifier("terminator")) $0.useColon(SyntaxFactory.makeColonToken(trailingTrivia: .spaces(1))) $0.useExpression(SyntaxFactory.makeStringLiteralExpr(" ")) } let callWithTerminator = call.withArgumentList( SyntaxFactory.makeFunctionCallArgumentList([ arg.withTrailingComma( SyntaxFactory.makeCommaToken(trailingTrivia: .spaces(1))), terminatorArg ]) ) expectEqual("\(callWithTerminator)", "print(\"Hello, world!\", terminator: \" \")") } runAllTests()
bf17512ad0a3c8805bd89b0ce3092d05
30.745614
79
0.661232
false
true
false
false
naoty/qiita-swift
refs/heads/master
Qiita/Qiita/Item.swift
mit
1
// // Item.swift // Qiita // // Created by Naoto Kaneko on 2014/12/13. // Copyright (c) 2014年 Naoto Kaneko. All rights reserved. // extension Qiita { public class Item { public let body: String? public let coediting: Bool? public let createdAt: NSDate? public let id: String? public let isPrivate: Bool? public let title: String? public let updatedAt: NSDate? public let url: NSURL? public let user: User? private var dateFormatter: NSDateFormatter { let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" return formatter } public init?(json: AnyObject) { if let jsonObject = json as? NSDictionary { if let body = jsonObject["body"] as? String { self.body = body } if let coediting = jsonObject["coediting"] as? Bool { self.coediting = coediting } if let createdAtTimestamp = jsonObject["created_at"] as? String { self.createdAt = dateFormatter.dateFromString(createdAtTimestamp) } if let id = jsonObject["id"] as? String { self.id = id } if let isPrivate = jsonObject["private"] as? Bool { self.isPrivate = isPrivate } if let title = jsonObject["title"] as? String { self.title = title } if let updatedAtTimestamp = jsonObject["updated_at"] as? String { self.updatedAt = dateFormatter.dateFromString(updatedAtTimestamp) } if let urlString = jsonObject["url"] as? String { self.url = NSURL(string: urlString)! } if let userJSONObject: AnyObject = jsonObject["user"] { self.user = User(json: userJSONObject) } } else { return nil } } } }
46b0c1d6e075b9f3cdacaad26541ab91
34.344262
85
0.499768
false
false
false
false
robpeach/test
refs/heads/master
SwiftPages/PagedScrollViewController.swift
mit
1
// // PagedScrollViewController.swift // Britannia v2 // // Created by Rob Mellor on 11/07/2016. // Copyright © 2016 Robert Mellor. All rights reserved. // import UIKit import SDWebImage class PagedScrollViewController: UIViewController, UIScrollViewDelegate, UIGestureRecognizerDelegate { var arrGallery : NSMutableArray! var imageCache : [String:UIImage]! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet var lblPhotoCount: UILabel! var pageViews: [UIImageView?] = [] var intPage : NSInteger! @IBOutlet var viewLower: UIView! @IBOutlet var viewUpper: UIView! @IBOutlet weak var newPageView: UIView! //var newPageView: UIView! override func viewDidLoad() { super.viewDidLoad() scrollView.delegate = self scrollView.needsUpdateConstraints() scrollView.setNeedsLayout() scrollView.layoutIfNeeded() // // //Manually added constraints at runtime let constraintTS = NSLayoutConstraint(item: scrollView, attribute: .Top, relatedBy: .Equal, toItem: viewUpper, attribute: .Bottom, multiplier: 1.0, constant: 0) let constraintBS = NSLayoutConstraint(item: scrollView, attribute: .Bottom, relatedBy: .Equal, toItem: viewLower, attribute: .Top, multiplier: 1.0, constant: 0) let constraintLS = NSLayoutConstraint(item: scrollView, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1.0, constant: 0) let constraintRS = NSLayoutConstraint(item: scrollView, attribute: .Trailing, relatedBy: .Equal, toItem: view, attribute: .Trailing, multiplier: 1.0, constant: 0) view.addConstraint(constraintTS) view.addConstraint(constraintBS) view.addConstraint(constraintLS) view.addConstraint(constraintRS) } override func viewWillAppear(animated: Bool) { centerScrollViewContents() } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() centerScrollViewContents() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(true) let pageCount = arrGallery.count for _ in 0..<pageCount { pageViews.append(nil) } let pagesScrollViewSize = scrollView.frame.size scrollView.contentSize = CGSizeMake(pagesScrollViewSize.width * CGFloat(arrGallery.count), pagesScrollViewSize.height) scrollView.contentOffset.x = CGFloat(intPage) * self.view.frame.size.width lblPhotoCount.text = String(format: "%d of %d Photos",intPage+1, arrGallery.count) loadVisiblePages() let recognizer = UITapGestureRecognizer(target: self, action:#selector(PagedScrollViewController.handleTap(_:))) // 4 recognizer.delegate = self scrollView.addGestureRecognizer(recognizer) scrollView.showsVerticalScrollIndicator = false viewUpper.alpha = 1.0 viewLower.alpha = 1.0 } func handleTap(recognizer: UITapGestureRecognizer) { viewUpper.alpha = 1.0 viewLower.alpha = 1.0 } func loadPage(page: Int) { if page < 0 || page >= arrGallery.count { // If it's outside the range of what you have to display, then do nothing return } if let page = pageViews[page] { // Do nothing. The view is already loaded. } else { var frame = scrollView.bounds frame.origin.x = frame.size.width * CGFloat(page) frame.origin.y = 0.0 let rowData: NSDictionary = arrGallery[page] as! NSDictionary let urlString: String = rowData["pic"] as! String let imgURL = NSURL(string: urlString) // If this image is already cached, don't re-download if let img = imageCache[urlString] { let newPageView = UIImageView(image: img) newPageView.contentMode = .ScaleAspectFit newPageView.frame = frame scrollView.addSubview(newPageView) pageViews[page] = newPageView } else { SDWebImageManager.sharedManager().downloadImageWithURL(imgURL, options: [],progress: nil, completed: {[weak self] (image, error, cached, finished, url) in if error == nil { // let image = UIImage(data: data!) //On Main Thread dispatch_async(dispatch_get_main_queue()){ self?.imageCache[urlString] = image // Update the cell let newPageView = UIImageView(image: image) newPageView.contentMode = .ScaleAspectFit newPageView.frame = frame self?.scrollView.addSubview(newPageView) // 4 self?.pageViews[page] = newPageView } } else { print("Error: \(error!.localizedDescription)") } }) } } } func purgePage(page: Int) { if page < 0 || page >= arrGallery.count { // If it's outside the range of what you have to display, then do nothing return } if let pageView = pageViews[page] { pageView.removeFromSuperview() pageViews[page] = nil } } func loadVisiblePages() { // First, determine which page is currently visible let pageWidth = scrollView.frame.size.width let page = Int(floor((scrollView.contentOffset.x * 2.0 + pageWidth) / (pageWidth * 2.0))) intPage = page // Update the page control lblPhotoCount.text = String(format: "%d of %d Photos",intPage+1, arrGallery.count) // Work out which pages you want to load let firstPage = max(0,page - 1) let lastPage = min(page + 1, arrGallery.count - 1) // Purge anything before the first page for index in 0..<firstPage { purgePage(index) } // Load pages in our range for index in firstPage...lastPage { loadPage(index) } // Purge anything after the last page for index in (lastPage + 1)..<(arrGallery.count) { purgePage(index) } } func scrollViewDidScroll(scrollView: UIScrollView) { // Load the pages that are now on screen if scrollView.contentSize.width > 320{ viewLower.alpha = 1 viewUpper.alpha = 1 loadVisiblePages() } } @IBAction func btnBackTapped(sender: AnyObject) { scrollView.delegate = nil if let navController = self.navigationController { navController.popToRootViewControllerAnimated(true) } } @IBAction func btnShareTapped(sender: AnyObject) { var sharingItems = [AnyObject]() let rowData: NSDictionary = arrGallery[intPage] as! NSDictionary // Grab the artworkUrl60 key to get an image URL for the app's thumbnail let urlString: String = rowData["pic"] as! String // let imgURL = NSURL(string: urlString) let img = imageCache[urlString] sharingItems.append(img!) // sharingItems.append(imgURL!) let activityViewController = UIActivityViewController(activityItems: sharingItems, applicationActivities: nil) self.presentViewController(activityViewController, animated: true, completion: nil) } @IBAction func btnGalleryTapped(sender: AnyObject) { scrollView.delegate = nil if let navController = self.navigationController { navController.popViewControllerAnimated(true) } } func centerScrollViewContents() { let boundsSize = scrollView.bounds.size var contentsFrame = newPageView.frame if contentsFrame.size.width < boundsSize.width { contentsFrame.origin.x = (boundsSize.width - contentsFrame.width) / 2.0 } else { contentsFrame.origin.x = 0.0 } if contentsFrame.size.height < boundsSize.height { contentsFrame.origin.y = (boundsSize.height - contentsFrame.height - self.topLayoutGuide.length) / 2.0 } else { contentsFrame.origin.y = 0.0 } newPageView.frame = contentsFrame } override func preferredStatusBarStyle() -> UIStatusBarStyle { //LightContent return UIStatusBarStyle.LightContent //Default //return UIStatusBarStyle.Default } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
c06e302c831f4434f2e8926011118974
31.156667
170
0.561107
false
false
false
false
terietor/GTForms
refs/heads/master
Source/Forms/ControlLabelView.swift
mit
1
// Copyright (c) 2015-2016 Giorgos Tsiapaliokas <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import SnapKit class ControlLabelView<V: UILabel>: UIView { var formAxis = FormAxis.horizontal let controlLabel: UILabel = { let label = V() label.numberOfLines = 0 label.translatesAutoresizingMaskIntoConstraints = false return label }() var control: UIView! { didSet { self.control.translatesAutoresizingMaskIntoConstraints = false addSubview(self.control) } } init() { super.init(frame: CGRect.zero) self.translatesAutoresizingMaskIntoConstraints = false addSubview(self.controlLabel) } required init?(coder aDecoder: NSCoder) { fatalError("Missing Implementation") } func configureView(_ makeConstraints: (UILabel, UIView) -> ()) { makeConstraints(self.controlLabel, self.control) } }
e7f402d1fdad6b86b550a0597c2dfe38
34.736842
82
0.709867
false
false
false
false
omochi/numsw
refs/heads/master
Sources/numsw/Matrix/MatrixRandom.swift
mit
1
import Foundation extension Matrix where T: FloatingPointFunctions & FloatingPoint { public static func uniform(low: T = 0, high: T = 1, rows: Int, columns: Int) -> Matrix<T> { let count = rows * columns let elements = (0..<count).map { _ in _uniform(low: low, high: high) } return Matrix<T>(rows: rows, columns: columns, elements: elements) } } extension Matrix where T: FloatingPoint & FloatingPointFunctions & Arithmetic { public static func normal(mu: T = 0, sigma: T = 0, rows: Int, columns: Int) -> Matrix<T> { // Box-Muller's method let u1 = uniform(low: T(0), high: T(1), rows: rows, columns: columns) let u2 = uniform(low: T(0), high: T(1), rows: rows, columns: columns) let stdNormal = sqrt(-2*log(u1)) .* cos(2*T.pi*u2) return stdNormal*sigma + mu } }
b1da6c9e1f7df7ad7fba59b6a24f9833
33.592593
95
0.562099
false
false
false
false
JohnEstropia/CoreStore
refs/heads/develop
Sources/ObjectSnapshot.swift
mit
1
// // ObjectSnapshot.swift // CoreStore // // Copyright © 2018 John Rommel Estropia // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import CoreData #if canImport(UIKit) import UIKit #elseif canImport(AppKit) import AppKit #endif // MARK: - ObjectSnapshot /** The `ObjectSnapshot` is a full copy of a `DynamicObject`'s properties at a given point in time. This is useful especially when keeping thread-safe state values, in ViewModels for example. Since this is a value type, any changes in this `struct` does not affect the actual object. */ @dynamicMemberLookup public struct ObjectSnapshot<O: DynamicObject>: ObjectRepresentation, Hashable { // MARK: Public public func dictionaryForValues() -> [String: Any] { return self.values } // MARK: AnyObjectRepresentation public func objectID() -> O.ObjectID { return self.id } public func cs_dataStack() -> DataStack? { return self.context.parentStack } // MARK: ObjectRepresentation public typealias ObjectType = O public func asPublisher(in dataStack: DataStack) -> ObjectPublisher<O> { let context = dataStack.unsafeContext() return context.objectPublisher(objectID: self.id) } public func asReadOnly(in dataStack: DataStack) -> O? { return dataStack.unsafeContext().fetchExisting(self.id) } public func asEditable(in transaction: BaseDataTransaction) -> O? { return transaction.unsafeContext().fetchExisting(self.id) } public func asSnapshot(in dataStack: DataStack) -> ObjectSnapshot<O>? { let context = dataStack.unsafeContext() return ObjectSnapshot<O>(objectID: self.id, context: context) } public func asSnapshot(in transaction: BaseDataTransaction) -> ObjectSnapshot<O>? { let context = transaction.unsafeContext() return ObjectSnapshot<O>(objectID: self.id, context: context) } // MARK: Equatable public static func == (_ lhs: Self, _ rhs: Self) -> Bool { return lhs.id == rhs.id && (lhs.generation == rhs.generation || lhs.valuesRef == rhs.valuesRef) } // MARK: Hashable public func hash(into hasher: inout Hasher) { hasher.combine(self.id) hasher.combine(self.valuesRef) } // MARK: Internal internal init?(objectID: O.ObjectID, context: NSManagedObjectContext) { guard let values = O.cs_snapshotDictionary(id: objectID, context: context) else { return nil } self.id = objectID self.context = context self.values = values self.generation = .init() } internal var cs_objectID: O.ObjectID { return self.objectID() } // MARK: FilePrivate fileprivate var values: [String: Any] { didSet { self.generation = .init() } } // MARK: Private private let id: O.ObjectID private let context: NSManagedObjectContext private var generation: UUID private var valuesRef: NSDictionary { return self.values as NSDictionary } } // MARK: - ObjectSnapshot where O: NSManagedObject extension ObjectSnapshot where O: NSManagedObject { /** Returns the value for the property identified by a given key. */ public subscript<V: AllowedObjectiveCKeyPathValue>(dynamicMember member: KeyPath<O, V>) -> V! { get { let key = String(keyPath: member) return self.values[key] as! V? } set { let key = String(keyPath: member) self.values[key] = newValue } } } // MARK: - ObjectSnapshot where O: CoreStoreObject extension ObjectSnapshot where O: CoreStoreObject { /** Returns the value for the property identified by a given key. */ public subscript<OBase, V>(dynamicMember member: KeyPath<O, FieldContainer<OBase>.Stored<V>>) -> V { get { let key = String(keyPath: member) return self.values[key] as! V } set { let key = String(keyPath: member) self.values[key] = newValue } } /** Returns the value for the property identified by a given key. */ public subscript<OBase, V>(dynamicMember member: KeyPath<O, FieldContainer<OBase>.Virtual<V>>) -> V { get { let key = String(keyPath: member) return self.values[key] as! V } set { let key = String(keyPath: member) self.values[key] = newValue } } /** Returns the value for the property identified by a given key. */ public subscript<OBase, V>(dynamicMember member: KeyPath<O, FieldContainer<OBase>.Coded<V>>) -> V { get { let key = String(keyPath: member) return self.values[key] as! V } set { let key = String(keyPath: member) self.values[key] = newValue } } /** Returns the value for the property identified by a given key. */ public subscript<OBase, V>(dynamicMember member: KeyPath<O, FieldContainer<OBase>.Relationship<V>>) -> V.PublishedType { get { let key = String(keyPath: member) let context = self.context let snapshotValue = self.values[key] as! V.SnapshotValueType return V.cs_toPublishedType(from: snapshotValue, in: context) } set { let key = String(keyPath: member) self.values[key] = V.cs_toSnapshotType(from: newValue) } } /** Returns the value for the property identified by a given key. */ public subscript<OBase, V>(dynamicMember member: KeyPath<O, ValueContainer<OBase>.Required<V>>) -> V { get { let key = String(keyPath: member) return self.values[key] as! V } set { let key = String(keyPath: member) self.values[key] = newValue } } /** Returns the value for the property identified by a given key. */ public subscript<OBase, V>(dynamicMember member: KeyPath<O, ValueContainer<OBase>.Optional<V>>) -> V? { get { let key = String(keyPath: member) return self.values[key] as? V } set { let key = String(keyPath: member) self.values[key] = newValue } } /** Returns the value for the property identified by a given key. */ public subscript<OBase, V>(dynamicMember member: KeyPath<O, TransformableContainer<OBase>.Required<V>>) -> V { get { let key = String(keyPath: member) return self.values[key] as! V } set { let key = String(keyPath: member) self.values[key] = newValue } } /** Returns the value for the property identified by a given key. */ public subscript<OBase, V>(dynamicMember member: KeyPath<O, TransformableContainer<OBase>.Optional<V>>) -> V? { get { let key = String(keyPath: member) return self.values[key] as? V } set { let key = String(keyPath: member) self.values[key] = newValue } } /** Returns the value for the property identified by a given key. */ public subscript<OBase, D>(dynamicMember member: KeyPath<O, RelationshipContainer<OBase>.ToOne<D>>) -> ObjectPublisher<D>? { get { let key = String(keyPath: member) guard let id = self.values[key] as? D.ObjectID else { return nil } return self.context.objectPublisher(objectID: id) } set { let key = String(keyPath: member) self.values[key] = newValue?.objectID() } } /** Returns the value for the property identified by a given key. */ public subscript<OBase, D>(dynamicMember member: KeyPath<O, RelationshipContainer<OBase>.ToManyOrdered<D>>) -> [ObjectPublisher<D>] { get { let key = String(keyPath: member) let context = self.context let ids = self.values[key] as! [D.ObjectID] return ids.map(context.objectPublisher(objectID:)) } set { let key = String(keyPath: member) self.values[key] = newValue.map({ $0.objectID() }) } } /** Returns the value for the property identified by a given key. */ public subscript<OBase, D>(dynamicMember member: KeyPath<O, RelationshipContainer<OBase>.ToManyUnordered<D>>) -> Set<ObjectPublisher<D>> { get { let key = String(keyPath: member) let context = self.context let ids = self.values[key] as! Set<D.ObjectID> return Set(ids.map(context.objectPublisher(objectID:))) } set { let key = String(keyPath: member) self.values[key] = Set(newValue.map({ $0.objectID() })) } } }
b4a3ba76a69f8b17d209e6653e20b538
25.688312
280
0.600389
false
false
false
false
lyimin/EyepetizerApp
refs/heads/master
EyepetizerApp/EyepetizerApp/Controllers/PopularViewController/EYEPopularController.swift
mit
1
// // EYEPopularController.swift // EyepetizerApp // // Created by 梁亦明 on 16/3/10. // Copyright © 2016年 xiaoming. All rights reserved. // import UIKit import Alamofire class EYEPopularController: EYEBaseViewController, LoadingPresenter { var loaderView : EYELoaderView! //MARK: --------------------------- Life Cycle -------------------------- override func viewDidLoad() { super.viewDidLoad() // 添加headerView self.view.addSubview(headerView) headerView.headerViewTitleDidClick { [unowned self](targetBtn, index) in self.itemDidClick(index) } // 添加控制器 // 默认选中第一个 itemDidClick(0) } //MARK: --------------------------- Private Methods -------------------------- private func itemDidClick(index : Int) { var actionController : UIViewController! // 再添加控制器 switch index { case 0: if weekController == nil { weekController = EYEPopularWeekController() } actionController = weekController break case 1: if monthController == nil { monthController = EYEPopularMonthController() } actionController = monthController break case 2: if historyController == nil { historyController = EYEPopularHistoryController() } actionController = historyController break default: break } self.addChildViewController(actionController) self.view.addSubview(actionController.view) self.setupControllerFrame(actionController.view) // 动画 if let currentVC = currentController { startAnimation(currentVC, toVC: actionController) } else { // 首次运行会来这里,将weekcontroller 赋值给当前控制器 currentController = actionController } } // 设置控制器frame private func startAnimation(fromVC: UIViewController, toVC: UIViewController) { toVC.view.alpha = 0 UIView.animateWithDuration(0.5, animations: { fromVC.view.alpha = 0 toVC.view.alpha = 1 }) {[unowned self] (_) in // 先清空currentview fromVC.view.removeFromSuperview() self.currentController = nil // 在赋值 self.currentController = toVC } } private func setupControllerFrame (view : UIView) { view.snp_makeConstraints { (make) in make.left.trailing.equalTo(self.view) make.top.equalTo(self.headerView).offset(headerView.height) make.bottom.equalTo(self.view).offset(-UIConstant.UI_TAB_HEIGHT) } } //MARK: --------------------------- Getter or Setter -------------------------- // controller private var weekController: EYEPopularWeekController? private var monthController: EYEPopularMonthController? private var historyController: EYEPopularHistoryController? // 当前选中控制器 private var currentController : UIViewController? private let titleArray = ["周排行", "月排行", "总排行"] // headerView private lazy var headerView : EYEPopularHeaderView = { let headerView = EYEPopularHeaderView(frame: CGRect(x: 0, y: UIConstant.UI_NAV_HEIGHT, width: UIConstant.SCREEN_WIDTH, height: UIConstant.UI_CHARTS_HEIGHT), titleArray: self.titleArray) return headerView }() }
c02885eca4e9596c4932ebdb7ee63828
31.618182
193
0.568999
false
false
false
false
Punch-In/PunchInIOSApp
refs/heads/master
PunchIn/LoginViewController.swift
mit
1
// // LoginViewController.swift // PunchIn // // Created by Nilesh Agrawal on 10/20/15. // Copyright © 2015 Nilesh Agrawal. All rights reserved. // import UIKit import Parse class LoginViewController: UIViewController { static let loginSegueName = "loginSegue" static let userTypes = [ "Student", "Instructor" ] private let initialEmailAddress = "[email protected]" private let initialPassword = "password" private static let noUserProvidedText = "Please provide an email address" private static let noPasswordProvidedText = "Please provide a password" private static let badUserText = "Email and/or Password is not valid" private static let notInstructorText = " is not an Instructor" private static let notStudentText = " is not a Student" @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var invalidEntryLabel: UILabel! @IBOutlet var studentIndicatorTapGesture: UITapGestureRecognizer! @IBOutlet weak var studentIndicatorImage: UIImageView! private var isStudent: Bool = false deinit { NSNotificationCenter.defaultCenter().removeObserver(self, name: ParseDB.BadLoginNotificationName, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: ParseDB.BadTypeNotificationName, object:nil) } override func viewDidLoad() { super.viewDidLoad() setupUI() setupGestureRecognizer() isStudent = false studentIndicatorImage.image = UIImage(named: "unselected_button_login.png") // Do any additional setup after loading the view. invalidEntryLabel.hidden = true NSNotificationCenter.defaultCenter().addObserver(self, selector: "badUser", name:ParseDB.BadLoginNotificationName, object:nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "badType", name:ParseDB.BadTypeNotificationName, object:nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } private func setupUI() { // set color schemes, etc // set background color self.view.backgroundColor = ThemeManager.theme().primaryDarkBlueColor() // set background color for email address & password field nameTextField.backgroundColor = ThemeManager.theme().primaryBlueColor() nameTextField.textColor = UIColor.whiteColor() nameTextField.placeholder = initialEmailAddress passwordTextField.backgroundColor = ThemeManager.theme().primaryBlueColor() passwordTextField.textColor = UIColor.whiteColor() passwordTextField.placeholder = initialPassword // set login loginButton.layer.borderColor = UIColor.whiteColor().CGColor loginButton.layer.borderWidth = 1.0 loginButton.tintColor = UIColor.whiteColor() // set color for invalid entry invalidEntryLabel.textColor = ThemeManager.theme().primaryYellowColor() } private func setupGestureRecognizer() { studentIndicatorTapGesture.addTarget(self, action: "didTapStudentIndicator") } func didTapStudentIndicator() { if isStudent { // change to not student isStudent = false studentIndicatorImage.image = UIImage(named: "unselected_button_login.png") }else{ // change to student isStudent = true studentIndicatorImage.image = UIImage(named: "selected_button_login.png") } } func validateInput() -> Bool { var goodInput: Bool = true goodInput = goodInput && !nameTextField.text!.isEmpty goodInput = goodInput && !passwordTextField.text!.isEmpty goodInput = goodInput && !(nameTextField.text==initialEmailAddress) goodInput = goodInput && !(passwordTextField.text==initialPassword) return goodInput } private func updateInvalidDataText(status: String) { self.invalidEntryLabel.alpha = 0 self.invalidEntryLabel.hidden = false self.invalidEntryLabel.text = status UIView.animateWithDuration(0.5) { () -> Void in self.invalidEntryLabel.alpha = 1 } } func badUser() { updateInvalidDataText(LoginViewController.badUserText) } func badType() { let errorText = isStudent ? LoginViewController.notStudentText : LoginViewController.notInstructorText updateInvalidDataText(self.nameTextField.text! + errorText) } @IBAction func accountLogin(sender: AnyObject) { guard !nameTextField.text!.isEmpty else { updateInvalidDataText(LoginViewController.noUserProvidedText) return } guard !passwordTextField.text!.isEmpty else { updateInvalidDataText(LoginViewController.noPasswordProvidedText) return } self.invalidEntryLabel.hidden = true ParseDB.login(nameTextField!.text!, password: passwordTextField!.text!, type: isStudent ? LoginViewController.userTypes[0] : LoginViewController.userTypes[1]) } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. } }
e8e730bc325d375094efd0a25d76ac73
35.570513
134
0.675723
false
false
false
false
jonkykong/SideMenu
refs/heads/master
Pod/Classes/SideMenuPushCoordinator.swift
mit
1
// // PushCoordinator.swift // SideMenu // // Created by Jon Kent on 9/4/19. // import UIKit protocol CoordinatorModel { var animated: Bool { get } var fromViewController: UIViewController { get } var toViewController: UIViewController { get } } protocol Coordinator { associatedtype Model: CoordinatorModel init(config: Model) @discardableResult func start() -> Bool } internal final class SideMenuPushCoordinator: Coordinator { struct Model: CoordinatorModel { var allowPushOfSameClassTwice: Bool var alongsideTransition: (() -> Void)? var animated: Bool var fromViewController: UIViewController var pushStyle: SideMenuPushStyle var toViewController: UIViewController } private let config: Model init(config: Model) { self.config = config } @discardableResult func start() -> Bool { guard config.pushStyle != .subMenu, let fromNavigationController = config.fromViewController as? UINavigationController else { return false } let toViewController = config.toViewController let presentingViewController = fromNavigationController.presentingViewController let splitViewController = presentingViewController as? UISplitViewController let tabBarController = presentingViewController as? UITabBarController let potentialNavigationController = (splitViewController?.viewControllers.first ?? tabBarController?.selectedViewController) ?? presentingViewController guard let navigationController = potentialNavigationController as? UINavigationController else { Print.warning(.cannotPush, arguments: String(describing: potentialNavigationController.self), required: true) return false } // To avoid overlapping dismiss & pop/push calls, create a transaction block where the menu // is dismissed after showing the appropriate screen CATransaction.begin() defer { CATransaction.commit() } UIView.animationsEnabled { [weak self] in self?.config.alongsideTransition?() } if let lastViewController = navigationController.viewControllers.last, !config.allowPushOfSameClassTwice && type(of: lastViewController) == type(of: toViewController) { return false } toViewController.navigationItem.hidesBackButton = config.pushStyle.hidesBackButton switch config.pushStyle { case .default: navigationController.pushViewController(toViewController, animated: config.animated) return true // subMenu handled earlier case .subMenu: return false case .popWhenPossible: for subViewController in navigationController.viewControllers.reversed() { if type(of: subViewController) == type(of: toViewController) { navigationController.popToViewController(subViewController, animated: config.animated) return true } } navigationController.pushViewController(toViewController, animated: config.animated) return true case .preserve, .preserveAndHideBackButton: var viewControllers = navigationController.viewControllers let filtered = viewControllers.filter { preservedViewController in type(of: preservedViewController) == type(of: toViewController) } guard let preservedViewController = filtered.last else { navigationController.pushViewController(toViewController, animated: config.animated) return true } viewControllers = viewControllers.filter { subViewController in subViewController !== preservedViewController } viewControllers.append(preservedViewController) navigationController.setViewControllers(viewControllers, animated: config.animated) return true case .replace: navigationController.setViewControllers([toViewController], animated: config.animated) return true } } }
684427dea2f87371b5cda95416eb7da9
38.065421
160
0.684928
false
true
false
false
stulevine/firefox-ios
refs/heads/master
Sync/SyncStateMachine.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import Account import XCGLogger // TODO: same comment as for SyncAuthState.swift! private let log = XCGLogger.defaultInstance() private let ShortCircuitMissingMetaGlobal = true // Do this so we don't exercise 'recovery' code. private let ShortCircuitMissingCryptoKeys = true // Do this so we don't exercise 'recovery' code. private let StorageVersionCurrent = 5 private let DefaultEngines: [String: Int] = ["tabs": 1] private let DefaultDeclined: [String] = [String]() private func getDefaultEngines() -> [String: EngineMeta] { return mapValues(DefaultEngines, { EngineMeta(version: $0, syncID: Bytes.generateGUID()) }) } public typealias TokenSource = () -> Deferred<Result<TokenServerToken>> public typealias ReadyDeferred = Deferred<Result<Ready>> // See docs in docs/sync.md. // You might be wondering why this doesn't have a Sync15StorageClient like FxALoginStateMachine // does. Well, such a client is pinned to a particular server, and this state machine must // acknowledge that a Sync client occasionally must migrate between two servers, preserving // some state from the last. // The resultant 'Ready' will be able to provide a suitably initialized storage client. public class SyncStateMachine { private class func scratchpadPrefs(prefs: Prefs) -> Prefs { return prefs.branch("scratchpad") } public class func getInfoCollections(authState: SyncAuthState, prefs: Prefs) -> Deferred<Result<InfoCollections>> { log.debug("Fetching info/collections in state machine.") let token = authState.token(NSDate.now(), canBeExpired: true) return chainDeferred(token, { (token, kB) in // TODO: the token might not be expired! Check and selectively advance. log.debug("Got token from auth state. Advancing to InitialWithExpiredToken.") let state = InitialWithExpiredToken(scratchpad: Scratchpad(b: KeyBundle.fromKB(kB), persistingTo: self.scratchpadPrefs(prefs)), token: token) return state.getInfoCollections() }) } public class func toReady(authState: SyncAuthState, prefs: Prefs) -> ReadyDeferred { let token = authState.token(NSDate.now(), canBeExpired: false) return chainDeferred(token, { (token, kB) in log.debug("Got token from auth state. Server is \(token.api_endpoint).") let scratchpadPrefs = self.scratchpadPrefs(prefs) let prior = Scratchpad.restoreFromPrefs(scratchpadPrefs, syncKeyBundle: KeyBundle.fromKB(kB)) if prior == nil { log.info("No persisted Sync state. Starting over.") } let scratchpad = prior ?? Scratchpad(b: KeyBundle.fromKB(kB), persistingTo: scratchpadPrefs) log.info("Advancing to InitialWithLiveToken.") let state = InitialWithLiveToken(scratchpad: scratchpad, token: token) return advanceSyncState(state) }) } } public enum SyncStateLabel: String { case Stub = "STUB" // For 'abstract' base classes. case InitialWithExpiredToken = "initialWithExpiredToken" case InitialWithExpiredTokenAndInfo = "initialWithExpiredTokenAndInfo" case InitialWithLiveToken = "initialWithLiveToken" case InitialWithLiveTokenAndInfo = "initialWithLiveTokenAndInfo" case ResolveMetaGlobal = "resolveMetaGlobal" case NewMetaGlobal = "newMetaGlobal" case HasMetaGlobal = "hasMetaGlobal" case Restart = "restart" // Go around again... once only, perhaps. case Ready = "ready" case ChangedServer = "changedServer" case MissingMetaGlobal = "missingMetaGlobal" case MissingCryptoKeys = "missingCryptoKeys" case MalformedCryptoKeys = "malformedCryptoKeys" case SyncIDChanged = "syncIDChanged" static let allValues: [SyncStateLabel] = [ InitialWithExpiredToken, InitialWithExpiredTokenAndInfo, InitialWithLiveToken, InitialWithLiveTokenAndInfo, ResolveMetaGlobal, NewMetaGlobal, HasMetaGlobal, Restart, Ready, ChangedServer, MissingMetaGlobal, MissingCryptoKeys, MalformedCryptoKeys, SyncIDChanged, ] } /** * States in this state machine all implement SyncState. * * States are either successful main-flow states, or (recoverable) error states. * Errors that aren't recoverable are simply errors. * Main-flow states flow one to one. * * (Terminal failure states might be introduced at some point.) * * Multiple error states (but typically only one) can arise from each main state transition. * For example, parsing meta/global can result in a number of different non-routine situations. * * For these reasons, and the lack of useful ADTs in Swift, we model the main flow as * the success branch of a Result, and the recovery flows as a part of the failure branch. * * We could just as easily use a ternary Either-style operator, but thanks to Swift's * optional-cast-let it's no saving to do so. * * Because of the lack of type system support, all RecoverableSyncStates must have the same * signature. That signature implies a possibly multi-state transition; individual states * will have richer type signatures. */ public protocol SyncState { var label: SyncStateLabel { get } } /* * Base classes to avoid repeating initializers all over the place. */ public class BaseSyncState: SyncState { public var label: SyncStateLabel { return SyncStateLabel.Stub } public let client: Sync15StorageClient! let token: TokenServerToken // Maybe expired. var scratchpad: Scratchpad // TODO: 304 for i/c. public func getInfoCollections() -> Deferred<Result<InfoCollections>> { return chain(self.client.getInfoCollections(), { return $0.value }) } public init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken) { self.scratchpad = scratchpad self.token = token self.client = client log.info("Inited \(self.label.rawValue)") } public func synchronizer<T: Synchronizer>(synchronizerClass: T.Type, prefs: Prefs) -> T { return T(scratchpad: self.scratchpad, basePrefs: prefs) } // This isn't a convenience initializer 'cos subclasses can't call convenience initializers. public init(scratchpad: Scratchpad, token: TokenServerToken) { let workQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) let resultQueue = dispatch_get_main_queue() let client = Sync15StorageClient(token: token, workQueue: workQueue, resultQueue: resultQueue) self.scratchpad = scratchpad self.token = token self.client = client log.info("Inited \(self.label.rawValue)") } } public class BaseSyncStateWithInfo: BaseSyncState { public let info: InfoCollections init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections) { self.info = info super.init(client: client, scratchpad: scratchpad, token: token) } init(scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections) { self.info = info super.init(scratchpad: scratchpad, token: token) } } /* * Error types. */ public protocol SyncError: ErrorType {} public class UnknownError: SyncError { public var description: String { return "Unknown error." } } public class CouldNotFetchMetaGlobalError: SyncError { public var description: String { return "Could not fetch meta/global." } } public class CouldNotFetchKeysError: SyncError { public var description: String { return "Could not fetch crypto/keys." } } public class StubStateError: SyncError { public var description: String { return "Unexpectedly reached a stub state. This is a coding error." } } public class UpgradeRequiredError: SyncError { let targetStorageVersion: Int public init(target: Int) { self.targetStorageVersion = target } public var description: String { return "Upgrade required to work with storage version \(self.targetStorageVersion)." } } public class InvalidKeysError: SyncError { let keys: Keys public init(_ keys: Keys) { self.keys = keys } public var description: String { return "Downloaded crypto/keys, but couldn't parse them." } } public class MissingMetaGlobalAndUnwillingError: SyncError { public var description: String { return "No meta/global on server, and we're unwilling to create one." } } public class MissingCryptoKeysAndUnwillingError: SyncError { public var description: String { return "No crypto/keys on server, and we're unwilling to create one." } } /* * Error states. These are errors that can be recovered from by taking actions. */ public protocol RecoverableSyncState: SyncState, SyncError { // All error states must be able to advance to a usable state. func advance() -> Deferred<Result<SyncState>> } /** * Recovery: discard our local timestamps and sync states; discard caches. * Be prepared to handle a conflict between our selected engines and the new * server's meta/global; if an engine is selected locally but not declined * remotely, then we'll need to upload a new meta/global and sync that engine. */ public class ChangedServerError: RecoverableSyncState { public var label: SyncStateLabel { return SyncStateLabel.ChangedServer } public var description: String { return "Token destination changed to \(self.newToken.api_endpoint)/\(self.newToken.uid)." } let newToken: TokenServerToken let newScratchpad: Scratchpad public init(scratchpad: Scratchpad, token: TokenServerToken) { self.newToken = token self.newScratchpad = Scratchpad(b: scratchpad.syncKeyBundle, persistingTo: scratchpad.prefs) } public func advance() -> Deferred<Result<SyncState>> { // TODO: mutate local storage to allow for a fresh start. let state = InitialWithLiveToken(scratchpad: newScratchpad.checkpoint(), token: newToken) return Deferred(value: Result(success: state)) } } /** * Recovery: same as for changed server, but no need to upload a new meta/global. */ public class SyncIDChangedError: RecoverableSyncState { public var label: SyncStateLabel { return SyncStateLabel.SyncIDChanged } public var description: String { return "Global sync ID changed." } private let previousState: BaseSyncStateWithInfo private let newMetaGlobal: Fetched<MetaGlobal> public init(previousState: BaseSyncStateWithInfo, newMetaGlobal: Fetched<MetaGlobal>) { self.previousState = previousState self.newMetaGlobal = newMetaGlobal } public func advance() -> Deferred<Result<SyncState>> { // TODO: mutate local storage to allow for a fresh start. let s = self.previousState.scratchpad.evolve().setGlobal(self.newMetaGlobal).setKeys(nil).build().checkpoint() let state = HasMetaGlobal(client: self.previousState.client, scratchpad: s, token: self.previousState.token, info: self.previousState.info) return Deferred(value: Result(success: state)) } } /** * Recovery: wipe the server (perhaps unnecessarily), upload a new meta/global, * do a fresh start. */ public class MissingMetaGlobalError: RecoverableSyncState { public var label: SyncStateLabel { return SyncStateLabel.MissingMetaGlobal } public var description: String { return "Missing meta/global." } private let previousState: BaseSyncStateWithInfo public init(previousState: BaseSyncStateWithInfo) { self.previousState = previousState } // TODO: this needs EnginePreferences. private class func createMetaGlobal(previous: MetaGlobal?, scratchpad: Scratchpad) -> MetaGlobal { return MetaGlobal(syncID: Bytes.generateGUID(), storageVersion: StorageVersionCurrent, engines: getDefaultEngines(), declined: DefaultDeclined) } private func onWiped(resp: StorageResponse<JSON>, s: Scratchpad) -> Deferred<Result<SyncState>> { // Upload a new meta/global. // Note that we discard info/collections -- we just wiped storage. return Deferred(value: Result(success: InitialWithLiveToken(client: self.previousState.client, scratchpad: s, token: self.previousState.token))) } private func advanceFromWiped(wipe: Deferred<Result<StorageResponse<JSON>>>) -> Deferred<Result<SyncState>> { // TODO: mutate local storage to allow for a fresh start. // Note that we discard the previous global and keys -- after all, we just wiped storage. let s = self.previousState.scratchpad.evolve().setGlobal(nil).setKeys(nil).build().checkpoint() return chainDeferred(wipe, { self.onWiped($0, s: s) }) } public func advance() -> Deferred<Result<SyncState>> { return self.advanceFromWiped(self.previousState.client.wipeStorage()) } } // TODO public class MissingCryptoKeysError: RecoverableSyncState { public var label: SyncStateLabel { return SyncStateLabel.MissingCryptoKeys } public var description: String { return "Missing crypto/keys." } public func advance() -> Deferred<Result<SyncState>> { return Deferred(value: Result(failure: MissingCryptoKeysAndUnwillingError())) } } /* * Non-error states. */ public class InitialWithExpiredToken: BaseSyncState { public override var label: SyncStateLabel { return SyncStateLabel.InitialWithExpiredToken } // This looks totally redundant, but try taking it out, I dare you. public override init(scratchpad: Scratchpad, token: TokenServerToken) { super.init(scratchpad: scratchpad, token: token) } func advanceWithInfo(info: InfoCollections) -> InitialWithExpiredTokenAndInfo { return InitialWithExpiredTokenAndInfo(scratchpad: self.scratchpad, token: self.token, info: info) } public func advanceIfNeeded(previous: InfoCollections?, collections: [String]?) -> Deferred<Result<InitialWithExpiredTokenAndInfo?>> { return chain(getInfoCollections(), { info in // Unchanged or no previous state? Short-circuit. if let previous = previous { if info.same(previous, collections: collections) { return nil } } // Changed? Move to the next state with the fetched info. return self.advanceWithInfo(info) }) } } public class InitialWithExpiredTokenAndInfo: BaseSyncStateWithInfo { public override var label: SyncStateLabel { return SyncStateLabel.InitialWithExpiredTokenAndInfo } public func advanceWithToken(liveTokenSource: TokenSource) -> Deferred<Result<InitialWithLiveTokenAndInfo>> { return chainResult(liveTokenSource(), { token in if self.token.sameDestination(token) { return Result(success: InitialWithLiveTokenAndInfo(scratchpad: self.scratchpad, token: token, info: self.info)) } // Otherwise, we're screwed: we need to start over. // Pass in the new token, of course. return Result(failure: ChangedServerError(scratchpad: self.scratchpad, token: token)) }) } } public class InitialWithLiveToken: BaseSyncState { public override var label: SyncStateLabel { return SyncStateLabel.InitialWithLiveToken } // This looks totally redundant, but try taking it out, I dare you. public override init(scratchpad: Scratchpad, token: TokenServerToken) { super.init(scratchpad: scratchpad, token: token) } // This looks totally redundant, but try taking it out, I dare you. public override init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken) { super.init(client: client, scratchpad: scratchpad, token: token) } func advanceWithInfo(info: InfoCollections) -> InitialWithLiveTokenAndInfo { return InitialWithLiveTokenAndInfo(scratchpad: self.scratchpad, token: self.token, info: info) } public func advance() -> Deferred<Result<InitialWithLiveTokenAndInfo>> { return chain(getInfoCollections(), self.advanceWithInfo) } } /** * Each time we fetch a new meta/global, we need to reconcile it with our * current state. * * It might be identical to our current meta/global, in which case we can short-circuit. * * We might have no previous meta/global at all, in which case this state * simply configures local storage to be ready to sync according to the * supplied meta/global. (Not necessarily datatype elections: those will be per-device.) * * Or it might be different. In this case the previous m/g and our local user preferences * are compared to the new, resulting in some actions and a final state. * * This state is similar in purpose to GlobalSession.processMetaGlobal in Android Sync. * TODO */ public class ResolveMetaGlobal: BaseSyncStateWithInfo { let fetched: Fetched<MetaGlobal> init(fetched: Fetched<MetaGlobal>, client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections) { self.fetched = fetched super.init(client: client, scratchpad: scratchpad, token: token, info: info) } public override var label: SyncStateLabel { return SyncStateLabel.ResolveMetaGlobal } class func fromState(state: BaseSyncStateWithInfo, fetched: Fetched<MetaGlobal>) -> ResolveMetaGlobal { return ResolveMetaGlobal(fetched: fetched, client: state.client, scratchpad: state.scratchpad, token: state.token, info: state.info) } func advanceAfterWipe(resp: StorageResponse<JSON>) -> ReadyDeferred { // This will only be called on a successful response. // Upload a new meta/global by advancing to an initial state. // Note that we discard info/collections -- we just wiped storage. let s = self.scratchpad.evolve().setGlobal(nil).setKeys(nil).build().checkpoint() let initial: InitialWithLiveToken = InitialWithLiveToken(client: self.client, scratchpad: s, token: self.token) return advanceSyncState(initial) } func advance() -> ReadyDeferred { // TODO: detect when an individual collection syncID has changed, and make sure that // collection is reset. // First: check storage version. let v = fetched.value.storageVersion if v > StorageVersionCurrent { log.info("Client upgrade required for storage version \(v)") return Deferred(value: Result(failure: UpgradeRequiredError(target: v))) } if v < StorageVersionCurrent { log.info("Server storage version \(v) is outdated.") // Wipe the server and upload. // TODO: if we're connecting for the first time, and this is an old server, try // to salvage old preferences from the old meta/global -- e.g., datatype elections. // This doesn't need to be implemented until we rev the storage format, which // might never happen. return chainDeferred(client.wipeStorage(), self.advanceAfterWipe) } // Second: check syncID and contents. if let previous = self.scratchpad.global?.value { // Do checks that only apply when we're coming from a previous meta/global. if previous.syncID != fetched.value.syncID { // Global syncID changed. Reset for every collection, and also throw away any cached keys. return resetStateWithGlobal(fetched) } // TODO: Check individual collections, resetting them as necessary if their syncID has changed! // For now, we just adopt the new meta/global, adjust our engines to match, and move on. // This means that if a per-engine syncID changes, *we won't do the right thing*. let withFetchedGlobal = self.scratchpad.withGlobal(fetched) return applyEngineChoicesAndAdvance(withFetchedGlobal) } // No previous meta/global. We know we need to do a fresh start sync. // This function will do the right thing if there's no previous meta/global. return resetStateWithGlobal(fetched) } /** * In some cases we downloaded a new meta/global, and we recognize that we need * a blank slate. This method makes one from our scratchpad, applies any necessary * changes to engine elections from the downloaded meta/global, uploads a changed * meta/global if we must, and then moves to HasMetaGlobal and on to Ready. * TODO: reset all local collections. */ private func resetStateWithGlobal(fetched: Fetched<MetaGlobal>) -> ReadyDeferred { let fresh = self.scratchpad.freshStartWithGlobal(fetched) return applyEngineChoicesAndAdvance(fresh) } private func applyEngineChoicesAndAdvance(newScratchpad: Scratchpad) -> ReadyDeferred { // When we adopt a new meta global, we might update our local enabled/declined // engine lists (which are stored in the scratchpad itself), or need to add // some to meta/global. This call asks the scratchpad to return a possibly new // scratchpad, and optionally a meta/global to upload. // If this upload fails, we abort, of course. let previousMetaGlobal = self.scratchpad.global?.value let (withEnginesApplied: Scratchpad, toUpload: MetaGlobal?) = newScratchpad.applyEngineChoices(previousMetaGlobal) if let toUpload = toUpload { // Upload the new meta/global. // The provided scratchpad *does not reflect this new meta/global*: you need to // get the timestamp from the upload! let upload = self.client.uploadMetaGlobal(toUpload, ifUnmodifiedSince: fetched.timestamp) return chainDeferred(upload, { resp in let postUpload = withEnginesApplied.checkpoint() // TODO: add the timestamp! return HasMetaGlobal.fromState(self, scratchpad: postUpload).advance() }) } // If the meta/global was quietly applied, great; roll on with what we were given. return HasMetaGlobal.fromState(self, scratchpad: withEnginesApplied.checkpoint()).advance() } } public class InitialWithLiveTokenAndInfo: BaseSyncStateWithInfo { public override var label: SyncStateLabel { return SyncStateLabel.InitialWithLiveTokenAndInfo } private func processFailure(failure: ErrorType?) -> ErrorType { // For now, avoid the risky stuff. if ShortCircuitMissingMetaGlobal { return MissingMetaGlobalAndUnwillingError() } if let failure = failure as? NotFound<StorageResponse<GlobalEnvelope>> { // OK, this is easy. // This state is responsible for creating the new m/g, uploading it, and // restarting with a clean scratchpad. return MissingMetaGlobalError(previousState: self) } // TODO: backoff etc. for all of these. if let failure = failure as? ServerError<StorageResponse<GlobalEnvelope>> { // Be passive. return failure } if let failure = failure as? BadRequestError<StorageResponse<GlobalEnvelope>> { // Uh oh. log.error("Bad request. Bailing out. \(failure.description)") return failure } log.error("Unexpected failure. \(failure?.description)") return failure ?? UnknownError() } // This method basically hops over HasMetaGlobal, because it's not a state // that we expect consumers to know about. func advance() -> ReadyDeferred { // Either m/g and c/k are in our local cache, and they're up-to-date with i/c, // or we need to fetch them. // Cached and not changed in i/c? Use that. // This check would be inaccurate if any other fields were stored in meta/; this // has been the case in the past, with the Sync 1.1 migration indicator. if let global = self.scratchpad.global { if let metaModified = self.info.modified("meta") { // The record timestamp *should* be no more recent than the current collection. // We don't check that (indeed, we don't even store it!). // We also check the last fetch timestamp for the record, and that can be // later than the collection timestamp. All we care about here is if the // server might have a newer record. if global.timestamp >= metaModified { log.info("Using cached meta/global.") // Strictly speaking we can avoid fetching if this condition is not true, // but if meta/ is modified for a different reason -- store timestamps // for the last collection fetch. This will do for now. return HasMetaGlobal.fromState(self).advance() } } } // Fetch. return self.client.getMetaGlobal().bind { result in if let resp = result.successValue { if let fetched = resp.value.toFetched() { // We bump the meta/ timestamp because, though in theory there might be // other records in that collection, even if there are we don't care about them. self.scratchpad.collectionLastFetched["meta"] = resp.metadata.lastModifiedMilliseconds return ResolveMetaGlobal.fromState(self, fetched: fetched).advance() } // This should not occur. log.error("Unexpectedly no meta/global despite a successful fetch.") } // Otherwise, we have a failure state. return Deferred(value: Result(failure: self.processFailure(result.failureValue))) } } } public class HasMetaGlobal: BaseSyncStateWithInfo { public override var label: SyncStateLabel { return SyncStateLabel.HasMetaGlobal } class func fromState(state: BaseSyncStateWithInfo) -> HasMetaGlobal { return HasMetaGlobal(client: state.client, scratchpad: state.scratchpad, token: state.token, info: state.info) } class func fromState(state: BaseSyncStateWithInfo, scratchpad: Scratchpad) -> HasMetaGlobal { return HasMetaGlobal(client: state.client, scratchpad: scratchpad, token: state.token, info: state.info) } private func processFailure(failure: ErrorType?) -> ErrorType { // For now, avoid the risky stuff. if ShortCircuitMissingCryptoKeys { return MissingCryptoKeysAndUnwillingError() } if let failure = failure as? NotFound<StorageResponse<KeysPayload>> { // This state is responsible for creating the new c/k, uploading it, and // restarting with a clean scratchpad. // But we haven't implemented it yet. return MissingCryptoKeysError() } // TODO: backoff etc. for all of these. if let failure = failure as? ServerError<StorageResponse<KeysPayload>> { // Be passive. return failure } if let failure = failure as? BadRequestError<StorageResponse<KeysPayload>> { // Uh oh. log.error("Bad request. Bailing out. \(failure.description)") return failure } log.error("Unexpected failure. \(failure?.description)") return failure ?? UnknownError() } func advance() -> ReadyDeferred { // Fetch crypto/keys, unless it's present in the cache already. // For now, just fetch. // // N.B., we assume that if the server has a meta/global, we don't have a cached crypto/keys, // and the server doesn't have crypto/keys, that the server was wiped. // // This assumption is basically so that we don't get trapped in a cycle of seeing this situation, // blanking the server, trying to upload meta/global, getting interrupted, and so on. // // I think this is pretty safe. TODO: verify this assumption by reading a-s and desktop code. // // TODO: detect when the keys have changed, and scream and run away if so. // TODO: upload keys if necessary, then go to Restart. let syncKey = Keys(defaultBundle: self.scratchpad.syncKeyBundle) let keysFactory: (String) -> KeysPayload? = syncKey.factory("keys", f: { KeysPayload($0) }) let client = self.client.clientForCollection("crypto", factory: keysFactory) // TODO: this assumes that there are keys on the server. Check first, and if there aren't, // go ahead and go to an upload state without having to fail. return client.get("keys").bind { result in if let resp = result.successValue { let collectionKeys = Keys(payload: resp.value.payload) if (!collectionKeys.valid) { log.error("Unexpectedly invalid crypto/keys during a successful fetch.") return Deferred(value: Result(failure: InvalidKeysError(collectionKeys))) } // setKeys bumps the crypto/ timestamp because, though in theory there might be // other records in that collection, even if there are we don't care about them. let fetched = Fetched(value: collectionKeys, timestamp: resp.value.modified) let s = self.scratchpad.evolve().setKeys(fetched).build().checkpoint() let ready = Ready(client: self.client, scratchpad: s, token: self.token, info: self.info, keys: collectionKeys) log.info("Arrived in Ready state.") return Deferred(value: Result(success: ready)) } // Otherwise, we have a failure state. // Much of this logic is shared with the meta/global fetch. return Deferred(value: Result(failure: self.processFailure(result.failureValue))) } } } public class Ready: BaseSyncStateWithInfo { public override var label: SyncStateLabel { return SyncStateLabel.Ready } let collectionKeys: Keys public init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections, keys: Keys) { self.collectionKeys = keys super.init(client: client, scratchpad: scratchpad, token: token, info: info) } } /* * Because a strongly typed state machine is incompatible with protocols, * we use function dispatch to ape a protocol. */ func advanceSyncState(s: InitialWithLiveToken) -> ReadyDeferred { return chainDeferred(s.advance(), { $0.advance() }) } func advanceSyncState(s: HasMetaGlobal) -> ReadyDeferred { return s.advance() }
1dadf9992d2064ac3551016380feb4e1
41.241892
153
0.6791
false
false
false
false