repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 202
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
kongtomorrow/ProjectEuler-Swift | ProjectEuler/shared.swift | 1 | 28067 | //
// main.swift
// ProjectEuler
//
// Created by Ken Ferry on 7/29/14.
// Copyright (c) 2014 Understudy. All rights reserved.
//
import Foundation
// MARK: -
// MARK: Utility
// MARK: -
// logging
postfix operator *** { }
postfix func ***<T>(obj:T) -> T { println(obj); return obj }
func benchmark<T>(label:String, body:()->T)->T {
var info = mach_timebase_info_data_t(numer: 0, denom: 0)
mach_timebase_info(&info)
let tick = mach_absolute_time()
let res = body()
let tock = mach_absolute_time()
let delta = tock - tick
let nanos = delta * UInt64(info.numer) / UInt64(info.denom)
let seconds = Double(nanos) / Double(NSEC_PER_SEC)
"\(label) returned \(res) in \(seconds) seconds"***
return res
}
// pointer
class Ptr<T> {
let val : T
init(_ aVal:T) {
val = aVal
}
}
// for switching on
//func compare(a:Int, b:Int)->NSComparisonResult {
// if a == b {
// return .OrderedSame
// } else if a < b {
// return .OrderedAscending
// } else {
// return .OrderedDescending
// }
//}
var logCacheMiss = false
var cacheMissDepth = 0
func memoize<S:Hashable,T>(f:S->T) ->S->T {
var cache = [S:T]()
return {
(args:S)->T in
var res = cache[args]
if res == nil {
if logCacheMiss {
for i in 0..<cacheMissDepth {
print(" ")
}
print("depth:\(cacheMissDepth) -- memoized cache will miss!\n")
}
res = f(args)
cache[args] = res
if logCacheMiss {
for i in 0..<cacheMissDepth {
print(" ")
}
print("depth:\(cacheMissDepth) -- memoized cache did miss \(res)!\n")
}
}
return res!
}
}
// void isn't hashable, so not covered above
func memoize<T>(f:()->T) ->()->T {
var cache : T? = nil
return {
if cache == nil {
if logCacheMiss {
for i in 0..<cacheMissDepth {
print(" ")
}
dump(nil as T?, name: "will miss cache", indent: cacheMissDepth, maxDepth: 100, maxItems: 10)
cacheMissDepth++
}
cache = f()
if logCacheMiss {
cacheMissDepth--
for i in 0..<cacheMissDepth {
print(" ")
}
dump(cache, name: "did miss cache", indent: cacheMissDepth, maxDepth: 100, maxItems: 10)
}
}
return cache!
}
}
func denseMemoize<T>(f:Int->T) ->Int->T {
var cache = [Optional<T>.None]
return {
(i:Int)->T in
while i >= cache.count {
cache.extend(Repeat(count: cache.count, repeatedValue: Optional<T>.None))
}
var res = cache[i]
if res == nil {
if logCacheMiss {
for i in 0..<cacheMissDepth {
print(" ")
}
print("depth:\(cacheMissDepth) -- memoized cache will miss!\n")
}
res = f(i)
cache[i] = res
if logCacheMiss {
for i in 0..<cacheMissDepth {
print(" ")
}
print("depth:\(cacheMissDepth) -- memoized cache did miss \(res)!\n")
}
}
return res!
}
}
func fix<D,R>(almost:(D->R)->(D->R))->(D->R) {
return almost {(args:D)->R in
return fix(almost)(args)
}
}
// delay/force
struct Delay<T> {
let _val:()->T
init(_ val: @autoclosure ()->T) {
_val = memoize(val)
}
init(_ val:()->T) {
_val = memoize(val)
}
func force()->T {
return _val()
}
}
extension Optional {
func chain<U>(f:T->U?)->U? {
switch self {
case .None: return nil
case let .Some(x): return f(x)
}
}
}
extension Array {
func flatmap<U>(transform: (T) -> [U]) -> [U] {
return map(transform).reduce(Array<U>(), combine: +)
}
}
func map<T,S>(tup:(T,T), f:T->S)->(S,S) {
let (a,b) = tup
return (f(a),f(b))
}
func map<T,S>(tup:(T,T,T), f:T->S)->(S,S,S) {
let (a,b,c) = tup
return (f(a),f(b),f(c))
}
func map<T,S>(tup:(T,T,T,T), f:T->S)->(S,S,S,S) {
let (a,b,c,d) = tup
return (f(a),f(b),f(c),f(d))
}
func reduce<T,S>(tup:(T,T), ini:S, f:(S,T)->S)->S {
let (a,b) = tup
return f(f(ini,a),b)
}
func reduce<T,S>(tup:(T,T,T), ini:S, f:(S,T)->S)->S {
let (a,b,c) = tup
return f(f(f(ini,a),b),c)
}
func reduce<T,S>(tup:(T,T,T,T), ini:S, f:(S,T)->S)->S {
let (a,b,c,d) = tup
return f(f(f(f(ini,a),b),c),d)
}
func ==<T1:Equatable,T2:Equatable>(x:(T1,T2), y:(T1,T2))->Bool {
let (x1,x2) = x
let (y1,y2) = y
return x1 == y1 && x2 == y2
}
func ==<T1:Equatable,T2:Equatable,T3:Equatable>(x:(T1,T2,T3), y:(T1,T2,T3))->Bool {
let (x1,x2,x3) = x
let (y1,y2,y3) = y
return x1 == y1 && x2 == y2 && x3 == y3
}
// MARK: -
// MARK: Flow Control / Data Structures
// MARK: -
// FIXME: Should be Stream<T>, but hitting bugs in Swift seed 5
struct Stream : Printable, SequenceType {
let _car : Int
let _cdr : ()->Stream?
var car : Int { get { return _car } }
var cdr : Stream? {
return _cdr()
}
init(_ car:Int, _ cdr:@autoclosure ()->Stream?) {
_car = car
_cdr = memoize(cdr)
}
static func streamWith(next:()->Int?)->Stream? {
switch next() {
case .None: return nilStream
case let .Some(el): return Stream(el, Stream.streamWith(next))
}
}
static func streamWith<Seq:SequenceType where Seq.Generator.Element == Int>(seq:Seq)->Stream? {
var gen = seq.generate()
let next = {()->Int? in return gen.next() }
return streamWith(next)
}
func generate() -> GeneratorOf<Int> {
var nextStream:()->Stream? = {self}
return GeneratorOf<Int> {
if let cur = nextStream() {
let el = cur.car
nextStream = cur._cdr
return el
} else {
return nil
}
}
}
func map(f:Int->Int)->Stream {
return Stream(f(car), cdr?.map(f))
}
func foldr<S>(merge:(Int, @autoclosure()->S)->S)->S {
assert(cdr != nil, "foldr hit the end of the stream!")
return merge(car, cdr!.foldr(merge))
}
func foldl<S>(ini:S, merge:(S,Int)->S)->S {
// recursive version wasn't tail calling
// we pass self.generate() rather than self here because reduce will retain the entire stream if you pass self
// this can lead to a stack overflow when the stream is deallocated, as the deallocation of each cell calls deallocation of the next
// side note: large streams must be deallocated as you go or never! if you try to kill it all at once, overflow.
return reduce(self.generate(), ini, merge)
}
func count()->Int {
return foldl(0, merge: { (countSoFar:Int, _) -> Int in
return countSoFar + 1
})
}
// index of first match
func find(pred:Int->Bool)->Int {
return takeWhile({!pred($0)})?.count() ?? 0
}
func takeWhile(pred:Int->Bool)->Stream? {
if pred(car) {
return Stream(car, cdr.chain({$0.takeWhile(pred)}))
} else {
return nil
}
}
func take(n:Int)->Stream? {
switch n {
case 0: return nil
case 1: return Stream(car,nilStream)
default:
return Stream(car, cdr?.take(n-1))
}
}
func skip(n:Int)->Stream? {
switch n {
case 0: return self
case _: return cdr?.skip(n-1)
}
}
var last : Int {
switch cdr {
case .None: return car
case let .Some(next): return next.last
}
}
func filter(pred:Int->Bool)-> Stream?{
// not tail calling as required
// if pred(car) {
// return Stream(car, cdr?.filter(pred))
// } else {
// return cdr?.filter(pred)
// }
return Stream.streamWith(lazy(self).filter(pred))
}
func uniq()-> Stream?{
var prev : Int? = nil
return self.filter {
if ($0 == prev) {
return false
} else {
prev = $0
return true
}
}
}
func interleave(other:Stream?) -> Stream {
return Stream(car, other?.interleave(cdr) ?? cdr)
}
subscript (r:Range<Int>)->Stream? {
switch (r.startIndex, r.endIndex) {
case (0,0):return nil
case let (0,end): return Stream(car,cdr?[Range(start: 0, end: end-1)])
case let (start,end): return cdr?[Range(start: start-1, end: end-1)]
}
}
subscript (i: Int) -> Int? {
switch i {
case 0: return car
case _: return cdr?[i-1]
}
}
var description : String {
return Array(self[0...4]!).description
}
}
func +(s1:Stream?, s2:Stream?) -> Stream? {
if s1 == nil {
return s2
} else if s2 == nil {
return s1
} else {
return Stream(s1!.car + s2!.car, s1!.cdr + s2!.cdr)
}
}
func *(coeff:Int, s:Stream) -> Stream {
return Stream(coeff * s.car, coeff * s.cdr)
}
func *(coeff:Int, optS:Stream?) -> Stream? {
if let s = optS {
return coeff * s
} else {
return nil
}
}
func *(optS:Stream?, coeff:Int) -> Stream? {
return coeff * optS
}
func *(s:Stream, coeff:Int) -> Stream? {
return coeff * s
}
// boo, crashing the compiler
func mergeSortedStreams(s1:Stream?, s2:Stream?, op:(Int?,Int?)->Int?)->Stream? {
switch (s1?.car, s2?.car) {
case (nil,nil):
return nilStream
case let (.Some(s1car), s2car) where s2car == nil || s1car < s2car!:
let next = { mergeSortedStreams(s1?.cdr, s2, op) }
if let el = op(s1car, nil) {
return Stream(el, next())
} else {
return next()
}
case let (s1car, .Some(s2car)) where s1car == nil || s2car < s1car!:
let next = {mergeSortedStreams(s1, s2?.cdr, op)}
if let el = op(nil, s2car) {
return Stream(el, next())
} else {
return next()
}
default:
// this should be a case statement above, but compiler is crashing
// case let (.Some(s1car), .Some(s2car)) where s1car == s2car:
let next = {mergeSortedStreams(s1?.cdr, s2?.cdr, op)}
if let el = op(s1!.car, s1!.car) {
return Stream(el, next())
} else {
return next()
}
}
}
// WARNING: not sure I want to keep this
struct StreamGen<T> : GeneratorType {
var thunk:()->(val:T?,next:StreamGen<T>)
mutating func next() -> T? {
let (val,next) = thunk()
thunk = next.thunk
return val
}
init(thunk aThunk:()->(val:T?,next:StreamGen<T>)) {
thunk = aThunk
}
init<Gen:GeneratorType where Gen.Element == T>(inout gen:Gen) {
thunk = {
return (gen.next(), StreamGen(gen: &gen))
}
}
}
func cartesianProduct<E1, E2>(s1:[E1], s2:[E2]) -> Array<(E1,E2)> {
var productArray = Array<(E1,E2)>()
productArray.reserveCapacity(s1.count*s2.count)
for e1 in s1 {
for e2 in s2 {
let pair = (e1,e2)
productArray.append(pair)
}
}
return productArray
}
func cartesianProduct<E1, E2>(s1:Range<E1>, s2:Range<E2>) -> Array<(E1,E2)> {
return cartesianProduct(Array(s1), Array(s2))
}
//
//func cartesianProduct<Seq1:SequenceType,Seq2:SequenceType>(seq1:Seq1, seq2:Seq2) -> GeneratorOf<(Seq1.Generator.Element,Seq2.Generator.Element)> {
// typealias E1 = Seq1.Generator.Element
// typealias E2 = Seq2.Generator.Element
// var seq1Gen = seq1.generate()
// var liveSeq2Generators = Array<(E1,()->E2)>()
// var col = 0
// return GeneratorOf<(E1,E2)> {
// while true {
// if col >= liveSeq2Generators.count {
// if let nextE1 = seq1Gen.next() {
// liveSeq2Generators.append( (nextE1,seq2.generate().next) )
// col = 0
// } else if col > 0 {
// col = 0
// } else {
// return nil
// }
// }
//
// let (e1, e2nextFunc) = liveSeq2Generators[col]
// if let e2 = e2nextFunc() {
// col++
// return (e1, e2)
// } else {
// liveSeq2Generators.removeAtIndex(col)
// }
// }
// }
//}
//class IntSeq : Swift.Sequence {
// let _subscriptFunc:(Int)->Int
// var _cacheGen : GeneratorOf<Int>
// var _cache = NSMutableIndexSet(index:0)
//
// init(subscriptFunc:(Int)->Int) {
// _subscriptFunc = subscriptFunc
// _cacheGen = subscriptGen(_subscriptFunc)
// }
//
// convenience init<G:GeneratorType where G.Element == Int>(gen:G) {
// var gen2 = gen
// var array = [Int]()
// self.init(subscriptFunc:{
// (i:Int)->Int in
// while i >= array.count {
// if let el = gen2.next() {
// array.append(el)
// } else {
// break
// }
// }
// return array[i]
// })
// }
//
// convenience init<Seq:SequenceType where Seq.Generator.Element == Int>(seq:Seq) {
// var gen = seq.generate()
// self.init(gen: gen)
// }
//
//
// subscript (i: Int) -> Int { get {return _subscriptFunc(i)} }
// func generate()-> GeneratorOf<Int> {
// return subscriptGen(_subscriptFunc)
// }
//
// func contains(n:Int) -> Bool {
// while n > _cache.lastIndex {
// _cache.addIndex(_cacheGen.next()!)
// }
// return _cache.containsIndex(n)
// }
//}
// MARK: -
// MARK: Useful Streams
// MARK: -
// a hack to allow referring to a var in its own definition
//
// let ones = Stream(1, ones)
//
// can be written as
//
// let ones : Stream = fixVar {
// Stream(1, $0())
// }
//
// . $0() is the var being defined.
func fixVar<T>(lazySelf:(()->T)->T)->T {
var _tmp:T! = nil
_tmp = lazySelf({_tmp})
return _tmp
}
let nilStream = nil as Stream?
let ones : Stream = fixVar {
Stream(1, $0())
}
let ints : Stream = fixVar {
Stream(1, $0() + ones)
}
let fibs = fixVar {
Stream(1, Stream(2, $0() + $0().cdr))
}
// I like the simple implementation, but the other is a lot faster
#if slowCleanPrimes
let primes = Stream(2, (2 * ints + ones)?.filter(isPrime))
#else
var _primesBacking = [2,3]
func _extendPrimesBacking()->Int {
var candidate = _primesBacking.last!
nextCandidate: while true {
candidate += 2
let maxDivisor = Int(sqrt(Double(candidate)))
for p in _primesBacking {
if p > maxDivisor {
break
} else if divides(candidate, p) {
continue nextCandidate
}
}
_primesBacking.append(candidate)
return candidate
}
}
let primes = Stream(2, Stream(3, Stream.streamWith({return _extendPrimesBacking()})))
#endif
func triangleNum(i:Int)->Int {
return i * (i + 1) / 2
}
func isTriangleNum(x:Int)->Bool {
/*
we know t(n) = ½n(n+1). Can we compute the inverse?
2*t(n) = n^2 + n
2*t(n) + 1/4 = n^2 + n + 1/4
2*t(n) + 1/4 = (n+1/2)^2
sqrt(2*t(n) + 1/4) = n+1/2
sqrt(2*t(n) + 1/4) - 1/2 = n
so, tInverse(x) = sqrt(2*x + 1/4) - 1/2
*/
let candidateInverse = Int(round(sqrt(2*Double(x) + 0.25) - 0.5))
return x == candidateInverse * (candidateInverse + 1) / 2
}
func pentagonalNum(n:Int)->Int {
return n*(3 * n - 1) / 2
}
func isPentagonalNum(x:Int)->Bool {
// Pn=n(3n−1)/2. What's P inverse?
// x = Pinv(x)(3*Pinv(x) - 1) / 2
// 2/3 x = Pinv(x)**2 - 1/3 Pinv(x)
// 2/3 x + 1/36 = Pinv(x)**2 - 1/3 Pinv(x) + 1/36
// 2/3 x + 1/36 = (Pinv(x) - 1/6)**2
// sqrt(2/3 x + 1/36) = Pinv(x) - 1/6
// Pinv(x) = sqrt(2/3 x + 1/36) + 1/6
let candidateSequenceIndex = Int(round(sqrt(2*Double(x)/3 + 1.0/36.0) + 1.0/6.0))
return x == pentagonalNum(candidateSequenceIndex)
}
func hexagonalNum(n:Int)->Int {
return n*(2*n - 1)
}
func isHexagonalNum(n:Int)->Bool {
// HInv(n)*(2*HInv(n) - 1) = n
// HInv(n)**2 - 1/2 HInv(n) = 1/2 n
// HInv(n)**2 - 1/2 HInv(n) + 1/4 = 1/2 n + 1/4
// (HInv(n) - 1/4)**2 = 1/2 n + 1/4
// HInv(n) - 1/4 = sqrt(1/2 n + 1/4)
// HInv(n) = sqrt(1/2 n + 1/4) + 1/4
let candidateSequenceIndex = Int(round(sqrt(Double(n)/2 + 0.25) + 0.25))
return n == hexagonalNum(candidateSequenceIndex)
}
// MARK: -
// MARK: accumulator
// MARK: -
struct Accumulator<S,T> {
var val : T
let _merge : (T,S)->T
init(initial:T, merge:(T,S)->T) {
val = initial
_merge = merge
}
mutating func merge(x:S) {
val = _merge(val, x)
}
}
// MARK: -
// MARK: Math
// MARK: -
func divides(n:Int, maybeFactor:Int)->Bool {
return n % maybeFactor == 0
}
func isEven(n:Int)->Bool {
return divides(n, 2)
}
func isPalindrome<T : Equatable>(arr:[T])->Bool {
for i in 0...arr.count/2 {
if arr[i] != arr[arr.count-1-i] {
return false
}
}
return true
}
var logPrimes = false
// Input: n >= 0, an integer to be tested for primality;
// Input: k, a parameter that determines the accuracy of the test
// Output: composite if n is composite, otherwise probably prime
func isPrimeRabinMiller(n:Int, k:Int) -> Bool {
if n <= 1 { return false }
if n == 2 { return true }
if n == 3 { return true }
if n % 2 == 0 { return false }
// Input: n > 3, an odd integer to be tested for primality;
// write n − 1 as 2**s·d with d odd by factoring powers of 2 from n − 1
var s = 0
var d = n-1
while d % 2 == 0 {
s++
d /= 2
}
// WitnessLoop: repeat k times:
WitnessLoop: for _ in 1...k {
// pick a random integer a in the range [2, n − 2]
let a = arc4random_uniform(n-3)+2
// x ← a**d mod n
var x = powmod(a, d, n)
switch x {
// if x = 1 or x = n − 1 then do next WitnessLoop
case 1, n-1: continue WitnessLoop
default:
// repeat s − 1 times:
for _ in 0..<(s-1) {
// x ← x2 mod n
x = powmod(x, 2, n)
switch x {
// if x = 1 then return composite
case 1: return false
// if x = n − 1 then do next WitnessLoop
case n-1: continue WitnessLoop
default:
break
}
}
}
// return composite
return false
}
if logPrimes {
n***
}
return true
}
func isPrime(n:Int) -> Bool {
return isPrimeRabinMiller(n, 10)
}
func square(n:Int)->Int {
return n*n
}
func isSquare(n:Int)->Bool {
let candidateRoot = Int(round(sqrt(Double(n))))
return square(candidateRoot) == n
}
func gcd(a:Int, b:Int)->Int {
switch b {
case 0: return a
case _: return gcd(b, a % b)
}
}
func maxInt(a:Int, b:Int)->Int {
return max(a,b)
}
func _maxIndex<T1:Comparable>(a:T1, b:T1)->Int {
if a > b {
return 0
} else {
return 1
}
}
func _maxIndex<T1:Comparable,T2:Comparable>(a:(T1,T2), b:(T1,T2))->Int {
let (a1,a2) = a
let (b1,b2) = b
if a1 > b1 {
return 0
} else if a1 == b1 {
return _maxIndex(a2,b2)
} else {
return 1
}
}
func _maxIndex<T1:Comparable,T2:Comparable,T3:Comparable>(a:(T1,T2,T3), b:(T1,T2,T3))->Int {
let (a1,a2,a3) = a
let (b1,b2,b3) = b
if a1 > b1 {
return 0
} else if a1 == b1 {
return _maxIndex((a2,a3),(b2,b3))
} else {
return 1
}
}
func max<T1:Comparable,T2:Comparable>(a:(T1,T2), b:(T1,T2))->(T1,T2) {
return _maxIndex(a,b) == 0 ? a : b
}
func _maxIndex<T1:Comparable,T2:Comparable,T3:Comparable>(a:(T1,T2,T3), b:(T1,T2,T3))->(T1,T2,T3) {
return _maxIndex(a,b) == 0 ? a : b
}
func mulmod(aIn:Int, bIn:Int, mod:Int) -> Int {
let (prod, overflow) = Int.multiplyWithOverflow(aIn, bIn)
if !overflow {
return prod % mod
} else {
var (a,b,mod) = (aIn,bIn,mod)
var res = 0;
while (a != 0) {
if (a % 2 == 1) {
res = (res + b) % mod
}
a /= 2
b = b*2 % mod;
}
return res;
}
}
func _pow(b:Int, e:Int, coeff:Int)->Int {
if e == 0 {
return coeff
} else if isEven(e) {
return _pow(b*b,e/2,coeff)
} else {
return _pow(b,e-1,coeff*b)
}
}
func pow(b:Int, e:Int)->Int {
return _pow(b, e, 1)
}
func _powmod(b:Int, e:Int, mod:Int, coeff:Int)->Int {
if e == 0 {
return coeff
} else if isEven(e) {
return _powmod(mulmod(b,b,mod),e/2, mod, coeff)
} else {
return _powmod(b, e-1, mod, mulmod(coeff,b,mod))
}
}
func powmod(b:Int, e:Int, mod:Int)->Int {
return _powmod(b % mod, e, mod, 1)
}
func arc4random_uniform(n:Int) -> Int {
if n <= Int(UInt32.max) {
return Int(arc4random_uniform(UInt32(n)))
} else {
let hi = n / (2 << 30)
let lo = n % (2 << 30)
let hiRand = Int(arc4random_uniform(UInt32(hi)))
let loRand = Int(arc4random_uniform(UInt32(lo)))
return hiRand*(2 << 30) + loRand
}
}
typealias SparseArray = [(Int,Int)]
func componentwiseOp(a:SparseArray, b:SparseArray, op:(Int,Int)->Int) -> SparseArray {
var c = SparseArray()
var aCursor = 0
var bCursor = 0
while (aCursor < a.count && bCursor < b.count) {
let (aIndex, aVal) = a[aCursor]
let (bIndex, bVal) = b[bCursor]
if (aIndex < bIndex) {
let term = (aIndex, op(aVal, 0))
c.append(term)
aCursor++
} else if (aIndex == bIndex) {
let term = (aIndex, op(aVal, bVal))
c.append(term)
aCursor++
bCursor++
} else {
let term = (bIndex, op(0, bVal))
c.append(term)
bCursor++
}
}
while aCursor < a.count {
let (aIndex, aVal) = a[aCursor++]
let term = (aIndex, op(aVal, 0))
c.append(term)
}
while bCursor < b.count {
let (bIndex, bVal) = b[bCursor++]
let term = (bIndex, op(0, bVal))
c.append(term)
}
return c
}
func +(a:SparseArray, b:SparseArray) -> SparseArray {
return componentwiseOp(a, b, +)
}
func *(coeff:Int, a:SparseArray) -> SparseArray {
var res = a
for i in 0..<res.count {
let (place, value) = res[i]
res[i] = (place, coeff*value)
}
return res
}
func max(a:SparseArray, b:SparseArray) -> SparseArray {
return componentwiseOp(a, b, max)
}
typealias Factors = SparseArray // 20 = 2**2 * 5**1 == [(2,2),(5,1)]
func factor(n:Int)->Factors {
var unfactored = n
var factors = Factors()
for p in primes {
var power = 0
while divides(unfactored, p) {
power++
unfactored /= p
}
if power > 0 {
factors.append((p,power) as (Int,Int))
}
if unfactored == 1{
break
}
}
return factors
}
func unfactor(factors:Factors)->Int {
return factors.map({pow($0, $1)}).reduce(1, combine: *)
}
func *(a:Factors, b:Factors) -> Factors {
return ((a as SparseArray) + (b as SparseArray)) as Factors
}
func /(a:Factors, b:Factors) -> Factors {
return (a as SparseArray) + -1 * (b as SparseArray)
}
func factoredFactorial(n:Int)->Factors {
return Array(1...n).map(factor).reduce(Factors(), combine: *)
}
let factorial : Int->Int = {
var fac : (Int->Int)!
func _fac(n:Int)->Int {
switch n {
case 0,1: return 1
case _: return n * fac(n-1)
}
}
fac = denseMemoize(_fac)
return fac
}()
//func almostFactorial(recur:Int->Int)->(n:Int)->Int
//let factorial = fix(almostFactorial)
//let factorial : (Int->Int) = {
// var _factorial : (Int->Int)!
// _factorial = denseMemoize {(n:Int) -> Int in
// switch n {
// case 1: return 1
// case _: return n * _factorial(n-1)
// }
// }
// return _factorial
//}()
func combinations(n:Int, k:Int)->Int {
let numerFactors = factoredFactorial(n)
let denomFactors = factoredFactorial(n-k) * factoredFactorial(k)
let simplifiedFactors = numerFactors / denomFactors
return unfactor(simplifiedFactors)
}
func divisorsCount(n:Int) -> Int {
return factor(n).map({$1+1}).reduce(1,*)
}
func allProductsUsingSubsetsOfFactors(factors:Slice<(Int,Int)>)->[Int] {
// all products will either
// (1) use the first factor or
// (2) not
// that's how we can recurse.
if factors.count == 0 {
return [1]
} else {
let productsNotUsingFirstFactor = allProductsUsingSubsetsOfFactors(factors[1..<factors.count])
let (prime,power) = factors[0]
let divisorsOfFirstTerm = Array(1...power).map { pow(prime,$0) }
let productsUsingFirstFactor = lazy(cartesianProduct(divisorsOfFirstTerm, productsNotUsingFirstFactor)).map {$0*$1}
return productsUsingFirstFactor + productsNotUsingFirstFactor
}
}
func divisors(n:Int) ->[Int] {
return allProductsUsingSubsetsOfFactors(Slice<(Int,Int)>(factor(n))).sorted(<)
}
func properDivisors(n:Int) ->[Int] {
return divisors(n).filter({n != $0})
}
func permutationsGen<T>(inArray : [T]) -> GeneratorOf<[T]> {
let numEls = inArray.count
var counters = Array<Int>(count: numEls, repeatedValue: 0)
counters[0] = -1
var array = inArray
return GeneratorOf<[T]> {
for n in 0..<numEls {
let c = counters[n]
let i1 = n % 2 == 0 ? 0 : c
let i2 = n
swap(&array[i1], &array[i2])
if c < n {
counters[n]++
for i in 0..<n {
counters[i] = 0
}
return array
}
}
return nil
}
}
// MARK: -
// MARK: Digits
// MARK: -
func digits(n:Int, # base:Int)->[Int] {
var digits = [Int]()
var rest = n
while rest != 0 {
digits.append(rest % base)
rest /= base
}
return digits
}
func digits(n:Int)->[Int] {
return digits(n, base:10)
}
extension Int {
init<Seq:SequenceType where Seq.Generator.Element == Int>(digits:Seq) {
var res = 0
for dig in digits {
res*=10
res+=dig
}
self.init(res)
}
}
func digitsToBitfield(digits:[Int])->UInt {
var bitfield:UInt = 0
for digit in digits {
bitfield |= 1 << UInt(digit)
}
return bitfield
}
func digits(xs:[Int], timesCoefficient coeff:Int=1, plusDigits ys:[Int] = [Int](), base:Int = 10)->[Int] {
func digit(zs:[Int], i:Int)->Int {
return i < zs.count ? zs[i] : 0
}
let maxLen = max(xs.count,ys.count)
var sumDigits = [Int]()
sumDigits.reserveCapacity(maxLen)
var carry = 0
var i = 0
while i < maxLen || carry != 0 {
let sum = coeff*digit(xs,i) + digit(ys,i) + carry
sumDigits.append(sum % base)
carry = sum / base
i++
}
return sumDigits
}
| mit | 90176ffaf2053111d30ab4b9af404cdc | 23.997326 | 148 | 0.506721 | 3.221571 | false | false | false | false |
HJliu1123/LearningNotes-LHJ | April/Xbook/Xbook/pushNewBook/VIew/HJPushDescriptionViewController.swift | 1 | 1719 | //
// HJPushDescriptionViewController.swift
// Xbook
//
// Created by liuhj on 16/3/7.
// Copyright © 2016年 liuhj. All rights reserved.
//
import UIKit
typealias HJPushDescriptionViewControllerBlock = (description : String) ->Void
class HJPushDescriptionViewController: UIViewController {
var textView : JVFloatLabeledTextView?
var callBack : HJPushDescriptionViewControllerBlock?
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
self.textView = JVFloatLabeledTextView(frame: CGRectMake(8, 58, SCREEN_WIDTH - 16, SCREEN_HIGHT - 58 - 8))
self.view.addSubview(self.textView!)
self.textView?.placeholder = " 你可以在这里撰写详细的评价、吐槽、介绍~~~"
self.textView?.font = UIFont(name: MY_FONT, size: 17)
self.view.tintColor = UIColor.grayColor()
XKeyBoard.registerKeyBoardHide(self)
XKeyBoard.registerKeyBoardShow(self)
}
func sure() {
self.callBack!(description: (self.textView?.text)!)
self.dismissViewControllerAnimated(true) { () -> Void in
}
}
func close() {
self.dismissViewControllerAnimated(true) { () -> Void in
}
}
func keyboardWillHideNotification(notification : NSNotification) {
self.textView?.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
}
func keyboardWillShowNotification(notification : NSNotification) {
let rect = XKeyBoard.returnKeyBoardWindow(notification)
self.textView?.contentInset = UIEdgeInsetsMake(0, 0, rect.size.height, 0)
}
}
| apache-2.0 | 59f4f5d07fd8d2680e2a40a79138d63a | 27.440678 | 114 | 0.642431 | 4.486631 | false | false | false | false |
lijian5509/KnowLedgeSummarize | 李健凡iOS知识总结 /ContactsF读取联系人/ContactsF读取联系人/MasterViewController.swift | 1 | 3574 | //
// MasterViewController.swift
// ContactsF读取联系人
//
// Created by mini on 15/10/19.
// Copyright © 2015年 mini. All rights reserved.
//
import UIKit
class MasterViewController: UITableViewController {
var detailViewController: DetailViewController? = nil
var objects = [AnyObject]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
self.navigationItem.rightBarButtonItem = addButton
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
}
override func viewWillAppear(animated: Bool) {
self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func insertNewObject(sender: AnyObject) {
objects.insert(NSDate(), atIndex: 0)
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let object = objects[indexPath.row] as! NSDate
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let object = objects[indexPath.row] as! NSDate
cell.textLabel!.text = object.description
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
objects.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
}
| gpl-3.0 | 9a855020fc289a93c2fde3ce9e570c40 | 36.882979 | 157 | 0.693345 | 5.7343 | false | false | false | false |
mylifeasdog/Future | Future.playground/Contents.swift | 1 | 4802 | //: Playground - noun: a place where people can play
import UIKit
enum Result <T, ErrorType>
{
case Success(T)
case Error(ErrorType)
}
enum UserInfoErrorDomain: ErrorType
{
case UserDoesNotExist
case UserRequestFailure(reason: String)
case NetworkRequestFailure(reason: String)
}
enum DownloadImageErrorDomain: ErrorType
{
case Timeout
case Unreachable
case Interrupted
}
struct Future<T, ErrorType>
{
typealias ResultType = Result<T, ErrorType>
typealias Completion = ResultType -> ()
typealias AsyncOperation = Completion -> ()
private let operation: AsyncOperation
init(operation: AsyncOperation)
{
self.operation = operation
}
func start(completion: Completion)
{
self.operation() { result in completion(result) }
}
}
extension Future
{
func map<U>(f: T -> U) -> Future<U, ErrorType>
{
return Future<U, ErrorType>(operation: { completion in
self.start { result in
switch result
{
case .Success(let value):
completion(Result.Success(f(value)))
case .Error(let error):
completion(Result.Error(error))
}
}
})
}
func andThen<U>(f: T -> Future<U, ErrorType>) -> Future<U, ErrorType>
{
return Future<U, ErrorType>(operation: { completion in
self.start { firstFutureResult in
switch firstFutureResult
{
case .Success(let value): f(value).start(completion)
case .Error(let error): completion(Result.Error(error))
}
}
})
}
}
struct User { let avatarURL: NSURL }
func downloadFile(URL: NSURL) -> Future<NSData, UserInfoErrorDomain>
{
return Future() { completion in
let result: Result<NSData, UserInfoErrorDomain>
// NSData(contentsOfURL: <#T##NSURL#>) not working with given URL in Playground
if let data = UIImageJPEGRepresentation(UIImage(named: URL.absoluteString)!, 1.0)
{
result = Result.Success(data)
}
else
{
result = Result.Error(.NetworkRequestFailure(reason: "Time out"))
}
completion(result)
}
}
func requestUserInfo(userID: String) -> Future<User, UserInfoErrorDomain>
{
if (userID == "1234")
{
return Future() { (completion) in completion(Result.Success(User(avatarURL: NSURL(string: "nyan_cat.jpeg")!))) }
}
else
{
return Future() { (completion) in completion(Result.Error(.UserDoesNotExist)) }
}
}
func downloadImage(URL: NSURL) -> Future<UIImage, UserInfoErrorDomain>
{
return downloadFile(URL).map { UIImage(data: $0)! }
}
func loadAvatar(userID: String) -> Future<UIImage, UserInfoErrorDomain>
{
return requestUserInfo(userID)
.map { $0.avatarURL }
.andThen(downloadImage)
}
// Success
loadAvatar("1234").start() { result in
switch result
{
case .Success(let avatar):
avatar
case .Error(let error):
do
{
throw error
}
catch UserInfoErrorDomain.UserDoesNotExist
{
print("UserDoesNotExist")
}
catch UserInfoErrorDomain.UserRequestFailure(let reason)
{
print("UserRequestFailure reason : \(reason)")
}
catch UserInfoErrorDomain.NetworkRequestFailure(let reason)
{
print("NetworkRequestFailure reason : \(reason)")
}
catch is DownloadImageErrorDomain
{
print("Error while downloading image")
}
catch _
{
print("There is an error.")
}
}
}
// Fail
loadAvatar("abc").start { result in
switch result
{
case .Success(let avatar):
avatar
case .Error(let error):
do
{
throw error
}
catch UserInfoErrorDomain.UserDoesNotExist
{
print("UserDoesNotExist")
}
catch UserInfoErrorDomain.UserRequestFailure(let reason)
{
print("UserRequestFailure reason : \(reason)")
}
catch UserInfoErrorDomain.NetworkRequestFailure(let reason)
{
print("NetworkRequestFailure reason : \(reason)")
}
catch is DownloadImageErrorDomain
{
print("Error while downloading image")
}
catch _
{
print("There is an error.")
}
}
}
| mit | ff8722e7d1796e5da432e196a8a194ef | 23.880829 | 120 | 0.549146 | 4.915046 | false | false | false | false |
jindulys/Leetcode_Solutions_Swift | Sources/Sort/75_SortColors.swift | 1 | 1465 | //
// 75_SortColors.swift
// LeetcodeSwift
//
// Created by yansong li on 2016-11-20.
// Copyright © 2016 YANSONG LI. All rights reserved.
//
import Foundation
/**
Title:75 Sort Colors
URL: https://leetcode.com/problems/sort-colors/
Space: O(NlgN)
Time: O(N)
*/
class SortColors_Solution {
func sortColors(_ nums: inout [Int]) {
mergeSort(&nums)
}
func mergeSort(_ nums: inout [Int]) {
if nums.count == 1 {
return
}
let mid = nums.count / 2
var firstHalf = Array(nums.prefix(upTo: mid))
var lastHalf = Array(nums.suffix(from: mid))
mergeSort(&firstHalf)
mergeSort(&lastHalf)
let firstLength = firstHalf.count
let lastLength = lastHalf.count
var firstPos = 0
var lastPos = 0
var currentIndex = 0
while firstPos <= firstLength - 1 && lastPos <= lastLength - 1 {
if firstHalf[firstPos] <= lastHalf[lastPos] {
nums[currentIndex] = firstHalf[firstPos]
firstPos += 1
} else {
nums[currentIndex] = lastHalf[lastPos]
lastPos += 1
}
currentIndex += 1
}
while firstPos <= firstLength - 1 {
nums[currentIndex] = firstHalf[firstPos]
firstPos += 1
currentIndex += 1
}
while lastPos <= lastLength - 1 {
nums[currentIndex] = lastHalf[lastPos]
lastPos += 1
currentIndex += 1
}
}
func test() {
var nums = [0, 1, 1, 2, 0]
sortColors(&nums)
print(nums)
}
}
| mit | 7b133004729ce1cb8e8598efc81446fa | 21.181818 | 68 | 0.595628 | 3.494033 | false | false | false | false |
kickerchen/PayByCrush | PayByCrush/GameScene.swift | 1 | 17675 | //
// GameScene.swift
// PayByCrush
//
// Created by CHENCHIAN on 7/29/15.
// Copyright (c) 2015 KICKERCHEN. All rights reserved.
//
import SpriteKit
let TileWidth: CGFloat = 44.0
let TileHeight: CGFloat = 44.0
typealias swipeResponder = (swap: PBCSwap) -> Void
class GameScene: SKScene {
var level: PBCLevel!
var swipeHandler: swipeResponder?
var gameLayer: SKNode!
var paymentLayer: SKNode!
var tilelayer: SKNode!
var swipeFromColumn: Int = NSNotFound
var swipeFromRow: Int = NSNotFound
var selectedSprite: SKSpriteNode = SKSpriteNode()
let matchSound: SKAction = SKAction.playSoundFileNamed("Sounds/cash register.wav", waitForCompletion: false)
let fascinating: SKAction = SKAction.playSoundFileNamed("Sounds/Spock_Fascinating.wav", waitForCompletion: false)
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initialize()
}
override init(size: CGSize) {
super.init(size: size)
self.initialize()
}
func initialize() {
self.anchorPoint = CGPointMake(0.5, 0.5)
// set backgorund
let background = SKSpriteNode(imageNamed: "Background")
background.alpha = 0.2
self.addChild(background)
//
self.gameLayer = SKNode()
self.gameLayer.hidden = true
self.addChild(gameLayer)
let layerPosition = CGPointMake(-TileWidth*CGFloat(NumColumns)/2.0, -TileHeight*CGFloat(NumRows)/2.0)
self.tilelayer = SKNode()
self.tilelayer.position = layerPosition
self.gameLayer.addChild(self.tilelayer)
self.paymentLayer = SKNode()
self.paymentLayer.position = layerPosition
self.gameLayer.addChild(self.paymentLayer)
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch in (touches as! Set<UITouch>) {
let location = touch.locationInNode(self.paymentLayer)
var column: Int = NSNotFound, row: Int = NSNotFound
if self.convertPoint(location, toColumn: &column, toRow: &row) {
// Check the touch is on a payment rather than on an empty square
if let payment = self.level.paymentAtColumn(column, row: row) {
// Record the column and row where the swipe started
// so you can compare them later to find the direction of the swipe
self.swipeFromColumn = column
self.swipeFromRow = row
self.showSelectionIndicatorForPayment(payment)
}
}
}
}
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
// Ignore
if self.swipeFromColumn == NSNotFound { return }
for touch in (touches as! Set<UITouch>) {
let location = touch.locationInNode(self.paymentLayer)
var column: Int = NSNotFound, row: Int = NSNotFound
if self.convertPoint(location, toColumn: &column, toRow: &row) {
// Diagonal swipe is not allowed,
// so we use else if statements, only one of horzDelta or vertDelta will be set.
var horzDelta: Int = 0, vertDelta: Int = 0
if column < self.swipeFromColumn {
horzDelta = -1
} else if column > self.swipeFromColumn {
horzDelta = 1
} else if row < self.swipeFromRow {
vertDelta = -1
} else if row > self.swipeFromRow {
vertDelta = 1
}
if horzDelta != 0 || vertDelta != 0 {
// try swap
self.trySwapHorizontal(horzDelta, vertDelta: vertDelta)
// reset
self.hideSelectionIndicator()
self.swipeFromColumn = NSNotFound
self.swipeFromRow = NSNotFound
}
}
}
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
// If the user just taps on the screen rather than swipes,
// you want to fade out the highlighted sprite, too.
if let parent = self.selectedSprite.parent {
if self.swipeFromColumn != NSNotFound {
self.hideSelectionIndicator()
}
}
self.swipeFromColumn = NSNotFound
self.swipeFromRow = NSNotFound
}
override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) {
self.touchesEnded(touches, withEvent: event)
}
// MARK: - Instance Methods
func addSpritesForPayments(payments: NSSet) {
self.paymentLayer.removeAllChildren()
for payment in payments {
if let payment = payment as? PBCPayment {
let sprite = SKSpriteNode(imageNamed: payment.spriteName)
sprite.position = self.pointForColumn(payment.column, row: payment.row)
self.paymentLayer.addChild(sprite)
payment.sprite = sprite
payment.sprite?.alpha = 0
payment.sprite?.xScale = 0.5
payment.sprite?.yScale = 0.5
payment.sprite?.runAction(SKAction.sequence([
SKAction.waitForDuration(0.25, withRange: 0.5),
SKAction.group([
SKAction.fadeInWithDuration(0.3),
SKAction.scaleTo(1.0, duration: 0.3)
])
]))
}
}
}
func addTiles() {
self.tilelayer.removeAllChildren()
for row in 0...NumRows-1 {
for column in 0...NumColumns-1 {
if self.level.tileAtColumn(column, row: row) == 1 {
let tileNode = SKSpriteNode(imageNamed: "Tile")
tileNode.position = self.pointForColumn(column, row: row)
self.tilelayer.addChild(tileNode)
}
}
}
}
// MARK: - Animation Related Instance Methods
func animateSwap(swap: PBCSwap, completion: dispatch_block_t) {
// Put the payment you started with on top.
swap.paymentA.sprite!.zPosition = 100
swap.paymentB.sprite!.zPosition = 90
let duration: NSTimeInterval = 0.3
let moveA = SKAction.moveTo(swap.paymentB.sprite!.position, duration: duration)
moveA.timingMode = .EaseOut
swap.paymentA.sprite!.runAction(SKAction.sequence([moveA, SKAction.runBlock(completion)]))
let moveB = SKAction.moveTo(swap.paymentA.sprite!.position, duration: duration)
moveB.timingMode = .EaseOut
swap.paymentB.sprite!.runAction(moveB)
}
func animateInvalidSwap(swap: PBCSwap, completion: dispatch_block_t) {
swap.paymentA.sprite!.zPosition = 100
swap.paymentB.sprite!.zPosition = 90
let duration: NSTimeInterval = 0.2
let moveA = SKAction.moveTo(swap.paymentB.sprite!.position, duration: duration)
moveA.timingMode = .EaseOut
let moveB = SKAction.moveTo(swap.paymentA.sprite!.position, duration: duration)
moveB.timingMode = .EaseOut
swap.paymentA.sprite!.runAction(SKAction.sequence([moveA, moveB, SKAction.runBlock(completion)]))
swap.paymentB.sprite!.runAction(SKAction.sequence([moveB, moveA]))
}
func animateMatchedPayments(chains: Set<PBCChain>, completion: dispatch_block_t) {
for chain in chains {
self.animateScoreForChain(chain)
for payment in chain.payments {
// The same PBCPayment could be part of two chains (one horizontal and one vertical), but you only want to add one animation to the sprite. This check ensures that you only animate the sprite once.
if payment.sprite != nil {
//
let scaleAction = SKAction.scaleTo(0.1, duration: 0.3)
scaleAction.timingMode = .EaseOut
payment.sprite!.runAction(SKAction.sequence([scaleAction, SKAction.removeFromParent()]))
// remove the link between the PBCPayment and its sprite as soon as you’ve added the animation.
payment.sprite = nil
}
}
}
// play sound
self.runAction(self.matchSound)
// only continue with the rest of the game after the animations finish
self.runAction(SKAction.sequence([
SKAction.waitForDuration(0.3),
SKAction.runBlock(completion)
]))
}
func animateFallingPayments(columns: Array<Array<PBCPayment>>, completion: dispatch_block_t) {
var longestDuration: Double = 0
for array in columns {
(array as NSArray).enumerateObjectsUsingBlock({(object, index, stop) in
let payment = object as! PBCPayment
let newPosition = self.pointForColumn(payment.column, row: payment.row)
// The higher up the payment is, the bigger the delay on the animation. That looks more dynamic than dropping all the payments at the same time. This calculation works because fillHoles guarantees that lower payments are first in the array.
let delay: Double = 0.1 * NSTimeInterval(index)
// Falling speed is 10 tiles/sec = 0.1 sec/tile
let duration: Double = (Double(payment.sprite!.position.y - newPosition.y) / Double(TileHeight)) * 0.1
// Calculate the longest duration to wait for animation to finish
longestDuration = max(longestDuration, duration + delay)
// Perform animations
let moveAction = SKAction.moveTo(newPosition, duration: duration)
moveAction.timingMode = .EaseOut
payment.sprite!.runAction(SKAction.sequence([
SKAction.waitForDuration(delay),
moveAction
]))
})
}
self.runAction(SKAction.sequence([
SKAction.waitForDuration(longestDuration),
SKAction.runBlock(completion)
]))
}
func animateNewPayments(columns: Array<Array<PBCPayment>>, completion: dispatch_block_t) {
var longestDuration: Double = 0
for array in columns {
var startRow = array.first!.row + 1
(array as NSArray).enumerateObjectsUsingBlock({(object, index, stop) in
let payment = object as! PBCPayment
let sprite = SKSpriteNode(imageNamed: payment.spriteName)
sprite.position = self.pointForColumn(payment.column, row: startRow)
self.paymentLayer.addChild(sprite)
payment.sprite = sprite
// The higher the payment, the longer you make the delay, so the payments appear to fall after one another.
let delay: Double = 0.2 * Double(array.count - index - 1)
let duration: Double = Double(startRow - payment.row) * 0.1
longestDuration = max(longestDuration, duration + delay)
// Perform animation
let newPosition = self.pointForColumn(payment.column, row: payment.row)
let moveAction = SKAction.moveTo(newPosition, duration: duration)
moveAction.timingMode = .EaseOut
payment.sprite!.alpha = 0 // for fade in
payment.sprite!.runAction(SKAction.sequence([
SKAction.waitForDuration(delay),
SKAction.group([
moveAction,
SKAction.fadeInWithDuration(0.05)
])
]))
})
}
self.runAction(SKAction.sequence([
SKAction.waitForDuration(longestDuration),
SKAction.runBlock(completion)
]))
}
func animateScoreForChain(chain: PBCChain) {
// Figure out where the midpoint of the chain is
if let firstPayment = chain.payments.first {
if let lastPayment = chain.payments.last {
let firstPos = self.pointForColumn(firstPayment.column, row: firstPayment.row)
let lastPos = self.pointForColumn(lastPayment.column, row: lastPayment.row)
let centerPoint = CGPointMake( (firstPos.x + lastPos.x)/2, (firstPos.y + lastPos.y)/2 - 8 )
// Add a label for the score that slowly floats up
let scoreLabel = SKLabelNode(fontNamed: "AmericanTypewriter-Bold")
scoreLabel.fontSize = 17
scoreLabel.text = "$" + chain.score.stringWithCommaSeparator
scoreLabel.position = centerPoint
scoreLabel.zPosition = 300
self.paymentLayer.addChild(scoreLabel)
let moveAction = SKAction.moveBy(CGVectorMake(0, 6), duration: 0.7)
moveAction.timingMode = .EaseOut
scoreLabel.runAction(SKAction.sequence([
SKAction.group([
moveAction,
SKAction.colorizeWithColorBlendFactor(0.5, duration: 0.7)]),
SKAction.removeFromParent()]))
}
}
}
func animateGameOver() {
let action = SKAction.moveBy(CGVectorMake(0, -self.size.height), duration: 0.3)
action.timingMode = .EaseIn
self.gameLayer.runAction(action)
}
func animateBeginGame() {
self.gameLayer.hidden = false
self.gameLayer.position = CGPointMake(0, self.size.height)
let action = SKAction.moveBy(CGVectorMake(0, -self.size.height), duration: 0.3)
action.timingMode = .EaseOut
self.gameLayer.runAction(action)
}
// MARK: - Helper Functions
func preloadResources() {
// When using SKLabelNode, Sprite Kit needs to load the font and convert it to a texture. That only happens once, but it does create a small delay, so it’s smart to pre-load this font before the game starts in earnest.
SKLabelNode(fontNamed: "AmericanTypewriter-Bold")
}
func pointForColumn(column: Int, row: Int) -> CGPoint {
return CGPointMake(CGFloat(column)*TileWidth + TileWidth/2, CGFloat(row)*TileHeight + TileHeight/2)
}
func convertPoint(point: CGPoint, inout toColumn column: Int, inout toRow row: Int) -> Bool {
// Is this a valid location within the payments layer? If yes,
// calculate the corresponding row and column numbers.
if (point.x >= 0 && point.x < CGFloat(NumColumns)*TileWidth &&
point.y >= 0 && point.y < CGFloat(NumRows)*TileHeight) {
column = Int(point.x / TileWidth)
row = Int(point.y / TileHeight)
return true
} else {
column = NSNotFound // invalid location
row = NSNotFound
return false
}
}
func showSelectionIndicatorForPayment(payment: PBCPayment) {
if let parent = self.selectedSprite.parent {
self.selectedSprite.removeFromParent()
}
let texture = SKTexture(imageNamed: payment.hightlightedSpriteName)
self.selectedSprite.size = texture.size()
self.selectedSprite.runAction(SKAction.setTexture(texture))
payment.sprite!.addChild(self.selectedSprite)
self.selectedSprite.alpha = 1.0
}
func hideSelectionIndicator() {
self.selectedSprite.runAction(SKAction.sequence([
SKAction.fadeOutWithDuration(0.3),
SKAction.removeFromParent()
]))
}
func trySwapHorizontal(horzDelta: Int, vertDelta: Int) {
var toColumn = self.swipeFromColumn + horzDelta
var toRow = self.swipeFromRow + vertDelta
if toColumn < 0 || toColumn > NumColumns { return }
if toRow < 0 || toRow > NumRows { return }
if let toPayment = self.level.paymentAtColumn(toColumn, row: toRow) {
if let fromPayment = self.level.paymentAtColumn(self.swipeFromColumn, row: self.swipeFromRow) {
let swap = PBCSwap()
swap.paymentA = fromPayment
swap.paymentB = toPayment
self.swipeHandler?(swap: swap)
}
}
}
}
| mit | 70ce27d03beed9581a48283e8c07d791 | 36.518047 | 256 | 0.554694 | 5.208075 | false | false | false | false |
AidanMatthews/Lifesaver | Lifesaver/Utilities/CurrentLocation.swift | 1 | 1158 | //
// CurrentLocation.swift
// Lifesaver
//
// Created by Grant McSheffrey on 2017-01-19.
// Copyright © 2017 Grant McSheffrey. All rights reserved.
//
import CoreLocation
class CurrentLocation: NSObject, CLLocationManagerDelegate {
static let sharedInstance = CurrentLocation()
let locationManager = CLLocationManager()
var currentCoordinate: CLLocationCoordinate2D
override init() {
self.currentCoordinate = CLLocationCoordinate2D.init()
super.init()
self.locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled() {
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
self.locationManager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
for location in locations {
self.currentCoordinate = location.coordinate
print("Current latitude is \(location.coordinate.latitude), longitude is \(location.coordinate.longitude)")
}
}
}
| mit | 6483dd1a3491f403469f7b2d0f7566a2 | 31.138889 | 119 | 0.706137 | 5.509524 | false | false | false | false |
aotian16/SwiftLog | SwiftLogDemo/SwiftLogDemo/SwiftLog.swift | 1 | 4876 | //
// SwiftLog.swift
// SwiftLogDemo
//
// Created by 童进 on 15/10/12.
// Copyright © 2015年 qefee. All rights reserved.
//
import Foundation
public class SwiftLog {
/// log level. Print logs which >= logLevel
public var logLevel: LogLevel
/// date format
public var dateFormat: String = "yyyy-MM-dd HH:mm:ss.SSS"
{
didSet {
dateFormatter.dateFormat = dateFormat
}
}
/// date formatter
private var dateFormatter: NSDateFormatter = NSDateFormatter()
/**
init with LogLevel.Debug
*/
public convenience init() {
self.init(logLevel: LogLevel.Debug)
}
public init(logLevel: LogLevel) {
self.logLevel = logLevel
self.dateFormatter.dateFormat = dateFormat
}
/**
print verbose log.
- parameter msg: msg
- parameter fileName: fileName
- parameter functionName: functionName
- parameter lineNum: lineNum
- parameter columnNum: columnNum
*/
public func v(msg: String, fileName: String = __FILE__, functionName: String = __FUNCTION__, lineNum: Int = __LINE__, columnNum: Int = __COLUMN__) {
printLog(LogLevel.Verbose, msg: msg, fileName: fileName, functionName: functionName, lineNum: lineNum, columnNum: columnNum)
}
/**
print debug log.
- parameter msg: msg
- parameter fileName: fileName
- parameter functionName: functionName
- parameter lineNum: lineNum
- parameter columnNum: columnNum
*/
public func d(msg: String, fileName: String = __FILE__, functionName: String = __FUNCTION__, lineNum: Int = __LINE__, columnNum: Int = __COLUMN__) {
printLog(LogLevel.Debug, msg: msg, fileName: fileName, functionName: functionName, lineNum: lineNum, columnNum: columnNum)
}
/**
print info log.
- parameter msg: msg
- parameter fileName: fileName
- parameter functionName: functionName
- parameter lineNum: lineNum
- parameter columnNum: columnNum
*/
public func i(msg: String, fileName: String = __FILE__, functionName: String = __FUNCTION__, lineNum: Int = __LINE__, columnNum: Int = __COLUMN__) {
printLog(LogLevel.Info, msg: msg, fileName: fileName, functionName: functionName, lineNum: lineNum, columnNum: columnNum)
}
/**
print warn log.
- parameter msg: msg
- parameter fileName: fileName
- parameter functionName: functionName
- parameter lineNum: lineNum
- parameter columnNum: columnNum
*/
public func w(msg: String, fileName: String = __FILE__, functionName: String = __FUNCTION__, lineNum: Int = __LINE__, columnNum: Int = __COLUMN__) {
printLog(LogLevel.Warn, msg: msg, fileName: fileName, functionName: functionName, lineNum: lineNum, columnNum: columnNum)
}
/**
print error log.
- parameter msg: msg
- parameter fileName: fileName
- parameter functionName: functionName
- parameter lineNum: lineNum
- parameter columnNum: columnNum
*/
public func e(msg: String, fileName: String = __FILE__, functionName: String = __FUNCTION__, lineNum: Int = __LINE__, columnNum: Int = __COLUMN__) {
printLog(LogLevel.Error, msg: msg, fileName: fileName, functionName: functionName, lineNum: lineNum, columnNum: columnNum)
}
/**
print assert log.
- parameter msg: msg
- parameter fileName: fileName
- parameter functionName: functionName
- parameter lineNum: lineNum
- parameter columnNum: columnNum
*/
public func a(msg: String, fileName: String = __FILE__, functionName: String = __FUNCTION__, lineNum: Int = __LINE__, columnNum: Int = __COLUMN__) {
printLog(LogLevel.Assert, msg: msg, fileName: fileName, functionName: functionName, lineNum: lineNum, columnNum: columnNum)
}
/**
print log.
If you want to custom log format, change this function.
- parameter logLevel: logLevel
- parameter msg: msg
- parameter fileName: fileName
- parameter functionName: functionName
- parameter lineNum: lineNum
- parameter columnNum: columnNum
*/
public func printLog(logLevel: LogLevel, msg: String, fileName: String = __FILE__, functionName: String = __FUNCTION__, lineNum: Int = __LINE__, columnNum: Int = __COLUMN__) {
if self.logLevel > logLevel {
return
}
let date = dateFormatter.stringFromDate(NSDate())
let file = NSString(string: fileName).lastPathComponent
let fun = functionName
let line = lineNum
let col = columnNum
let lvl = logLevel
print("\(date) \(file) : \(fun) : \(line) : \(col) \(lvl) \(msg)")
}
}
| mit | ac0f586fd07051c2df70264225412522 | 33.531915 | 179 | 0.6145 | 4.576128 | false | false | false | false |
AlexChekanov/Gestalt | Gestalt/UI/Views/Details/DetailViewController.swift | 1 | 1595 | import UIKit
class DetailViewController: UIViewController {
@IBOutlet var theTitle: UILabel!
var presenter: DetailViewControllerPresenter!
fileprivate weak var navigationCoordinator: NavigationCoordinator?
override func viewDidLoad() {
super.viewDidLoad()
clean()
setupView()
setupStyle()
updateData()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if isMovingFromParentViewController {
navigationCoordinator?.movingBack()
}
}
func configure(with presenter: DetailViewControllerPresenter,
navigationCoordinator: NavigationCoordinator)
{
self.presenter = presenter
self.navigationCoordinator = navigationCoordinator
}
func clean() {
theTitle.text = ""
}
func setupView() {
self.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem
self.navigationItem.leftItemsSupplementBackButton = true
}
func setupStyle() {
self.view.backgroundColor = .orange
}
func updateData () {
guard presenter != nil else { return }
self.theTitle.text = presenter.title
self.title = presenter.title
}
}
//MARK: - Touch Events
extension DetailViewController {
@IBAction func briefcaseTapped(_ button: UIButton) {
let args = ["task": presenter.task!]
navigationCoordinator?.next(arguments: args)
}
}
| apache-2.0 | babd3fca0278537abec11b967b3d1ffa | 23.538462 | 90 | 0.625078 | 5.907407 | false | false | false | false |
ed-chin/EarlGrey | Demo/EarlGreyContribs/EarlGreyContribsSwiftTests/EarlGreyContribsSwiftTests.swift | 4 | 2941 | //
// Copyright 2016 Google Inc.
//
// 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 EarlGrey
import XCTest
class EarlGreyContribsSwiftTests: XCTestCase {
override func tearDown() {
EarlGrey().selectElementWithMatcher(grey_anyOf([grey_text("EarlGreyContribTestApp"),
grey_text("Back")]))
.performAction(grey_tap())
super.tearDown()
}
func testBasicViewController() {
EarlGrey().selectElementWithMatcher(grey_text("Basic Views"))
.usingSearchAction(grey_scrollInDirection(.Down, 50),
onElementWithMatcher: grey_kindOfClass(UITableView.self))
.performAction(grey_tap())
EarlGrey().selectElementWithMatcher(grey_accessibilityLabel("textField"))
.performAction(grey_typeText("Foo"))
EarlGrey().selectElementWithMatcher(grey_accessibilityLabel("showButton"))
.performAction(grey_tap())
EarlGrey().selectElementWithMatcher(grey_accessibilityLabel("textLabel"))
.assertWithMatcher(grey_text("Foo"))
}
func testCountOfTableViewCells() {
var error: NSError? = nil
let matcher: GREYMatcher! = grey_kindOfClass(UITableViewCell.self)
let countOfTableViewCells: UInt = count(matcher)
GREYAssert(countOfTableViewCells > 1, reason: "There are more than one cell present.")
EarlGrey().selectElementWithMatcher(matcher)
.atIndex(countOfTableViewCells + 1)
.assertWithMatcher(grey_notNil(), error: &error)
let errorCode: GREYInteractionErrorCode =
GREYInteractionErrorCode.MatchedElementIndexOutOfBoundsErrorCode
let errorReason: String = "The Interaction element's index being used was over the count " +
"of matched elements available."
GREYAssert(error?.code == errorCode.rawValue, reason:errorReason)
}
}
func count(matcher: GREYMatcher!) -> UInt {
var error: NSError? = nil
var index: UInt = 0
let countMatcher: GREYElementMatcherBlock =
GREYElementMatcherBlock.matcherWithMatchesBlock({ (element: AnyObject?) -> Bool in
if (matcher.matches(element)) {
index = index + 1;
}
return false;
}) { (description: AnyObject?) in
let greyDescription:GREYDescription = description as! GREYDescription
greyDescription.appendText("Count of Matcher")
}
EarlGrey().selectElementWithMatcher(countMatcher)
.assertWithMatcher(grey_notNil(), error: &error);
return index
}
| apache-2.0 | fb65de56673395ea0518bfc17dfe947b | 39.287671 | 96 | 0.710303 | 4.675676 | false | true | false | false |
melling/ios_topics | CollectionViewBasic/CollectionViewBasic/BasicCollectionViewController.swift | 1 | 2763 | //
// BasicCollectionViewController.swift
// CollectionViewBasic
//
// Created by Michael Mellinger on 5/24/16.
//
import UIKit
class BasicCollectionViewController: UICollectionViewController {
private let reuseIdentifier = "Cell"
// MARK: - View Management
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView?.backgroundColor = UIColor.purple
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Register cell classes
self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
}
}
// MARK: - UICollectionViewDataSource
extension BasicCollectionViewController {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 20
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
// Configure the cell
let aColor = indexPath.row % 2 == 0 ? UIColor.orange : UIColor.green
cell.backgroundColor = aColor
return cell
}
// MARK: - UICollectionViewDelegate
/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
*/
/*
// Uncomment this method to specify if the specified item should be selected
override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
*/
/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
return false
}
override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
}
*/
}
| cc0-1.0 | eb0fa7d2fa55c71beb7cb732f817ccad | 30.044944 | 185 | 0.718422 | 6.181208 | false | false | false | false |
apple/swift-syntax | Sources/SwiftParserDiagnostics/PresenceUtils.swift | 1 | 4394 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 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
//
//===----------------------------------------------------------------------===//
@_spi(RawSyntax) import SwiftSyntax
import SwiftBasicFormat
/// Walks a tree and checks whether the tree contained any present tokens.
class PresentNodeChecker: SyntaxAnyVisitor {
var hasPresentToken: Bool = false
override func visitAny(_ node: Syntax) -> SyntaxVisitorContinueKind {
if hasPresentToken {
// If we already saw a present token, we don't need to continue.
return .skipChildren
} else {
return .visitChildren
}
}
override func visit(_ node: TokenSyntax) -> SyntaxVisitorContinueKind {
if node.presence == .present {
hasPresentToken = true
}
return .visitChildren
}
}
extension SyntaxProtocol {
/// Returns `true` if all tokens nodes in this tree are missing.
var isMissingAllTokens: Bool {
let checker = PresentNodeChecker(viewMode: .all)
checker.walk(Syntax(self))
return !checker.hasPresentToken
}
}
/// Transforms a syntax tree by making all missing tokens present.
class PresentMaker: SyntaxRewriter {
override func visit(_ token: TokenSyntax) -> TokenSyntax {
if token.presence == .missing {
let presentToken: TokenSyntax
let (rawKind, text) = token.tokenKind.decomposeToRaw()
if let text = text, !text.isEmpty {
presentToken = TokenSyntax(token.tokenKind, presence: .present)
} else {
let newKind = TokenKind.fromRaw(kind: rawKind, text: rawKind.defaultText.map(String.init) ?? "<#\(rawKind.nameForDiagnostics)#>")
presentToken = TokenSyntax(newKind, presence: .present)
}
return BasicFormat().visit(presentToken)
} else {
return token
}
}
override func visit(_ node: MissingDeclSyntax) -> DeclSyntax {
let leadingTriviaBeforePlaceholder: Trivia
if node.isMissingAllTokens {
leadingTriviaBeforePlaceholder = []
} else if node.modifiers != nil {
leadingTriviaBeforePlaceholder = .space
} else {
leadingTriviaBeforePlaceholder = .newline
}
return DeclSyntax(StructDeclSyntax(
node.unexpectedBeforeAttributes,
attributes: node.attributes,
node.unexpectedBetweenAttributesAndModifiers,
modifiers: node.modifiers,
structKeyword: .structKeyword(presence: .missing),
identifier: .identifier("<#declaration#>", leadingTrivia: leadingTriviaBeforePlaceholder),
genericParameterClause: nil,
inheritanceClause: nil,
genericWhereClause: nil,
members: MemberDeclBlockSyntax(
leftBrace: .leftBraceToken(presence: .missing),
members: MemberDeclListSyntax([]),
rightBrace: .rightBraceToken(presence: .missing)
)
))
}
override func visit(_ node: MissingExprSyntax) -> ExprSyntax {
return ExprSyntax(IdentifierExprSyntax(
identifier: .identifier("<#expression#>"),
declNameArguments: nil
))
}
override func visit(_ node: MissingPatternSyntax) -> PatternSyntax {
return PatternSyntax(IdentifierPatternSyntax(
identifier: .identifier("<#pattern#>")
))
}
override func visit(_ node: MissingStmtSyntax) -> StmtSyntax {
return StmtSyntax(ExpressionStmtSyntax(
expression: ExprSyntax(IdentifierExprSyntax(
identifier: .identifier("<#statement#>"),
declNameArguments: nil
))
))
}
override func visit(_ node: MissingTypeSyntax) -> TypeSyntax {
return TypeSyntax(SimpleTypeIdentifierSyntax(
name: .identifier("<#type#>"),
genericArgumentClause: nil
))
}
override func visit(_ node: MissingSyntax) -> Syntax {
return Syntax(IdentifierExprSyntax(
identifier: .identifier("<#syntax#>"),
declNameArguments: nil
))
}
}
class MissingMaker: SyntaxRewriter {
override func visit(_ node: TokenSyntax) -> TokenSyntax {
guard node.presence == .present else {
return node
}
return TokenSyntax(node.tokenKind, presence: .missing)
}
}
| apache-2.0 | 17df457b6fbff783decdebf66b1a1426 | 31.548148 | 137 | 0.666591 | 4.740022 | false | false | false | false |
iot-spotted/spotted | AppMessage/AppMessage/Controlers/CameraViewController.swift | 1 | 11131 | //
// SimpleCameraController.swift
// SimpleCamera
//
// Created by Simon Ng on 16/10/2016.
// Copyright © 2016 AppCoda. All rights reserved.
//
import UIKit
import AVFoundation
import CloudKit
import EVCloudKitDao
import EVReflection
import Async
class CameraViewController: UIViewController {
@IBOutlet var cameraButton:UIButton!
@IBOutlet var titleLabel:UILabel!
let captureSession = AVCaptureSession()
var backFacingCamera: AVCaptureDevice?
var frontFacingCamera: AVCaptureDevice?
var currentDevice: AVCaptureDevice?
var stillImageOutput: AVCaptureStillImageOutput?
var stillImage: UIImage?
var navTitle: UINavigationItem?
var cameraPreviewLayer:AVCaptureVideoPreviewLayer?
//var toggleCameraGestureRecognizer = UISwipeGestureRecognizer()
var zoomGestureRecognizer = UIPinchGestureRecognizer()
var initialVideoZoomFactor: CGFloat = 0.0
var gameController: GameController? = nil
override func viewDidLoad() {
super.viewDidLoad()
titleLabel.layer.shadowColor = UIColor.black.cgColor
titleLabel.layer.shadowRadius = 50
titleLabel.layer.shadowOpacity = 50
// Preset the session for taking photo in full resolution
captureSession.sessionPreset = AVCaptureSessionPresetiFrame960x540
let devices = AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo) as! [AVCaptureDevice]
// Get the front and back-facing camera for taking photos
for device in devices {
if device.position == AVCaptureDevicePosition.back {
backFacingCamera = device
} else if device.position == AVCaptureDevicePosition.front {
frontFacingCamera = device
}
}
currentDevice = backFacingCamera
do {
let captureDeviceInput = try AVCaptureDeviceInput(device: currentDevice)
// Configure the session with the output for capturing still images
stillImageOutput = AVCaptureStillImageOutput()
stillImageOutput?.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
// Configure the session with the input and the output devices
captureSession.addInput(captureDeviceInput)
captureSession.addOutput(stillImageOutput)
// Provide a camera preview
cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
view.layer.addSublayer(cameraPreviewLayer!)
cameraPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
cameraPreviewLayer?.frame = view.layer.frame
// Bring the camera button to front
view.bringSubview(toFront: cameraButton)
view.bringSubview(toFront: titleLabel)
captureSession.startRunning()
} catch {
print(error)
}
// Toggle Camera recognizer
//toggleCameraGestureRecognizer.direction = .up
//toggleCameraGestureRecognizer.addTarget(self, action: #selector(toggleCamera))
//view.addGestureRecognizer(toggleCameraGestureRecognizer)
// Zoom In recognizer
zoomGestureRecognizer.addTarget(self, action: #selector(zoom))
view.addGestureRecognizer(zoomGestureRecognizer)
}
override func viewDidLayoutSubviews() {
let topBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 60))
topBar.barStyle = UIBarStyle.blackOpaque
topBar.isTranslucent = true
topBar.setBackgroundImage(UIImage(), for: .default)
topBar.shadowImage = UIImage()
topBar.tintColor = UIColor.white
topBar.layer.shadowColor = UIColor.black.cgColor
topBar.layer.shadowRadius = 50
topBar.layer.shadowOpacity = 50
//topBar.layer.shadowOffset = CGSize(width:100, height:100)
self.view.addSubview(topBar)
// self.navTitle = UINavigationItem(title: ("Find " + (self.gameController?.LocalGroupState.It_User_Name)!) + "!")
self.navTitle = UINavigationItem(title: (""))
let chat = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.compose, target: nil, action: #selector(loadChat))
let profile = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.organize, target: nil, action: #selector(loadProfile))
self.navTitle?.rightBarButtonItem = chat
self.navTitle?.leftBarButtonItem = profile
topBar.setItems([self.navTitle!], animated: false)
// if ((self.gameController?.LocalGroupState.It_User_Name) == getMyName()){
// self.titleLabel.text = "You're it!"
// self.disableCamera()
// }
// else{
// self.titleLabel.text = "Find " + (self.gameController?.LocalGroupState.It_User_Name)! + "!"
// self.enableCamera()
// }
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func addText(inImage image: UIImage) -> UIImage {
let textColor = UIColor.white
let textFont = UIFont(name: "Helvetica Bold", size: 100)!
let style = NSMutableParagraphStyle()
style.alignment = NSTextAlignment.center
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(image.size, false, scale)
var textFontAttributes = [
NSFontAttributeName: textFont,
NSForegroundColorAttributeName: textColor, NSParagraphStyleAttributeName:
style] as [String : Any]
image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
var rect = CGRect(origin: CGPoint(x:0, y:150), size: image.size)
var text = self.gameController?.LocalGroupState.It_User_Name.components(separatedBy: " ").first?.uppercased()
text?.draw(in: rect, withAttributes: textFontAttributes)
rect = CGRect(origin: CGPoint(x:0, y:image.size.height-250), size: image.size)
text = "SPOTTED"
textFontAttributes = [
NSFontAttributeName: textFont,
NSForegroundColorAttributeName: textColor, NSParagraphStyleAttributeName:
style] as [String : Any]
text?.draw(in: rect, withAttributes: textFontAttributes)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
// MARK: - Action methods
@IBAction func capture(sender: UIButton) {
let videoConnection = stillImageOutput?.connection(withMediaType: AVMediaTypeVideo)
videoConnection?.videoScaleAndCropFactor = (currentDevice?.videoZoomFactor)!
stillImageOutput?.captureStillImageAsynchronously(from: videoConnection, completionHandler: { (imageDataSampleBuffer, error) -> Void in
if let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer) {
let image = UIImage(data: imageData)
self.stillImage = self.addText(inImage: image!)
self.performSegue(withIdentifier: "showPhoto", sender: self)
}
})
}
func updateLabel(label: String) {
DispatchQueue.main.async {
// self.navTitle?.title = "Find " + label + "!"
if ((self.gameController?.LocalGroupState.It_User_Name) == getMyName()){
self.titleLabel.text = "You're it!"
self.disableCamera()
}
else{
self.titleLabel.text = "Find " + (self.gameController?.LocalGroupState.It_User_Name)! + "!"
self.enableCamera()
}
print("Set It User Label=\(label)")
}
}
func loadChat() {
NotificationCenter.default.post(name: Notification.Name(rawValue:"loadChat"), object: nil)
}
func loadProfile() {
NotificationCenter.default.post(name: Notification.Name(rawValue:"loadProfile"), object: nil)
}
// MARK: - Camera methods
func toggleCamera() {
captureSession.beginConfiguration()
// Change the device based on the current camera
let newDevice = (currentDevice?.position == AVCaptureDevicePosition.back) ? frontFacingCamera : backFacingCamera
// Remove all inputs from the session
for input in captureSession.inputs {
captureSession.removeInput(input as! AVCaptureDeviceInput)
}
// Change to the new input
let cameraInput:AVCaptureDeviceInput
do {
cameraInput = try AVCaptureDeviceInput(device: newDevice)
} catch {
print(error)
return
}
if captureSession.canAddInput(cameraInput) {
captureSession.addInput(cameraInput)
}
currentDevice = newDevice
captureSession.commitConfiguration()
}
func zoom(sender: UIPinchGestureRecognizer) {
if (sender.state == UIGestureRecognizerState.began) {
initialVideoZoomFactor = (currentDevice?.videoZoomFactor)!
} else {
let scale: CGFloat = min(max(1, initialVideoZoomFactor * sender.scale), 4)
CATransaction.begin()
CATransaction.setAnimationDuration(0.01)
cameraPreviewLayer?.setAffineTransform(CGAffineTransform(scaleX: scale, y: scale))
CATransaction.commit()
do {
try currentDevice?.lockForConfiguration()
currentDevice?.videoZoomFactor = scale
currentDevice?.unlockForConfiguration()
} catch {
NSLog("error!")
}
}
}
// MARK: - Segues
@IBAction func unwindToCameraView(segue: UIStoryboardSegue) {
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == "showPhoto" {
let photoViewController = segue.destination as! PhotoViewController
photoViewController.image = stillImage
photoViewController.itValue = self.gameController?.LocalGroupState.It_User_Name
photoViewController.mode = Mode.Sender
photoViewController.gameController = gameController
}
}
func StartVote() {
print("camera ui start vote")
}
func disableCamera(){
cameraButton.isEnabled = false
}
func enableCamera(){
cameraButton.isEnabled = true
}
}
| bsd-3-clause | 39b559e4e85d4dbe60baea9fcfb8f3bd | 37.116438 | 143 | 0.637197 | 5.601409 | false | false | false | false |
daaavid/TIY-Assignments | 41-Show-'n-Tell/ExtensionTest/ExtensionTest/Extensions.swift | 2 | 1935 | //
// Extensions.swift
// ExtensionTest
//
// Created by david on 12/1/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import Foundation
import UIKit
extension UIView
{
func appearWithFade(duration: Double)
{
self.alpha = 0
UIView.animateWithDuration(duration) { () -> Void in
self.alpha = 1
}
}
func hideWithFade(duration: Double)
{
self.alpha = 1
UIView.animateWithDuration(duration) { () -> Void in
self.alpha = 0
}
}
func slideHorizontally(duration: Double, fromPointX: CGFloat)
{
let originalX = self.frame.origin.x
self.frame.origin.x += fromPointX
UIView.animateWithDuration(duration) { () -> Void in
self.frame.origin.x = originalX
}
}
func slideVertically(duration: Double, fromPointY: CGFloat)
{
let originalY = self.frame.origin.y
self.frame.origin.y += fromPointY
UIView.animateWithDuration(duration) { () -> Void in
self.frame.origin.y = originalY
}
}
}
extension UIImageView
{
func downloadImgFrom(imageURL imageURL: String, contentMode: UIViewContentMode)
{
if let url = NSURL(string: imageURL)
{
let task = NSURLSession.sharedSession().dataTaskWithURL(url,
completionHandler: { (data, response, error) -> Void in
if data != nil
{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let image = UIImage(data: data!)
self.image = image
self.contentMode = contentMode
})
}
})
task.resume()
}
else
{
print("url \(imageURL) was invalid")
}
}
} | cc0-1.0 | ecc94ab20202b9891b76536c866f929a | 25.148649 | 83 | 0.520683 | 4.740196 | false | false | false | false |
zmeyc/GRDB.swift | Tests/GRDBTests/QueryInterfaceExpressionsTests.swift | 1 | 41664 | import XCTest
#if USING_SQLCIPHER
import GRDBCipher
#elseif USING_CUSTOMSQLITE
import GRDBCustomSQLite
#else
import GRDB
#endif
private struct Col {
static let id = Column("id")
static let name = Column("name")
static let age = Column("age")
static let readerId = Column("readerId")
}
private struct Reader : TableMapping {
static let databaseTableName = "readers"
}
private let tableRequest = Reader.all()
class QueryInterfaceExpressionsTests: GRDBTestCase {
var collation: DatabaseCollation!
var customFunction: DatabaseFunction!
override func setup(_ dbWriter: DatabaseWriter) throws {
collation = DatabaseCollation("localized_case_insensitive") { (lhs, rhs) in
return (lhs as NSString).localizedCaseInsensitiveCompare(rhs)
}
dbWriter.add(collation: collation)
customFunction = DatabaseFunction("avgOf", pure: true) { databaseValues in
let sum = databaseValues.flatMap { Int.fromDatabaseValue($0) }.reduce(0, +)
return Double(sum) / Double(databaseValues.count)
}
dbWriter.add(function: self.customFunction)
var migrator = DatabaseMigrator()
migrator.registerMigration("createReaders") { db in
try db.execute(
"CREATE TABLE readers (" +
"id INTEGER PRIMARY KEY, " +
"name TEXT NOT NULL, " +
"age INT" +
")")
}
try migrator.migrate(dbWriter)
}
// MARK: - Boolean expressions
func testContains() throws {
let dbQueue = try makeDatabaseQueue()
// emptyArray.contains(): 0
XCTAssertEqual(
sql(dbQueue, tableRequest.filter([Int]().contains(Col.id))),
"SELECT * FROM \"readers\" WHERE 0")
// !emptyArray.contains(): 0
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(![Int]().contains(Col.id))),
"SELECT * FROM \"readers\" WHERE 1")
// Array.contains(): IN operator
XCTAssertEqual(
sql(dbQueue, tableRequest.filter([1,2,3].contains(Col.id))),
"SELECT * FROM \"readers\" WHERE (\"id\" IN (1, 2, 3))")
// Array.contains(): IN operator
XCTAssertEqual(
sql(dbQueue, tableRequest.filter([Col.id].contains(Col.id))),
"SELECT * FROM \"readers\" WHERE (\"id\" IN (\"id\"))")
// EmptyCollection.contains(): 0
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(EmptyCollection<Int>().contains(Col.id))),
"SELECT * FROM \"readers\" WHERE 0")
// !EmptyCollection.contains(): 1
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(!EmptyCollection<Int>().contains(Col.id))),
"SELECT * FROM \"readers\" WHERE 1")
// Sequence.contains(): IN operator
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(AnySequence([1,2,3]).contains(Col.id))),
"SELECT * FROM \"readers\" WHERE (\"id\" IN (1, 2, 3))")
// Sequence.contains(): IN operator
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(AnySequence([Col.id]).contains(Col.id))),
"SELECT * FROM \"readers\" WHERE (\"id\" IN (\"id\"))")
// !Sequence.contains(): NOT IN operator
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(![1,2,3].contains(Col.id))),
"SELECT * FROM \"readers\" WHERE (\"id\" NOT IN (1, 2, 3))")
// !!Sequence.contains(): IN operator
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(!(![1,2,3].contains(Col.id)))),
"SELECT * FROM \"readers\" WHERE (\"id\" IN (1, 2, 3))")
// CountableRange.contains(): min <= x < max
XCTAssertEqual(
sql(dbQueue, tableRequest.filter((1..<10).contains(Col.id))),
"SELECT * FROM \"readers\" WHERE ((\"id\" >= 1) AND (\"id\" < 10))")
// CountableClosedRange.contains(): BETWEEN operator
XCTAssertEqual(
sql(dbQueue, tableRequest.filter((1...10).contains(Col.id))),
"SELECT * FROM \"readers\" WHERE (\"id\" BETWEEN 1 AND 10)")
// !CountableClosedRange.contains(): BETWEEN operator
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(!(1...10).contains(Col.id))),
"SELECT * FROM \"readers\" WHERE (\"id\" NOT BETWEEN 1 AND 10)")
// Range.contains(): min <= x < max
XCTAssertEqual(
sql(dbQueue, tableRequest.filter((1.1..<10.9).contains(Col.id))),
"SELECT * FROM \"readers\" WHERE ((\"id\" >= 1.1) AND (\"id\" < 10.9))")
// Range.contains(): min <= x < max
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(("A"..<"z").contains(Col.name))),
"SELECT * FROM \"readers\" WHERE ((\"name\" >= 'A') AND (\"name\" < 'z'))")
// ClosedRange.contains(): BETWEEN operator
XCTAssertEqual(
sql(dbQueue, tableRequest.filter((1.1...10.9).contains(Col.id))),
"SELECT * FROM \"readers\" WHERE (\"id\" BETWEEN 1.1 AND 10.9)")
// ClosedRange.contains(): BETWEEN operator
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(("A"..."z").contains(Col.name))),
"SELECT * FROM \"readers\" WHERE (\"name\" BETWEEN 'A' AND 'z')")
// !ClosedRange.contains(): NOT BETWEEN operator
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(!("A"..."z").contains(Col.name))),
"SELECT * FROM \"readers\" WHERE (\"name\" NOT BETWEEN 'A' AND 'z')")
// Subquery
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(tableRequest.select(Col.id).contains(Col.id))),
"SELECT * FROM \"readers\" WHERE (\"id\" IN (SELECT \"id\" FROM \"readers\"))")
// Subquery
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(!tableRequest.select(Col.id).contains(Col.id))),
"SELECT * FROM \"readers\" WHERE (\"id\" NOT IN (SELECT \"id\" FROM \"readers\"))")
}
func testContainsWithCollation() throws {
let dbQueue = try makeDatabaseQueue()
// Array.contains(): IN operator
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(["arthur", "barbara"].contains(Col.name.collating(.nocase)))),
"SELECT * FROM \"readers\" WHERE (\"name\" IN ('arthur', 'barbara') COLLATE NOCASE)")
// Sequence.contains(): IN operator
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(AnySequence(["arthur", "barbara"]).contains(Col.name.collating(.nocase)))),
"SELECT * FROM \"readers\" WHERE (\"name\" IN ('arthur', 'barbara') COLLATE NOCASE)")
// Sequence.contains(): IN operator
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(AnySequence([Col.name]).contains(Col.name.collating(.nocase)))),
"SELECT * FROM \"readers\" WHERE (\"name\" IN (\"name\") COLLATE NOCASE)")
// ClosedInterval: BETWEEN operator
let closedInterval = "A"..."z"
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(closedInterval.contains(Col.name.collating(.nocase)))),
"SELECT * FROM \"readers\" WHERE (\"name\" BETWEEN 'A' AND 'z' COLLATE NOCASE)")
// HalfOpenInterval: min <= x < max
let halfOpenInterval = "A"..<"z"
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(halfOpenInterval.contains(Col.name.collating(.nocase)))),
"SELECT * FROM \"readers\" WHERE ((\"name\" >= 'A' COLLATE NOCASE) AND (\"name\" < 'z' COLLATE NOCASE))")
}
func testGreaterThan() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age > 10)),
"SELECT * FROM \"readers\" WHERE (\"age\" > 10)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(10 > Col.age)),
"SELECT * FROM \"readers\" WHERE (10 > \"age\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(10 > 10)),
"SELECT * FROM \"readers\" WHERE 0")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age > Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" > \"age\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name > "B")),
"SELECT * FROM \"readers\" WHERE (\"name\" > 'B')")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter("B" > Col.name)),
"SELECT * FROM \"readers\" WHERE ('B' > \"name\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter("B" > "B")),
"SELECT * FROM \"readers\" WHERE 0")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name > Col.name)),
"SELECT * FROM \"readers\" WHERE (\"name\" > \"name\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.group(Col.name).having(average(Col.age) + 10 > 20)),
"SELECT * FROM \"readers\" GROUP BY \"name\" HAVING ((AVG(\"age\") + 10) > 20)")
}
func testGreaterThanWithCollation() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) > "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" > 'fOo' COLLATE NOCASE)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name.collating(collation) > "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" > 'fOo' COLLATE localized_case_insensitive)")
}
func testGreaterThanOrEqual() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age >= 10)),
"SELECT * FROM \"readers\" WHERE (\"age\" >= 10)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(10 >= Col.age)),
"SELECT * FROM \"readers\" WHERE (10 >= \"age\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(10 >= 10)),
"SELECT * FROM \"readers\" WHERE 1")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age >= Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" >= \"age\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name >= "B")),
"SELECT * FROM \"readers\" WHERE (\"name\" >= 'B')")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter("B" >= Col.name)),
"SELECT * FROM \"readers\" WHERE ('B' >= \"name\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter("B" >= "B")),
"SELECT * FROM \"readers\" WHERE 1")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name >= Col.name)),
"SELECT * FROM \"readers\" WHERE (\"name\" >= \"name\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.group(Col.name).having(average(Col.age) + 10 >= 20)),
"SELECT * FROM \"readers\" GROUP BY \"name\" HAVING ((AVG(\"age\") + 10) >= 20)")
}
func testGreaterThanOrEqualWithCollation() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) >= "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" >= 'fOo' COLLATE NOCASE)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name.collating(collation) >= "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" >= 'fOo' COLLATE localized_case_insensitive)")
}
func testLessThan() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age < 10)),
"SELECT * FROM \"readers\" WHERE (\"age\" < 10)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(10 < Col.age)),
"SELECT * FROM \"readers\" WHERE (10 < \"age\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(10 < 10)),
"SELECT * FROM \"readers\" WHERE 0")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age < Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" < \"age\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name < "B")),
"SELECT * FROM \"readers\" WHERE (\"name\" < 'B')")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter("B" < Col.name)),
"SELECT * FROM \"readers\" WHERE ('B' < \"name\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter("B" < "B")),
"SELECT * FROM \"readers\" WHERE 0")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name < Col.name)),
"SELECT * FROM \"readers\" WHERE (\"name\" < \"name\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.group(Col.name).having(average(Col.age) + 10 < 20)),
"SELECT * FROM \"readers\" GROUP BY \"name\" HAVING ((AVG(\"age\") + 10) < 20)")
}
func testLessThanWithCollation() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) < "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" < 'fOo' COLLATE NOCASE)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name.collating(collation) < "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" < 'fOo' COLLATE localized_case_insensitive)")
}
func testLessThanOrEqual() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age <= 10)),
"SELECT * FROM \"readers\" WHERE (\"age\" <= 10)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(10 <= Col.age)),
"SELECT * FROM \"readers\" WHERE (10 <= \"age\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(10 <= 10)),
"SELECT * FROM \"readers\" WHERE 1")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age <= Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" <= \"age\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name <= "B")),
"SELECT * FROM \"readers\" WHERE (\"name\" <= 'B')")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter("B" <= Col.name)),
"SELECT * FROM \"readers\" WHERE ('B' <= \"name\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter("B" <= "B")),
"SELECT * FROM \"readers\" WHERE 1")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name <= Col.name)),
"SELECT * FROM \"readers\" WHERE (\"name\" <= \"name\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.group(Col.name).having(average(Col.age) + 10 <= 20)),
"SELECT * FROM \"readers\" GROUP BY \"name\" HAVING ((AVG(\"age\") + 10) <= 20)")
}
func testLessThanOrEqualWithCollation() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) <= "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" <= 'fOo' COLLATE NOCASE)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name.collating(collation) <= "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" <= 'fOo' COLLATE localized_case_insensitive)")
}
func testEqual() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age == 10)),
"SELECT * FROM \"readers\" WHERE (\"age\" = 10)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age == (10 as Int?))),
"SELECT * FROM \"readers\" WHERE (\"age\" = 10)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(10 == Col.age)),
"SELECT * FROM \"readers\" WHERE (10 = \"age\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter((10 as Int?) == Col.age)),
"SELECT * FROM \"readers\" WHERE (10 = \"age\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(10 == 10)),
"SELECT * FROM \"readers\" WHERE 1")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age == Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" = \"age\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age == nil)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NULL)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(nil == Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NULL)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age == Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" = \"age\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name == "B")),
"SELECT * FROM \"readers\" WHERE (\"name\" = 'B')")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter("B" == Col.name)),
"SELECT * FROM \"readers\" WHERE ('B' = \"name\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter("B" == "B")),
"SELECT * FROM \"readers\" WHERE 1")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name == Col.name)),
"SELECT * FROM \"readers\" WHERE (\"name\" = \"name\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age == true)),
"SELECT * FROM \"readers\" WHERE \"age\"")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(true == Col.age)),
"SELECT * FROM \"readers\" WHERE \"age\"")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age == false)),
"SELECT * FROM \"readers\" WHERE NOT \"age\"")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(false == Col.age)),
"SELECT * FROM \"readers\" WHERE NOT \"age\"")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(true == true)),
"SELECT * FROM \"readers\" WHERE 1")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(false == false)),
"SELECT * FROM \"readers\" WHERE 1")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(true == false)),
"SELECT * FROM \"readers\" WHERE 0")
}
func testEqualWithCollation() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) == "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" = 'fOo' COLLATE NOCASE)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) == ("fOo" as String?))),
"SELECT * FROM \"readers\" WHERE (\"name\" = 'fOo' COLLATE NOCASE)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) == nil)),
"SELECT * FROM \"readers\" WHERE (\"name\" IS NULL COLLATE NOCASE)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name.collating(collation) == "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" = 'fOo' COLLATE localized_case_insensitive)")
}
func testNotEqual() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age != 10)),
"SELECT * FROM \"readers\" WHERE (\"age\" <> 10)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age != (10 as Int?))),
"SELECT * FROM \"readers\" WHERE (\"age\" <> 10)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(10 != Col.age)),
"SELECT * FROM \"readers\" WHERE (10 <> \"age\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter((10 as Int?) != Col.age)),
"SELECT * FROM \"readers\" WHERE (10 <> \"age\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(10 != 10)),
"SELECT * FROM \"readers\" WHERE 0")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age != Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" <> \"age\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age != nil)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT NULL)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(nil != Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT NULL)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age != Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" <> \"age\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name != "B")),
"SELECT * FROM \"readers\" WHERE (\"name\" <> 'B')")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter("B" != Col.name)),
"SELECT * FROM \"readers\" WHERE ('B' <> \"name\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter("B" != "B")),
"SELECT * FROM \"readers\" WHERE 0")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name != Col.name)),
"SELECT * FROM \"readers\" WHERE (\"name\" <> \"name\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age != true)),
"SELECT * FROM \"readers\" WHERE NOT \"age\"")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(true != Col.age)),
"SELECT * FROM \"readers\" WHERE NOT \"age\"")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age != false)),
"SELECT * FROM \"readers\" WHERE \"age\"")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(false != Col.age)),
"SELECT * FROM \"readers\" WHERE \"age\"")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(true != true)),
"SELECT * FROM \"readers\" WHERE 0")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(false != false)),
"SELECT * FROM \"readers\" WHERE 0")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(true != false)),
"SELECT * FROM \"readers\" WHERE 1")
}
func testNotEqualWithCollation() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) != "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" <> 'fOo' COLLATE NOCASE)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) != ("fOo" as String?))),
"SELECT * FROM \"readers\" WHERE (\"name\" <> 'fOo' COLLATE NOCASE)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) != nil)),
"SELECT * FROM \"readers\" WHERE (\"name\" IS NOT NULL COLLATE NOCASE)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name.collating(collation) != "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" <> 'fOo' COLLATE localized_case_insensitive)")
}
func testNotEqualWithSwiftNotOperator() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(!(Col.age == 10))),
"SELECT * FROM \"readers\" WHERE (\"age\" <> 10)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(!(10 == Col.age))),
"SELECT * FROM \"readers\" WHERE (10 <> \"age\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(!(10 == 10))),
"SELECT * FROM \"readers\" WHERE 0")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(!(Col.age == Col.age))),
"SELECT * FROM \"readers\" WHERE (\"age\" <> \"age\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(!(Col.age == nil))),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT NULL)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(!(nil == Col.age))),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT NULL)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(!(Col.age == Col.age))),
"SELECT * FROM \"readers\" WHERE (\"age\" <> \"age\")")
}
func testIs() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age === 10)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS 10)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(10 === Col.age)),
"SELECT * FROM \"readers\" WHERE (10 IS \"age\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age === Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS \"age\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age === nil)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NULL)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(nil === Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NULL)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age === Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS \"age\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name === "B")),
"SELECT * FROM \"readers\" WHERE (\"name\" IS 'B')")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter("B" === Col.name)),
"SELECT * FROM \"readers\" WHERE ('B' IS \"name\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name === Col.name)),
"SELECT * FROM \"readers\" WHERE (\"name\" IS \"name\")")
}
func testIsWithCollation() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) === "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" IS 'fOo' COLLATE NOCASE)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name.collating(collation) === "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" IS 'fOo' COLLATE localized_case_insensitive)")
}
func testIsNot() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age !== 10)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT 10)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(10 !== Col.age)),
"SELECT * FROM \"readers\" WHERE (10 IS NOT \"age\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age !== Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT \"age\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age !== nil)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT NULL)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(nil !== Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT NULL)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age !== Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT \"age\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name !== "B")),
"SELECT * FROM \"readers\" WHERE (\"name\" IS NOT 'B')")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter("B" !== Col.name)),
"SELECT * FROM \"readers\" WHERE ('B' IS NOT \"name\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name !== Col.name)),
"SELECT * FROM \"readers\" WHERE (\"name\" IS NOT \"name\")")
}
func testIsNotWithCollation() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) !== "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" IS NOT 'fOo' COLLATE NOCASE)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name.collating(collation) !== "fOo")),
"SELECT * FROM \"readers\" WHERE (\"name\" IS NOT 'fOo' COLLATE localized_case_insensitive)")
}
func testIsNotWithSwiftNotOperator() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(!(Col.age === 10))),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT 10)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(!(10 === Col.age))),
"SELECT * FROM \"readers\" WHERE (10 IS NOT \"age\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(!(Col.age === Col.age))),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT \"age\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(!(Col.age === nil))),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT NULL)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(!(nil === Col.age))),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT NULL)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(!(Col.age === Col.age))),
"SELECT * FROM \"readers\" WHERE (\"age\" IS NOT \"age\")")
}
func testExists() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(tableRequest.exists())),
"SELECT * FROM \"readers\" WHERE (EXISTS (SELECT * FROM \"readers\"))")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(!tableRequest.exists())),
"SELECT * FROM \"readers\" WHERE (NOT EXISTS (SELECT * FROM \"readers\"))")
}
func testLogicalOperators() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(!Col.age)),
"SELECT * FROM \"readers\" WHERE NOT \"age\"")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age && true)),
"SELECT * FROM \"readers\" WHERE (\"age\" AND 1)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(true && Col.age)),
"SELECT * FROM \"readers\" WHERE (1 AND \"age\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age || false)),
"SELECT * FROM \"readers\" WHERE (\"age\" OR 0)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(false || Col.age)),
"SELECT * FROM \"readers\" WHERE (0 OR \"age\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age != nil || Col.name != nil)),
"SELECT * FROM \"readers\" WHERE ((\"age\" IS NOT NULL) OR (\"name\" IS NOT NULL))")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age != nil || Col.name != nil && Col.id != nil)),
"SELECT * FROM \"readers\" WHERE ((\"age\" IS NOT NULL) OR ((\"name\" IS NOT NULL) AND (\"id\" IS NOT NULL)))")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter((Col.age != nil || Col.name != nil) && Col.id != nil)),
"SELECT * FROM \"readers\" WHERE (((\"age\" IS NOT NULL) OR (\"name\" IS NOT NULL)) AND (\"id\" IS NOT NULL))")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(!(Col.age > 18) && !(Col.name > "foo"))),
"SELECT * FROM \"readers\" WHERE (NOT (\"age\" > 18) AND NOT (\"name\" > 'foo'))")
}
// MARK: - String functions
func testStringFunctions() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.select(Col.name.capitalized)),
"SELECT swiftCapitalizedString(\"name\") FROM \"readers\"")
XCTAssertEqual(
sql(dbQueue, tableRequest.select(Col.name.lowercased)),
"SELECT swiftLowercaseString(\"name\") FROM \"readers\"")
XCTAssertEqual(
sql(dbQueue, tableRequest.select(Col.name.uppercased)),
"SELECT swiftUppercaseString(\"name\") FROM \"readers\"")
if #available(iOS 9.0, OSX 10.11, *) {
XCTAssertEqual(
sql(dbQueue, tableRequest.select(Col.name.localizedCapitalized)),
"SELECT swiftLocalizedCapitalizedString(\"name\") FROM \"readers\"")
XCTAssertEqual(
sql(dbQueue, tableRequest.select(Col.name.localizedLowercased)),
"SELECT swiftLocalizedLowercaseString(\"name\") FROM \"readers\"")
XCTAssertEqual(
sql(dbQueue, tableRequest.select(Col.name.localizedUppercased)),
"SELECT swiftLocalizedUppercaseString(\"name\") FROM \"readers\"")
}
}
// MARK: - Arithmetic expressions
func testPrefixMinusOperator() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(-Col.age)),
"SELECT * FROM \"readers\" WHERE -\"age\"")
}
func testInfixMinusOperator() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age - 2)),
"SELECT * FROM \"readers\" WHERE (\"age\" - 2)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(2 - Col.age)),
"SELECT * FROM \"readers\" WHERE (2 - \"age\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(2 - 2)),
"SELECT * FROM \"readers\" WHERE 0")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age - Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" - \"age\")")
}
func testInfixPlusOperator() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age + 2)),
"SELECT * FROM \"readers\" WHERE (\"age\" + 2)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(2 + Col.age)),
"SELECT * FROM \"readers\" WHERE (2 + \"age\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(2 + 2)),
"SELECT * FROM \"readers\" WHERE 4")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age + Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" + \"age\")")
}
func testInfixMultiplyOperator() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age * 2)),
"SELECT * FROM \"readers\" WHERE (\"age\" * 2)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(2 * Col.age)),
"SELECT * FROM \"readers\" WHERE (2 * \"age\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(2 * 2)),
"SELECT * FROM \"readers\" WHERE 4")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age * Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" * \"age\")")
}
func testInfixDivideOperator() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age / 2)),
"SELECT * FROM \"readers\" WHERE (\"age\" / 2)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(2 / Col.age)),
"SELECT * FROM \"readers\" WHERE (2 / \"age\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(2 / 2)),
"SELECT * FROM \"readers\" WHERE 1")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age / Col.age)),
"SELECT * FROM \"readers\" WHERE (\"age\" / \"age\")")
}
func testCompoundArithmeticExpression() throws {
let dbQueue = try makeDatabaseQueue()
// Int / Double
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age / 2.0)),
"SELECT * FROM \"readers\" WHERE (\"age\" / 2.0)")
// Double / Int
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(2.0 / Col.age)),
"SELECT * FROM \"readers\" WHERE (2.0 / \"age\")")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age + 2 * 5)),
"SELECT * FROM \"readers\" WHERE (\"age\" + 10)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age * 2 + 5)),
"SELECT * FROM \"readers\" WHERE ((\"age\" * 2) + 5)")
}
// MARK: - IFNULL expression
func testIfNull() throws {
let dbQueue = try makeDatabaseQueue()
var optInt: Int? = nil
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age ?? 2)),
"SELECT * FROM \"readers\" WHERE IFNULL(\"age\", 2)")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(optInt ?? Col.age)),
"SELECT * FROM \"readers\" WHERE \"age\"")
optInt = 1
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(optInt ?? Col.age)),
"SELECT * FROM \"readers\" WHERE 1")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age ?? Col.age)),
"SELECT * FROM \"readers\" WHERE IFNULL(\"age\", \"age\")")
}
// MARK: - Aggregated expressions
func testCountExpression() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.select(count(Col.age))),
"SELECT COUNT(\"age\") FROM \"readers\"")
XCTAssertEqual(
sql(dbQueue, tableRequest.select(count(Col.age ?? 0))),
"SELECT COUNT(IFNULL(\"age\", 0)) FROM \"readers\"")
XCTAssertEqual(
sql(dbQueue, tableRequest.select(count(distinct: Col.age))),
"SELECT COUNT(DISTINCT \"age\") FROM \"readers\"")
XCTAssertEqual(
sql(dbQueue, tableRequest.select(count(distinct: Col.age / Col.age))),
"SELECT COUNT(DISTINCT (\"age\" / \"age\")) FROM \"readers\"")
}
func testAvgExpression() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.select(average(Col.age))),
"SELECT AVG(\"age\") FROM \"readers\"")
XCTAssertEqual(
sql(dbQueue, tableRequest.select(average(Col.age / 2))),
"SELECT AVG((\"age\" / 2)) FROM \"readers\"")
}
func testLengthExpression() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.select(length(Col.name))),
"SELECT LENGTH(\"name\") FROM \"readers\"")
}
func testMinExpression() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.select(min(Col.age))),
"SELECT MIN(\"age\") FROM \"readers\"")
XCTAssertEqual(
sql(dbQueue, tableRequest.select(min(Col.age / 2))),
"SELECT MIN((\"age\" / 2)) FROM \"readers\"")
}
func testMaxExpression() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.select(max(Col.age))),
"SELECT MAX(\"age\") FROM \"readers\"")
XCTAssertEqual(
sql(dbQueue, tableRequest.select(max(Col.age / 2))),
"SELECT MAX((\"age\" / 2)) FROM \"readers\"")
}
func testSumExpression() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.select(sum(Col.age))),
"SELECT SUM(\"age\") FROM \"readers\"")
XCTAssertEqual(
sql(dbQueue, tableRequest.select(sum(Col.age / 2))),
"SELECT SUM((\"age\" / 2)) FROM \"readers\"")
}
// MARK: - LIKE operator
func testLikeOperator() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.name.like("%foo"))),
"SELECT * FROM \"readers\" WHERE (\"name\" LIKE '%foo')")
}
// MARK: - Function
func testCustomFunction() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.select(customFunction.apply(Col.age, 1, 2))),
"SELECT avgOf(\"age\", 1, 2) FROM \"readers\"")
}
}
| mit | e96e126f6bfb274d9eba9fd51f70de3f | 42.17513 | 123 | 0.543035 | 4.65 | false | false | false | false |
ReactiveKit/ReactiveAPI | Sources/Activity.swift | 1 | 1289 | //
// Activity.swift
// ReactiveAPI
//
// Created by Srdan Rasic on 15/01/2017.
// Copyright © 2017 Reactive Kit. All rights reserved.
//
import ReactiveKit
import UIKit
public class Activity {
fileprivate let _isActive = Property(false)
private var count = 0 {
didSet {
if oldValue == 1, count == 0 {
_isActive.value = false
} else if oldValue == 0, count == 1 {
_isActive.value = true
}
}
}
public var isActive: Bool {
return _isActive.value
}
public init(updateNetworkActivityIndicator: Bool = true) {
if updateNetworkActivityIndicator {
_ = _isActive.observeNext { isActive in
UIApplication.shared.isNetworkActivityIndicatorVisible = isActive
}
}
}
public func increase() {
count += 1
}
public func decrease() {
count -= 1
}
}
extension Activity: SubjectProtocol {
public func on(_ event: Event<Bool, NoError>) {
switch event {
case .next(let active):
if active {
increase()
} else {
decrease()
}
default:
break
}
}
public func observe(with observer: @escaping (Event<Bool, NoError>) -> Void) -> Disposable {
return _isActive.observeIn(ImmediateOnMainExecutionContext).observe(with: observer)
}
}
| mit | 1710b28e0eca5986825c48285b058f07 | 18.815385 | 94 | 0.621894 | 4.222951 | false | false | false | false |
nlampi/SwiftGridView | Examples/Universal/SwiftGridExample/ViewController.swift | 1 | 19355 | // ViewController.swift
// Copyright (c) 2016 Nathan Lampi (http://nathanlampi.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 SwiftGridView
class ViewController: UIViewController, SwiftGridViewDataSource, SwiftGridViewDelegate {
@IBOutlet weak var dataGridContainerView: UIView!
@IBOutlet weak var dataGridView: SwiftGridView! /// Data Grid IBOutlet
var sectionCount: Int = 5
var frozenColumns: Int = 1
var reloadOverride: Bool = false
var columnCount: Int = 10
var rowCountIncrease: Int = 15
let columnGroupings: [[Int]] = [[2,4], [6,9]] /// Columns are grouped by start and end column index.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.dataGridView.allowsSelection = true
self.dataGridView.allowsMultipleSelection = true
self.dataGridView.rowSelectionEnabled = true
self.dataGridView.isDirectionalLockEnabled = false
self.dataGridView.bounces = true
self.dataGridView.stickySectionHeaders = true
self.dataGridView.showsHorizontalScrollIndicator = true
self.dataGridView.showsVerticalScrollIndicator = true
self.dataGridView.alwaysBounceHorizontal = false
self.dataGridView.alwaysBounceVertical = false
self.dataGridView.pinchExpandEnabled = true
// Register Basic Cell types
self.dataGridView.register(BasicTextCell.self, forCellWithReuseIdentifier:BasicTextCell.reuseIdentifier())
self.dataGridView.register(UINib(nibName: "BasicNibCell", bundle:nil), forCellWithReuseIdentifier: BasicNibCell.reuseIdentifier())
// Register Basic View for Header supplementary views
self.dataGridView.register(BasicTextReusableView.self, forSupplementaryViewOfKind: SwiftGridElementKindHeader, withReuseIdentifier: BasicTextReusableView.reuseIdentifier())
self.dataGridView.register(BasicTextReusableView.self, forSupplementaryViewOfKind: SwiftGridElementKindGroupedHeader, withReuseIdentifier: BasicTextReusableView.reuseIdentifier())
// Register Section header Views
self.dataGridView.register(BasicTextReusableView.self, forSupplementaryViewOfKind: SwiftGridElementKindSectionHeader, withReuseIdentifier: BasicTextReusableView.reuseIdentifier())
self.dataGridView.register(UINib(nibName: "BasicNibReusableView", bundle:nil), forSupplementaryViewOfKind: SwiftGridElementKindSectionHeader, withReuseIdentifier: BasicNibReusableView.reuseIdentifier())
// Register Footer views
self.dataGridView.register(BasicTextReusableView.self, forSupplementaryViewOfKind: SwiftGridElementKindSectionFooter, withReuseIdentifier: BasicTextReusableView.reuseIdentifier())
self.dataGridView.register(BasicTextReusableView.self, forSupplementaryViewOfKind: SwiftGridElementKindFooter, withReuseIdentifier: BasicTextReusableView.reuseIdentifier())
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Gesture Recognizers
@IBAction func didTapChangeData(_ sender: AnyObject) {
reloadOverride = false
sectionCount = Int(arc4random_uniform(5)) + 3
frozenColumns = Int(arc4random_uniform(4))
columnCount = Int(arc4random_uniform(30)) + 1
rowCountIncrease = Int(arc4random_uniform(50))
self.dataGridView.reloadData()
}
@IBAction func didTapScrollButton(_ sender: AnyObject) {
let indexPath = IndexPath(forSGRow: 0, atColumn: 0, inSection: 3)
self.dataGridView.scrollToCellAtIndexPath(indexPath, atScrollPosition: [.top, .left], animated: true)
}
@IBAction func didTapReloadCells(_ sender: AnyObject) {
self.reloadOverride = true
// Reload Cells
let indexPaths = [
IndexPath(forSGRow: 0, atColumn: 0, inSection: 0),
IndexPath(forSGRow: 0, atColumn: 2, inSection: 0),
IndexPath(forSGRow: 1, atColumn: 1, inSection: 0),
IndexPath(forSGRow: 1, atColumn: 3, inSection: 0)
]
self.dataGridView.reloadCellsAtIndexPaths(indexPaths, animated: true, completion: { completed in
self.reloadOverride = false
})
// // Reload Headers
// indexPaths = [
// NSIndexPath(forsgRow: 0, atColumn: 1, inSection: 0),
// NSIndexPath(forsgRow: 0, atColumn: 3, inSection: 0)
// ]
// self.dataGridView.reloadSupplementaryViewsOfKind(SwiftGridElementKindHeader, atIndexPaths: indexPaths)
//
// // Reload Section Headers
// indexPaths = [
// NSIndexPath(forsgRow: 0, atColumn: 1, inSection: 0),
// NSIndexPath(forsgRow: 0, atColumn: 3, inSection: 0)
// ]
// self.dataGridView.reloadSupplementaryViewsOfKind(SwiftGridElementKindSectionHeader, atIndexPaths: indexPaths)
//
// // Reload Section Footers
// indexPaths = [
// NSIndexPath(forsgRow: 0, atColumn: 0, inSection: 0),
// NSIndexPath(forsgRow: 0, atColumn: 2, inSection: 0)
// ]
// self.dataGridView.reloadSupplementaryViewsOfKind(SwiftGridElementKindSectionFooter, atIndexPaths: indexPaths)
//
//
// // Reload Footers
// indexPaths = [
// NSIndexPath(forsgRow: 0, atColumn: 1, inSection: 0),
// NSIndexPath(forsgRow: 0, atColumn: 3, inSection: 0)
// ]
// self.dataGridView.reloadSupplementaryViewsOfKind(SwiftGridElementKindFooter, atIndexPaths: indexPaths)
}
// MARK: - SwiftGridViewDataSource
func numberOfSectionsInDataGridView(_ dataGridView: SwiftGridView) -> Int {
return sectionCount
}
func numberOfColumnsInDataGridView(_ dataGridView: SwiftGridView) -> Int {
return columnCount
}
func dataGridView(_ dataGridView: SwiftGridView, numberOfRowsInSection section: Int) -> Int {
return section + rowCountIncrease
}
func dataGridView(_ dataGridView: SwiftGridView, numberOfFrozenRowsInSection section: Int) -> Int {
if section < 1 {
return 2
}
return 0
}
// Cells
func dataGridView(_ dataGridView: SwiftGridView, cellAtIndexPath indexPath: IndexPath) -> SwiftGridCell {
let cell: SwiftGridCell
if(indexPath.sgColumn > 0) {
let textCell: BasicTextCell = dataGridView.dequeueReusableCellWithReuseIdentifier(BasicTextCell.reuseIdentifier(), forIndexPath: indexPath) as! BasicTextCell
if(reloadOverride) {
textCell.backgroundView?.backgroundColor = UIColor.cyan
} else {
let r: CGFloat = (147 + CGFloat(indexPath.sgSection) * 10) / 255
let g: CGFloat = (173 + CGFloat(indexPath.sgRow) * 2) / 255
let b: CGFloat = (207 + CGFloat(indexPath.sgColumn) * 2) / 255
textCell.backgroundView?.backgroundColor = UIColor(red: r, green: g, blue: b, alpha: 1.0)
}
textCell.textLabel.text = "(\(indexPath.sgSection), \(indexPath.sgColumn), \(indexPath.sgRow))"
cell = textCell
} else {
let nibCell: BasicNibCell = dataGridView.dequeueReusableCellWithReuseIdentifier(BasicNibCell.reuseIdentifier(), forIndexPath: indexPath) as! BasicNibCell
if(reloadOverride) {
nibCell.backgroundView?.backgroundColor = UIColor.cyan
} else {
let r: CGFloat = (147 + CGFloat(indexPath.sgSection) * 10) / 255
let g: CGFloat = (173 + CGFloat(indexPath.sgRow) * 2) / 255
let b: CGFloat = (207 + CGFloat(indexPath.sgColumn) * 2) / 255
nibCell.backgroundView?.backgroundColor = UIColor(red: r, green: g, blue: b, alpha: 1.0)
}
nibCell.textLabel.text = "(\(indexPath.sgSection), \(indexPath.sgColumn), \(indexPath.sgRow))"
cell = nibCell
}
return cell
}
// Header / Footer Views
func dataGridView(_ dataGridView: SwiftGridView, gridHeaderViewForColumn column: NSInteger) -> SwiftGridReusableView {
let view = dataGridView.dequeueReusableSupplementaryViewOfKind(SwiftGridElementKindHeader, withReuseIdentifier: BasicTextReusableView.reuseIdentifier(), atColumn: column) as! BasicTextReusableView
if(reloadOverride) {
view.backgroundView?.backgroundColor = UIColor.cyan
} else {
let r: CGFloat = (159 + CGFloat(column) * 3) / 255
let g: CGFloat = (159 + CGFloat(column) * 3) / 255
let b: CGFloat = (160 + CGFloat(column) * 3) / 255
view.backgroundView?.backgroundColor = UIColor(red: r, green: g, blue: b, alpha: 1.0)
}
view.textLabel.text = "HCol: (\(column))"
return view
}
func dataGridView(_ dataGridView: SwiftGridView, groupedHeaderViewFor columnGrouping: [Int], at index: Int) -> SwiftGridReusableView {
let view = dataGridView.dequeueReusableSupplementaryViewOfKind(SwiftGridElementKindGroupedHeader, withReuseIdentifier: BasicTextReusableView.reuseIdentifier(), atColumn: index) as! BasicTextReusableView
if(reloadOverride) {
view.backgroundView?.backgroundColor = UIColor.cyan
} else {
let r: CGFloat = (159 + CGFloat(columnGrouping[0]) * 3) / 255
let g: CGFloat = (159 + CGFloat(columnGrouping[0]) * 3) / 255
let b: CGFloat = (160 + CGFloat(columnGrouping[0]) * 3) / 255
view.backgroundView?.backgroundColor = UIColor(red: r, green: g, blue: b, alpha: 1.0)
}
view.textLabel.textAlignment = .center
view.textLabel.text = "Grouping [\(columnGrouping[0]), \(columnGrouping[1])]"
return view;
}
func dataGridView(_ dataGridView: SwiftGridView, gridFooterViewForColumn column: NSInteger) -> SwiftGridReusableView {
let view = dataGridView.dequeueReusableSupplementaryViewOfKind(SwiftGridElementKindFooter, withReuseIdentifier: BasicTextReusableView.reuseIdentifier(), atColumn: column) as! BasicTextReusableView
if(reloadOverride) {
view.backgroundView?.backgroundColor = UIColor.cyan
} else {
let r: CGFloat = (104 + CGFloat(column) * 3) / 255
let g: CGFloat = (153 + CGFloat(column) * 3) / 255
let b: CGFloat = (71 + CGFloat(column) * 3) / 255
view.backgroundView?.backgroundColor = UIColor(red: r, green: g, blue: b, alpha: 1.0)
}
view.textLabel.text = "FCol: (\(column))"
return view
}
// Section Header / Footer Views
func dataGridView(_ dataGridView: SwiftGridView, sectionHeaderCellAtIndexPath indexPath: IndexPath) -> SwiftGridReusableView {
let view: SwiftGridReusableView
if(indexPath.sgColumn > 0) {
let textView: BasicTextReusableView = dataGridView.dequeueReusableSupplementaryViewOfKind(SwiftGridElementKindSectionHeader, withReuseIdentifier: BasicTextReusableView.reuseIdentifier(), forIndexPath: indexPath) as! BasicTextReusableView
if(reloadOverride) {
textView.backgroundView?.backgroundColor = UIColor.cyan
} else {
let r: CGFloat = (71 + CGFloat(indexPath.sgSection) * 3) / 255
let g: CGFloat = (101 + CGFloat(indexPath.sgRow) * 3) / 255
let b: CGFloat = (198 + CGFloat(indexPath.sgColumn) * 3) / 255
textView.backgroundView?.backgroundColor = UIColor(red: r, green: g, blue: b, alpha: 1.0)
}
textView.textLabel.text = "(\(indexPath.sgSection), \(indexPath.sgColumn), \(indexPath.sgRow))"
view = textView
} else {
let nibView: BasicNibReusableView = dataGridView.dequeueReusableSupplementaryViewOfKind(SwiftGridElementKindSectionHeader, withReuseIdentifier: BasicNibReusableView.reuseIdentifier(), forIndexPath: indexPath) as! BasicNibReusableView
if(reloadOverride) {
nibView.backgroundView?.backgroundColor = UIColor.cyan
} else {
let r: CGFloat = (71 + CGFloat(indexPath.sgSection) * 3) / 255
let g: CGFloat = (101 + CGFloat(indexPath.sgRow) * 3) / 255
let b: CGFloat = (198 + CGFloat(indexPath.sgColumn) * 3) / 255
nibView.backgroundView?.backgroundColor = UIColor(red: r, green: g, blue: b, alpha: 1.0)
}
nibView.textLabel.text = "(\(indexPath.sgSection), \(indexPath.sgColumn), \(indexPath.sgRow))"
view = nibView
}
return view
}
func dataGridView(_ dataGridView: SwiftGridView, sectionFooterCellAtIndexPath indexPath: IndexPath) -> SwiftGridReusableView {
let view = dataGridView.dequeueReusableSupplementaryViewOfKind(SwiftGridElementKindSectionFooter, withReuseIdentifier: BasicTextReusableView.reuseIdentifier(), forIndexPath: indexPath) as! BasicTextReusableView
if(reloadOverride) {
view.backgroundView?.backgroundColor = UIColor.cyan
} else {
let r: CGFloat = (196 + CGFloat(indexPath.sgSection) * 3) / 255
let g: CGFloat = (102 + CGFloat(indexPath.sgRow) * 3) / 255
let b: CGFloat = (137 + CGFloat(indexPath.sgColumn) * 3) / 255
view.backgroundView?.backgroundColor = UIColor(red: r, green: g, blue: b, alpha: 1.0)
}
view.textLabel.text = "(\(indexPath.sgSection), \(indexPath.sgColumn), \(indexPath.sgRow))"
return view
}
// Grouped Headers
func columnGroupingsForDataGridView(_ dataGridView: SwiftGridView) -> [[Int]] {
return self.columnGroupings
}
// Frozen Columns
func numberOfFrozenColumnsInDataGridView(_ dataGridView: SwiftGridView) -> Int {
return frozenColumns
}
// MARK: - SwiftGridViewDelegate
func dataGridView(_ dataGridView: SwiftGridView, didSelectHeaderAtIndexPath indexPath: IndexPath) {
NSLog("Selected header indexPath: (\(indexPath.sgSection), \(indexPath.sgColumn), \(indexPath.sgRow))")
}
func dataGridView(_ dataGridView: SwiftGridView, didDeselectHeaderAtIndexPath indexPath: IndexPath) {
NSLog("Deselected header indexPath: (\(indexPath.sgSection), \(indexPath.sgColumn), \(indexPath.sgRow))")
}
func dataGridView(_ dataGridView: SwiftGridView, didSelectGroupedHeader columnGrouping: [Int], at index: Int) {
NSLog("Selected grouped header [\(columnGrouping[0]), \(columnGrouping[1])]")
}
func dataGridView(_ dataGridView: SwiftGridView, didDeselectGroupedHeader columnGrouping: [Int], at index: Int) {
NSLog("Deselected grouped header [\(columnGrouping[0]), \(columnGrouping[1])]")
}
func dataGridView(_ dataGridView: SwiftGridView, didSelectFooterAtIndexPath indexPath: IndexPath) {
NSLog("Selected footer indexPath: (\(indexPath.sgSection), \(indexPath.sgColumn), \(indexPath.sgRow))")
}
func dataGridView(_ dataGridView: SwiftGridView, didDeselectFooterAtIndexPath indexPath: IndexPath) {
NSLog("Deselected footer indexPath: (\(indexPath.sgSection), \(indexPath.sgColumn), \(indexPath.sgRow))")
}
func dataGridView(_ dataGridView: SwiftGridView, didSelectCellAtIndexPath indexPath: IndexPath) {
NSLog("Selected indexPath: (\(indexPath.sgSection), \(indexPath.sgColumn), \(indexPath.sgRow))")
}
func dataGridView(_ dataGridView: SwiftGridView, didDeselectCellAtIndexPath indexPath: IndexPath) {
NSLog("Deselected indexPath: (\(indexPath.sgSection), \(indexPath.sgColumn), \(indexPath.sgRow))")
}
func dataGridView(_ dataGridView: SwiftGridView, didSelectSectionHeaderAtIndexPath indexPath: IndexPath) {
NSLog("Selected section header indexPath: (\(indexPath.sgSection), \(indexPath.sgColumn), \(indexPath.sgRow))")
}
func dataGridView(_ dataGridView: SwiftGridView, didDeselectSectionHeaderAtIndexPath indexPath: IndexPath) {
NSLog("Deselected section header indexPath: (\(indexPath.sgSection), \(indexPath.sgColumn), \(indexPath.sgRow))")
}
func dataGridView(_ dataGridView: SwiftGridView, didSelectSectionFooterAtIndexPath indexPath: IndexPath) {
NSLog("Selected section footer indexPath: (\(indexPath.sgSection), \(indexPath.sgColumn), \(indexPath.sgRow))")
}
func dataGridView(_ dataGridView: SwiftGridView, didDeselectSectionFooterAtIndexPath indexPath: IndexPath) {
NSLog("Deselected section footer indexPath: (\(indexPath.sgSection), \(indexPath.sgColumn), \(indexPath.sgRow))")
}
func dataGridView(_ dataGridView: SwiftGridView, heightOfRowAtIndexPath indexPath: IndexPath) -> CGFloat {
return 55
}
func dataGridView(_ dataGridView: SwiftGridView, widthOfColumnAtIndex columnIndex: Int) -> CGFloat {
return 150 + 25 * CGFloat(columnIndex)
}
func heightForGridHeaderInDataGridView(_ dataGridView: SwiftGridView) -> CGFloat {
return 75.0
}
func heightForGridFooterInDataGridView(_ dataGridView: SwiftGridView) -> CGFloat {
return 55.0
}
func dataGridView(_ dataGridView: SwiftGridView, heightOfHeaderInSection section: Int) -> CGFloat {
return 75.0
}
func dataGridView(_ dataGridView: SwiftGridView, heightOfFooterInSection section: Int) -> CGFloat {
return 75.0
}
}
| mit | c46e23f2a58235af9d098d7edb2fa293 | 44.327869 | 249 | 0.653475 | 5.168224 | false | false | false | false |
NoodleOfDeath/PastaParser | runtime/swift/GrammarKit/Classes/extensions/Extensions.swift | 1 | 30466 | //
// The MIT License (MIT)
//
// Copyright © 2020 NoodleOfDeath. All rights reserved.
// NoodleOfDeath
//
// 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 CoreImage
// MARK: - Path Component Concatentation Infix Operator
infix operator +/ : AdditionPrecedence
// MARK: - Optional Assignment Operator
infix operator ?= : AssignmentPrecedence
// MARK: - Exponentiation Infix Operator
precedencegroup ExponentiationPrecedence {
associativity: right
higherThan: MultiplicationPrecedence
}
infix operator ** : ExponentiationPrecedence
// MARK: - Optional Wrapper Assignment Operator Methods
///
///
/// - Parameters:
/// - lhs:
/// - rhs:
func ?= <T>(lhs: inout T, rhs: T?) {
guard let rhs = rhs else { return }
lhs = rhs
}
///
///
/// - Parameters:
/// - lhs:
/// - rhs:
func ?= <T>(lhs: inout T?, rhs: T?) {
guard let rhs = rhs else { return }
lhs = rhs
}
// MARK: - Numeric-Boolean Math Operator Methods
///
///
/// - Parameters:
/// - lhs:
/// - rhs:
/// - Returns:
func + <NumericType: Numeric>(lhs: NumericType, rhs: Bool) -> NumericType {
return lhs + (rhs ? 1 : 0)
}
///
///
/// - Parameters:
/// - lhs:
/// - rhs:
/// - Returns:
func + <NumericType: Numeric>(lhs: Bool, rhs: NumericType) -> NumericType {
return (lhs ? 1 : 0) + rhs
}
// MARK: - CGFloat Extension
extension CGFloat {
/// Legacy alias for `leastNormalMagnitude`.
static var min: CGFloat { return leastNormalMagnitude }
/// Legacy alias for `greatestFiniteMagnitude`.
static var max: CGFloat { return greatestFiniteMagnitude }
}
// MARK: - Dictiopnary Extension
extension Dictionary {
static func + (lhs: Dictionary<Key, Value>, rhs: Dictionary<Key, Value>) -> Dictionary<Key, Value> {
var dict = lhs
rhs.forEach { dict[$0.key] = $0.value }
return dict
}
static func += (lhs: inout Dictionary<Key, Value>, rhs: Dictionary<Key, Value>) {
lhs = lhs + rhs
}
}
// MARK: - NSRange Extension
extension NSRange {
/// A range with location and length set to `0`.
static var zero: NSRange { return NSMakeRange(0, 0) }
/// Any range with a negative length is invalid.
static var invalid: NSRange { return NSMakeRange(NSNotFound, NSNotFound) }
/// Returns the sum of the `location` and `length` of this range.
/// Shorthand for `NSMaxRange(self)`.
var max: Int { return NSMaxRange(self) }
/// Range struct representatin of this range.
var bridgedRange: Range<Int> { return location ..< max }
/// Returns `true` if, and only if, `location != NSNotFound && length != NSNotFound`.
var isValid: Bool { return location < NSNotFound && length < NSNotFound }
}
// MARK: - NSRange Addition Extension
extension NSRange {
/// Shifts a range location and length by a specified integer tuple.
///
/// - Parameters:
/// - lhs: range to shift.
/// - rhs: tuple to shift the location and length of `lhs` by.
/// - Returns: a range with a location equal to
/// `lhs.location + rhs.location` and length equal to
/// `lhs.length + rhs.length`.
static func + (lhs: NSRange, rhs: (location: Int, length: Int)) -> NSRange {
return NSMakeRange(lhs.location + rhs.location, lhs.length + rhs.length)
}
}
// MARK: - NSRange Shifting Extension
extension NSRange {
/// Shifts the location of this range by a specified offset and adjusts
/// its length to have the same end index, unless `true` is passed for
/// `keepLength`.
///
/// - Parameters:
/// - offset: to shift the location of this range by.
/// - keepLength: specify `true` to indicate the length of this range
/// should remain unchanged; specfiy `false`, to indicate that the length
/// should be adjusted to maintain the same `max` value. Default value
/// is `false`.
mutating func shiftLocation(by offset: Int, keepLength: Bool = false) {
location += offset
length = keepLength ? length : Swift.max(length - offset, 0)
}
/// Returns a copy of this range with the location shifted by a specified
/// offset and the length adjusted to have the same end index as this range,
/// unless `true` is passed for `keepLength`.
///
/// - Parameters:
/// - offset: to shift the location of the range by relative to the
/// location of this range.
/// - keepLength: specify `true` to indicate the length of the returned
/// range should be equal to the range of this range; specify `false`, to
/// indicate that the length should be adjusted to maintain the same `max`
/// value of this range. Default value is `false`.
/// - Returns: a copy of this range with the location shifted by a specified
/// offset and the length adjusted to have the same end index as this range,
/// unless `true` is passed for `keepLength`.
func shiftingLocation(by offset: Int, keepLength: Bool = false) -> NSRange {
return NSMakeRange(location + offset, keepLength ? length : Swift.max(length - offset, 0))
}
/// Contracts this range at both ends by a specified width. The result
/// leaves this range with a postive, or zero, length that equal to
/// `oldLength - (width * 2)` and a location equal to `length + width`.
///
/// - Parameters:
/// - width: to contract this range by.
mutating func contract(by width: Int) {
location += width
length = Swift.max(length - (width * 2), 0)
}
/// Expands this range at both ends by a specified width. The result
/// leaves this range with a postive, or zero, length that equal to
/// `oldLength + (width * 2)` and a location equal to `length - width`.
///
/// - Parameters:
/// - width: to expand this range by.
mutating func expand(by width: Int) {
location -= width
length += (width * 2)
}
/// Returns a copy of this range that is contracted at both ends by a
/// specified width. The resultant range will have a postive, or zero,
/// length that equal to `oldLength - (width * 2)` and a location equal
/// to `length + width`.
///
/// - Parameters:
/// - width: to contract this range by.
/// - Returns: a copy of this range that has been contracted at both ends
/// by `width`.
func contracted(by width: Int) -> NSRange {
return NSMakeRange(location + width, Swift.max(length - (width * 2), 0))
}
/// Returns a copy of this range that is expanded at both ends by a
/// specified width. The resultant range will have a postive, or zero,
/// length that equal to `oldLength + (width * 2)` and a location equal
/// to `length - width`.
/// - Parameters:
/// - width: to contract this range by.
/// - Returns: a copy of this range that has been expanded at both ends
/// by `width`.
func expanded(by width: Int) -> NSRange {
return NSMakeRange(location - width, length + (width * 2))
}
}
#if os(iOS)
// MARK: - NSShadow Extension
extension NSShadow {
/// UI type casted color of this shadow.
var color: UIColor? {
get { return shadowColor as? UIColor }
set { shadowColor = newValue }
}
/// CG type casted color of this shadow.
var cgColor: CGColor? {
get { return color?.cgColor }
set {
guard let cgColor = newValue else { color = nil; return }
color = UIColor(cgColor: cgColor)
}
}
}
#endif
// MARK: - Range Property Extension
extension Range where Bound == Int {
/// Length of this range.
var length: Bound { return upperBound - lowerBound }
/// NSRange representation of this range.
var bridgedRange: NSRange { return NSMakeRange(lowerBound, length) }
}
///
public struct StringFormattingOption: BaseOptionSet {
public typealias This = StringFormattingOption
public typealias RawValue = Int
public static let escapeWhitespaces = This(1 << 0)
public static let escapeRegex = This(1 << 1)
public let rawValue: RawValue
public init(rawValue: RawValue) {
self.rawValue = rawValue
}
}
// MARK: - String Path Concatenation
extension String {
static func +/ (lhs: String, rhs: String) -> String {
return lhs.appendingPathComponent(rhs)
}
static func +/ (lhs: String?, rhs: String) -> String? {
guard let lhs = lhs else { return nil }
return lhs.appendingPathComponent(rhs)
}
static func +/ (lhs: String, rhs: String?) -> String? {
guard let rhs = rhs else { return nil }
return lhs.appendingPathComponent(rhs)
}
}
// MARK: - String Property Extension (NSString Bridging Properties)
extension String {
/// This string casted as a `NSString`.
/// Shorthand for `(self as NSString)`.
fileprivate var ns: NSString { return self as NSString }
/// Actual length of this string in terms of number of bytes.
/// Shorthand for `(self as NSString).length`.
var length: Int { return ns.length }
/// Zero based range of this string.
/// Shorthand for `NSMakeRange(0, length)`.
var range: NSRange { return NSMakeRange(0, length) }
func range(offsetBy offset: Int) -> NSRange { return NSMakeRange(offset, length - offset) }
/// First letter of this string; or an empty string if this string is empty.
var firstCharacter: String { return length > 0 ? substring(to: 1) : "" }
/// Last letter of this string; or an empty string if this string is empty.
var lastCharacter: String { return length > 0 ? substring(from: length - 1) : "" }
/// Returns `true` if the first letter of this string is capitalized.
/// An empty string will return `false`.
var isCapitalized: Bool { return length > 0 && firstCharacter == firstCharacter.uppercased() }
/// Returns `true` if this entire string is uppercased.
/// An empty string will return `false`.
var isUppercased: Bool { return length > 0 && self == uppercased() }
/// Returns `true` if this entire string is lowercased.
/// An empty string will return `false`.
var isLowercased: Bool { return length > 0 && self == lowercased() }
/// Last path component of this string.
/// Shorthand for `(self as NSString).lastPathComponent`.
var lastPathComponent: String { return ns.lastPathComponent }
/// Path extension of this string.
/// Shorthand for `(self as NSString).pathExtension`.
var pathExtension: String { return ns.pathExtension }
/// This string with the last path component removed.
/// Shorthand for `(self as NSString).deletingLastPathComponent`.
var deletingLastPathComponent: String { return ns.deletingLastPathComponent }
/// This string with the path extension removed.
/// Shorthand for `(self as NSString).deletingPathExtension`.
var deletingPathExtension: String { return ns.deletingPathExtension }
/// Number of lines contained in this string.
var lineCount: Int { return components(separatedBy: .newlines).count }
/// Number of lines contained in this string.
var wordCount: Int { return components(separatedBy: .whitespacesAndNewlines).count }
/// File URL instance that uses this string as the file URL path.
/// Shorthand for `URL(fileURLWithPath: self)`.
var fileURL: URL { return URL(fileURLWithPath: self) }
}
// MARK: - String Method Extension (NSString Bridging Methods)
extension String {
var trimmed: String {
return trimmed()
}
/// Trims the whitespaces and optionally newlines of this strings.
func trimmed(_ includingNewlines: Bool = false) -> String {
return trimmingCharacters(in: (includingNewlines ? .whitespacesAndNewlines : .whitespaces))
}
/// Returns a new string containing the characters of the receiver up to,
/// but not including, the one at a given index.
///
/// - Parameters:
/// - index: An index. The value must lie within the bounds
/// of the receiver, or be equal to the length of the receiver.
/// Raises an rangeException if (anIndex - 1) lies beyond the end of the
/// receiver.
/// - Returns: A new string containing the characters of the receiver up
/// to, but not including, the one at anIndex. If anIndex is equal to the
/// length of the string, returns a copy of the receiver.
func substring(to index: Int) -> String {
return ns.substring(to: index)
}
/// Returns a new string containing the characters of the receiver up to,
/// but not including, the one at a given index.
///
/// - Parameters:
/// - index: An index. The value must lie within the bounds of
/// the receiver, or be equal to the length of the receiver.
/// Raises an rangeException if (anIndex - 1) lies beyond the end of the
/// receiver.
/// - Returns: A new string containing the characters of the receiver from
/// the one at anIndex to the end. If anIndex is equal to the length of the
/// string, returns an empty string.
func substring(from index: Int) -> String {
return ns.substring(from: index)
}
///
/// - Parameters:
/// - range: A range. The range must not exceed the bounds of the
/// receiver. Raises an rangeException if `(aRange.location - 1)` or
/// `(aRange.location + aRange.length - 1)` lies beyond the end of the
/// receiver.
/// - Returns: A string object containing the characters of the receiver
/// that lie within `range`.
func substring(with range: NSRange) -> String {
guard range.isValid else { return "" }
return ns.substring(with: range)
}
///
/// - Parameters:
/// - range: A range. The range must not exceed the bounds of the
/// receiver. Raises an rangeException if `(aRange.location - 1)` or
/// `(aRange.location + aRange.length - 1)` lies beyond the end of the
/// receiver.
/// - Returns: A string object containing the characters of the receiver
/// that lie within `range`.
func substring(with range: Range<Int>) -> String {
guard range.bridgedRange.isValid else { return "" }
return ns.substring(with: range.bridgedRange)
}
///
/// - Parameters:
/// - range: A range. The range must not exceed the bounds of the
/// receiver. Raises an rangeException if `(aRange.location - 1)` or
/// `(aRange.location + aRange.length - 1)` lies beyond the end of the
/// receiver.
/// - Returns: A string object containing the characters of the receiver
/// that lie within `range`.
subscript (range: Range<Int>) -> String {
guard range.bridgedRange.isValid else { return "" }
return ns.substring(with: range.bridgedRange)
}
///
/// - parameter anIndex:
/// - Returns:
func char(at anIndex: Int) -> String {
return substring(with: NSMakeRange(anIndex, 1))
}
///
/// - parameter substring:
/// - Returns:
func range(of substring: String) -> NSRange {
return ns.range(of: substring)
}
///
/// - parameter substring:
/// - Returns:
func index(of substring: String) -> Int {
return range(of: substring).location
}
///
/// - parameter options:
/// - Returns:
func format(using options: StringFormattingOption = []) -> String {
return String(with: self, options: options)
}
/// Returns a new string made by appending to the receiver a given string.
///
/// - Parameters:
/// - str: The path component to append to the receiver.
/// - Returns: A new string made by appending aString to the receiver,
/// preceded if necessary by a path separator.
func appendingPathComponent(_ str: String) -> String {
return ns.appendingPathComponent(str)
}
/// Returns a new string made by appending to the receiver an extension
/// separator followed by a given extension.
///
/// - Parameters:
/// - ext: The extension to append to the receiver.
/// - Returns: A new string made by appending to the receiver an extension
/// separator followed by `ext`.
func appendingPathExtension(_ ext: String) -> String? {
return ns.appendingPathExtension(ext)
}
/// Returns a new string in which all occurrences of a target string in a
/// specified range of the receiver are replaced by another given string.
///
/// - Parameters:
/// - target: to replace.
/// - replacement: to replace `target` with.
/// - options: to use when comparing `target` with the receiver.
/// - range: in the receiver in which to search for `target`.
/// - Returns: A new string in which all occurrences of `target`, matched
/// using `options`, in `searchRange` of the receiver are replaced by
/// `replacement`.
func replacingOccurrences(of target: String, with replacement: String, options: NSString.CompareOptions, range: NSRange) -> String {
return ns.replacingOccurrences(of: target, with: replacement, options: options, range: range)
}
///
///
/// - Parameters:
/// - string:
/// - options:
/// - range:
/// - Returns:
func matches(in string: String, options: NSRegularExpression.Options, range: NSRange? = nil) -> [NSTextCheckingResult] {
return matches(in: string, options: (options, []), range: range)
}
///
///
/// - Parameters:
/// - string:
/// - options:
/// - range:
/// - Returns:
func matches(in string: String, options: NSRegularExpression.MatchingOptions, range: NSRange? = nil) -> [NSTextCheckingResult] {
return matches(in: string, options: ([], options), range: range)
}
///
///
/// - Parameters:
/// - string:
/// - options:
/// - range:
/// - Returns:
func matches(in string: String, options: (NSRegularExpression.Options, NSRegularExpression.MatchingOptions) = ([],[]), range: NSRange? = nil) -> [NSTextCheckingResult] {
do {
return (try NSRegularExpression(pattern: self, options: options.0))
.matches(in: string,
options: options.1,
range: range ?? string.range)
} catch {
print(error.localizedDescription)
}
return []
}
///
///
/// - Parameters:
/// - string:
/// - options:
/// - range:
/// - block:
/// - Returns:
func enumerateMatches(in string: String, options: NSRegularExpression.Options, range: NSRange? = nil, using block: (NSTextCheckingResult?, NSRegularExpression.MatchingFlags, UnsafeMutablePointer<ObjCBool>) -> Void) {
enumerateMatches(in: string, options: (options, []), using: block)
}
///
///
/// - Parameters:
/// - string:
/// - options:
/// - range:
/// - block:
/// - Returns:
func enumerateMatches(in string: String, options: NSRegularExpression.MatchingOptions, range: NSRange? = nil, using block: (NSTextCheckingResult?, NSRegularExpression.MatchingFlags, UnsafeMutablePointer<ObjCBool>) -> Void) {
enumerateMatches(in: string, options: ([], options), using: block)
}
///
///
/// - Parameters:
/// - string:
/// - options:
/// - range:
/// - block:
/// - Returns:
func enumerateMatches(in string: String, options: (NSRegularExpression.Options, NSRegularExpression.MatchingOptions) = ([],[]), range: NSRange? = nil, using block: (NSTextCheckingResult?, NSRegularExpression.MatchingFlags, UnsafeMutablePointer<ObjCBool>) -> Void) {
do {
(try NSRegularExpression(pattern: self, options: options.0))
.enumerateMatches(in: string,
options: options.1,
range: range ?? string.range,
using: block)
} catch {
print(error.localizedDescription)
}
}
///
///
/// - Parameters:
/// - string:
/// - options:
/// - range:
/// - Returns:
func doesMatch(_ string: String, options: NSRegularExpression.Options, range: NSRange? = nil) -> Bool {
return doesMatch(string, options: (options, []), range: range)
}
///
///
/// - Parameters:
/// - string:
/// - options:
/// - range:
/// - Returns:
func doesMatch(_ string: String, options: NSRegularExpression.MatchingOptions, range: NSRange? = nil) -> Bool {
return doesMatch(string, options: ([], options), range: range)
}
///
///
/// - Parameters:
/// - string:
/// - options:
/// - range:
/// - Returns:
func doesMatch(_ string: String, options: (NSRegularExpression.Options, NSRegularExpression.MatchingOptions) = ([],[]), range: NSRange? = nil) -> Bool {
return firstMatch(in: string, options: options, range: range) != nil
}
///
///
/// - Parameters:
/// - string:
/// - options:
/// - range:
/// - Returns:
func firstMatch(in string: String, options: NSRegularExpression.Options, range: NSRange? = nil) -> NSTextCheckingResult? {
return firstMatch(in: string, options: (options, []), range: range)
}
///
///
/// - Parameters:
/// - string:
/// - options:
/// - range:
/// - Returns:
func firstMatch(in string: String, options: NSRegularExpression.MatchingOptions, range: NSRange? = nil) -> NSTextCheckingResult? {
return firstMatch(in: string, options: ([], options), range: range)
}
///
///
/// - Parameters:
/// - string:
/// - options:
/// - range:
/// - Returns:
func firstMatch(in string: String, options: (NSRegularExpression.Options, NSRegularExpression.MatchingOptions) = ([],[]), range: NSRange? = nil) -> NSTextCheckingResult? {
do {
return (try NSRegularExpression(pattern: self, options: options.0))
.firstMatch(in: string, options: options.1,
range: range ?? string.range)
} catch {
print(error.localizedDescription)
}
return nil
}
///
///
///
func split(by pattern: String) -> [String] {
guard let re = try? NSRegularExpression(pattern: pattern, options: [])
else { return [] }
let nsString = self as NSString // needed for range compatibility
let stop = "<SomeStringThatYouDoNotExpectToOccurInSelf>"
let modifiedString = re.stringByReplacingMatches(
in: self,
options: [],
range: NSRange(location: 0, length: nsString.length),
withTemplate: stop)
return modifiedString.components(separatedBy: stop)
}
///
///
/// - Parameters:
/// - attributes:
/// - Returns:
func size(withAttributes attributes: [NSAttributedString.Key: Any]) -> CGSize {
return ns.size(withAttributes: attributes)
}
///
///
/// - Parameters:
/// - attributes:
/// - Returns:
func width(withAttributes attributes: [NSAttributedString.Key: Any]) -> CGFloat {
return size(withAttributes: attributes).width
}
///
///
/// - Parameters:
/// - attributes:
/// - Returns:
func height(withAttributes attributes: [NSAttributedString.Key: Any]) -> CGFloat {
return size(withAttributes: attributes).height
}
}
extension String {
///
init(with arg: CVarArg, options: StringFormattingOption = []) {
var text = String(format: "%@", arg)
if options.contains(.escapeWhitespaces) {
text = text.replacingOccurrences(of: "\\r", with: "\\\\r", options: .regularExpression)
.replacingOccurrences(of: "\\n", with: "\\\\n", options: .regularExpression, range: text.range)
.replacingOccurrences(of: "\\t", with: "\\\\t", options: .regularExpression, range: text.range)
.replacingOccurrences(of: "\\s", with: "\\\\s", options: .regularExpression, range: text.range)
}
if options.contains(.escapeRegex) {
text = text.replacingOccurrences(of: "[?!{}()^<>=.*\\[\\]]", with: "\\\\$0", options: .regularExpression)
}
self = text
}
}
// MARK: - UIImage Method Extension
extension UIImage {
/// Width of this image.
var width: CGFloat { return size.width }
/// Height of this image.
var height: CGFloat { return size.height }
///
struct CGAttribute: BaseRawRepresentable {
typealias This = CGAttribute
typealias RawValue = String
let rawValue: String
static let tintColor = This("tintColor")
static let alpha = This("alpha")
static let shadow = This("shadow")
static let cropSize = This("cropSize")
init(rawValue: RawValue) {
self.rawValue = rawValue
}
}
/// Returns a version of this image that is redrawn with specified
/// attributes.
///
/// - Parameters:
/// - attributes: to redraw this image with.
/// - Returns: A version of this image that is redrawn with the specified
/// `attributes`, or `nil` if this operation fails.
func with(attributes: [CGAttribute: Any]) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
guard
let cgImage = cgImage,
let context = UIGraphicsGetCurrentContext()
else { return nil }
let rect = CGRect(origin: .zero, size: size)
context.translateBy(x: 0, y: size.height)
context.scaleBy(x: 1.0, y: -1.0)
if let shadow = attributes[.shadow] as? NSShadow {
context.setShadow(offset: shadow.shadowOffset,
blur: shadow.shadowBlurRadius,
color: (shadow.color ?? UIColor.black.withAlphaComponent(0.2)).cgColor)
}
context.draw(cgImage, in: rect)
context.clip(to: rect, mask: cgImage)
if let tintColor = attributes[.tintColor] as? UIColor {
context.setFillColor(tintColor.cgColor)
context.setBlendMode(.screen)
context.fill(rect)
}
if let alpha = attributes[.alpha] as? CGFloat, alpha < 1.0 {
context.setFillColor(UIColor.white.cgColor)
context.setBlendMode(.normal)
context.setAlpha(1.0 - alpha)
context.fill(rect)
}
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
if let cropSize = attributes[.cropSize] as? CGSize {
return newImage?.scalingAndCropping(to: cropSize)
}
return newImage
}
/// Returns an image that is scaled and cropped to a target size.
///
/// - Parameters:
/// - targetSize: Size to scale and/or crop this image to.
/// - Returns: A copy of this image that is scaled and cropped to a
/// target size.
func scalingAndCropping(to targetSize: CGSize) -> UIImage? {
var scaleFactor: CGFloat = 0.0
var scaledSize = targetSize
var thumbnailOrigin: CGPoint = .zero
if (size != targetSize) {
let widthFactor = targetSize.width / width
let heightFactor = targetSize.height / height
scaleFactor = max(widthFactor, heightFactor)
scaledSize.width = width * scaleFactor
scaledSize.height = height * scaleFactor
if (widthFactor > heightFactor) {
thumbnailOrigin.y = (targetSize.height - scaledSize.height) * 0.5
} else if (widthFactor < heightFactor) {
thumbnailOrigin.x = (targetSize.width - scaledSize.width) * 0.5
}
}
UIGraphicsBeginImageContext(targetSize)
let rect = CGRect(origin: thumbnailOrigin, size: scaledSize)
draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
// MARK: - URL Path Concatenation
extension URL {
static func +/ (lhs: URL, rhs: String) -> URL {
return lhs.appendingPathComponent(rhs)
}
static func +/ (lhs: URL, rhs: String?) -> URL? {
guard let rhs = rhs else { return nil }
return lhs.appendingPathComponent(rhs)
}
}
func +/ (lhs: URL?, rhs: String) -> URL? {
guard let lhs = lhs else { return nil }
return lhs.appendingPathComponent(rhs)
}
// MARK: - URL Property Extension
extension URL {
///
var pathComponentsResolvingSymlinksInPath: [String] {
return resolvingSymlinksInPath().pathComponents
}
@available(OSX 10.11, iOS 9.0, *)
func relativeTo(baseURL: URL) -> URL {
return URL(fileURLWithPath: resolvingSymlinksInPath().path, relativeTo: baseURL)
}
}
| mit | 5279db404fcc499a652f62a46cbf8e2f | 33.501699 | 269 | 0.609618 | 4.531459 | false | false | false | false |
natestedman/PrettyOkayKit | PrettyOkayKit/Dictionary+Decoding.swift | 1 | 1584 | // Copyright (c) 2016, Nate Stedman <[email protected]>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
import Foundation
extension Dictionary
{
@warn_unused_result
func decode<Decoded>(key: Key) throws -> Decoded
{
if let value = self[key] as? Decoded
{
return value
}
else
{
throw DecodeKeyError(key: "\(key)")
}
}
@warn_unused_result
func decodeURL(key: Key) throws -> NSURL
{
let URLString: String = try decode(key)
if let URL = NSURL(string: URLString) where URL.scheme == "http" || URL.scheme == "https"
{
return URL
}
else
{
throw InvalidURLError(URLString: URLString, key: "\(key)")
}
}
@warn_unused_result
func sub(key: Key) throws -> Dictionary
{
return try decode(key)
}
}
| isc | f8da9539848b867a97ebea05a83b675d | 29.461538 | 97 | 0.643939 | 4.424581 | false | false | false | false |
PedroTrujilloV/TIY-Assignments | 33--The-Eagle-has-Landed/DynamicsDemo/DynamicsDemo/ViewController.swift | 1 | 3928 | //
// ViewController.swift
// DynamicsDemo
//
// Source from Ray Wenderlich tutorial:
// http://www.raywenderlich.com/76147/uikit-dynamics-tutorial-swift
// Modified by Ben Gohlke on 11/17/15 to function properly on iOS 9 and Swift 2.0
import UIKit
class ViewController: UIViewController, UICollisionBehaviorDelegate
{
var animator: UIDynamicAnimator!
var gravity: UIGravityBehavior!
var collision: UICollisionBehavior!
var firstContact = true
var square: UIView!
var snap: UISnapBehavior!
override func viewDidLoad()
{
super.viewDidLoad()
// let square = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
square = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
square.backgroundColor = UIColor.grayColor()
view.addSubview(square)
animator = UIDynamicAnimator(referenceView: view)
gravity = UIGravityBehavior(items: [square])
animator.addBehavior(gravity)
collision = UICollisionBehavior(items: [square])
collision.translatesReferenceBoundsIntoBoundary = true
animator.addBehavior(collision)
let barrier = UIView(frame: CGRect(x: 0, y: 300, width: 130, height: 20))
barrier.backgroundColor = UIColor.redColor()
view.addSubview(barrier)
// collision.addItem(barrier)
collision.addBoundaryWithIdentifier("barrier", forPath: UIBezierPath(rect: barrier.frame))
collision.collisionDelegate = self
let itemBehavior = UIDynamicItemBehavior(items: [square])
itemBehavior.elasticity = 0.6
animator.addBehavior(itemBehavior)
// var updateCount = 0
// collision.action = {
// if updateCount % 3 == 0
// {
// let outline = UIView(frame: square.bounds)
// outline.transform = square.transform
// outline.center = square.center
//
// outline.alpha = 0.5
// outline.backgroundColor = UIColor.clearColor()
// outline.layer.borderColor = square.layer.presentationLayer()?.backgroundColor
// outline.layer.borderWidth = 1.0
// self.view.addSubview(outline)
// }
//
// ++updateCount
// }
}
func collisionBehavior(behavior: UICollisionBehavior, beganContactForItem item: UIDynamicItem, withBoundaryIdentifier identifier: NSCopying?, atPoint p: CGPoint) {
print("Boundary contact occurred - \(identifier)")
let collidingView = item as! UIView
collidingView.backgroundColor = UIColor.yellowColor()
UIView.animateWithDuration(0.3) {
collidingView.backgroundColor = UIColor.grayColor()
}
// if firstContact
// {
// firstContact = false
//
// let square = UIView(frame: CGRect(x: 30, y: 0, width: 100, height: 100))
// square.backgroundColor = UIColor.grayColor()
// view.addSubview(square)
//
// collision.addItem(square)
// gravity.addItem(square)
//
// let attach = UIAttachmentBehavior(item: collidingView, attachedToItem: square)
// animator.addBehavior(attach)
// }
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?)
{
if snap != nil
{
animator.removeBehavior(snap)
}
let touch = touches.first! as UITouch
snap = UISnapBehavior(item: square, snapToPoint: touch.locationInView(view))
animator.addBehavior(snap)
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| cc0-1.0 | 06f65bf56af7303159050805ae733516 | 32.288136 | 167 | 0.601578 | 4.819632 | false | false | false | false |
planetexpress69/SlideMenuControllerSwift | SlideMenuControllerSwift/LeftViewController.swift | 2 | 4815 | //
// LeftViewController.swift
// SlideMenuControllerSwift
//
// Created by Yuji Hato on 12/3/14.
//
import UIKit
enum LeftMenu: Int {
case Main = 0
case Swift
case Java
case Go
case NonMenu
}
protocol LeftMenuProtocol : class {
func changeViewController(menu: LeftMenu)
}
class LeftViewController : UIViewController, LeftMenuProtocol {
@IBOutlet weak var tableView: UITableView!
var menus = ["Main", "Swift", "Java", "Go", "NonMenu"]
var mainViewController: UIViewController!
var swiftViewController: UIViewController!
var javaViewController: UIViewController!
var goViewController: UIViewController!
var nonMenuViewController: UIViewController!
var imageHeaderView: ImageHeaderView!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.separatorColor = UIColor(red: 224/255, green: 224/255, blue: 224/255, alpha: 1.0)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let swiftViewController = storyboard.instantiateViewControllerWithIdentifier("SwiftViewController") as! SwiftViewController
self.swiftViewController = UINavigationController(rootViewController: swiftViewController)
let javaViewController = storyboard.instantiateViewControllerWithIdentifier("JavaViewController") as! JavaViewController
self.javaViewController = UINavigationController(rootViewController: javaViewController)
let goViewController = storyboard.instantiateViewControllerWithIdentifier("GoViewController") as! GoViewController
self.goViewController = UINavigationController(rootViewController: goViewController)
let nonMenuController = storyboard.instantiateViewControllerWithIdentifier("NonMenuController") as! NonMenuController
nonMenuController.delegate = self
self.nonMenuViewController = UINavigationController(rootViewController: nonMenuController)
self.tableView.registerCellClass(BaseTableViewCell.self)
self.imageHeaderView = ImageHeaderView.loadNib()
self.view.addSubview(self.imageHeaderView)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.imageHeaderView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: 160)
self.view.layoutIfNeeded()
}
func changeViewController(menu: LeftMenu) {
switch menu {
case .Main:
self.slideMenuController()?.changeMainViewController(self.mainViewController, close: true)
case .Swift:
self.slideMenuController()?.changeMainViewController(self.swiftViewController, close: true)
case .Java:
self.slideMenuController()?.changeMainViewController(self.javaViewController, close: true)
case .Go:
self.slideMenuController()?.changeMainViewController(self.goViewController, close: true)
case .NonMenu:
self.slideMenuController()?.changeMainViewController(self.nonMenuViewController, close: true)
}
}
}
extension LeftViewController : UITableViewDelegate {
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if let menu = LeftMenu(rawValue: indexPath.item) {
switch menu {
case .Main, .Swift, .Java, .Go, .NonMenu:
return BaseTableViewCell.height()
}
}
return 0
}
}
extension LeftViewController : UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return menus.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let menu = LeftMenu(rawValue: indexPath.item) {
switch menu {
case .Main, .Swift, .Java, .Go, .NonMenu:
let cell = BaseTableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: BaseTableViewCell.identifier)
cell.setData(menus[indexPath.row])
return cell
}
}
return UITableViewCell()
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let menu = LeftMenu(rawValue: indexPath.item) {
self.changeViewController(menu)
}
}
}
extension LeftViewController: UIScrollViewDelegate {
func scrollViewDidScroll(scrollView: UIScrollView) {
if self.tableView == scrollView {
}
}
}
| mit | f91f25bd01f96ebcf06260850db43005 | 35.203008 | 131 | 0.68432 | 5.46538 | false | false | false | false |
FuckBoilerplate/RxCache | watchOS/Pods/RxSwift/RxSwift/Observables/Implementations/RefCount.swift | 6 | 2531 | //
// RefCount.swift
// Rx
//
// Created by Krunoslav Zaher on 3/5/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class RefCountSink<CO: ConnectableObservableType, O: ObserverType>
: Sink<O>
, ObserverType where CO.E == O.E {
typealias Element = O.E
typealias Parent = RefCount<CO>
private let _parent: Parent
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
let subscription = _parent._source.subscribeSafe(self)
_parent._lock.lock(); defer { _parent._lock.unlock() } // {
if _parent._count == 0 {
_parent._count = 1
_parent._connectableSubscription = _parent._source.connect()
}
else {
_parent._count = _parent._count + 1
}
// }
return Disposables.create {
subscription.dispose()
self._parent._lock.lock(); defer { self._parent._lock.unlock() } // {
if self._parent._count == 1 {
self._parent._connectableSubscription!.dispose()
self._parent._count = 0
self._parent._connectableSubscription = nil
}
else if self._parent._count > 1 {
self._parent._count = self._parent._count - 1
}
else {
rxFatalError("Something went wrong with RefCount disposing mechanism")
}
// }
}
}
func on(_ event: Event<Element>) {
switch event {
case .next:
forwardOn(event)
case .error, .completed:
forwardOn(event)
dispose()
}
}
}
class RefCount<CO: ConnectableObservableType>: Producer<CO.E> {
fileprivate let _lock = NSRecursiveLock()
// state
fileprivate var _count = 0
fileprivate var _connectableSubscription = nil as Disposable?
fileprivate let _source: CO
init(source: CO) {
_source = source
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == CO.E {
let sink = RefCountSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
| mit | ea02a2e647a54a1d2be79273e83afe98 | 29.119048 | 141 | 0.541502 | 4.608379 | false | false | false | false |
zjjzmw1/speedxSwift | speedxSwift/speedxSwift/HomeVC.swift | 1 | 4075 | //
// Home_VC.swift
// LBTabBar
//
// Created by chenlei_mac on 15/8/25.
// Copyright (c) 2015年 Bison. All rights reserved.
//
import UIKit
import RealmSwift
class HomeVC: BaseViewController,UITableViewDelegate,UITableViewDataSource {
/// 骑行管理单例
var cycManager = CyclingManager.getCyclingManager()
var dataArray = NSMutableArray()
var format = NSDateFormatter()
/// 表格
var tableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "我"
format.dateFormat = "yyyy-MM-dd HH:mm:ss"
/// 暂时写骑行列表
tableView = UITableView(frame: self.view.frame, style: .Grouped)
tableView.delegate = self
tableView.dataSource = self
self.view.addSubview(tableView)
// Class 注册
tableView.registerClass(HomeCell.self, forCellReuseIdentifier: "HomeCellID")
/// 读取数据库的数据
var ao:Results<ActivityObject>?
ao = cycManager.realm!.objects(ActivityObject)
if (ao?.count)! > 0 && ao!.last!.isFinished {
for object in ao! {
if object.isFinished {// 骑行结束的
dataArray .addObject(object)
}
}
}
tableView.reloadData()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
//表格的区块里有多少个单元格
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count
}
//表格相应位置的单元格,显示哪些内容
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let object = dataArray[indexPath.row] as! ActivityObject
// cell.textLabel?.text = format.stringFromDate(object.startTime)
// 自定义cell
var cell:HomeCell!
cell = tableView.dequeueReusableCellWithIdentifier("HomeCellID") as! HomeCell
cell.indexP = indexPath
cell?.testLabel?.text = format.stringFromDate(object.startTime)
cell.testLabel .sizeToFit()
// if indexPath.row == 0 {
// cell.testButton.hidden = true
// }
// cell.buttonClickBlock = {
// (ind,btn) -> () in
// print(indexPath.row)
// print(btn.currentTitle!)
// }
return cell
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
return .Delete
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
let object = dataArray[indexPath.row] as! ActivityObject
/// 读取数据库的数据
try! cycManager.realm?.write(){
dataArray.removeObject(object)
cycManager.realm!.delete(object)
}
tableView.reloadData()
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print(indexPath.row)
let object = dataArray[indexPath.row] as! ActivityObject
let mapV = ShowMapVC()
mapV.myObject = object
// self.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(mapV, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 8f76612fb828f329d711764541da6f4a | 30.432 | 148 | 0.601171 | 5.14941 | false | false | false | false |
BeauNouvelle/SimpleCheckbox | demo/ViewController.swift | 1 | 2626 | //
// ViewController.swift
// Checkbox
//
// Created by Beau Nouvelle on 5/8/17.
// Copyright © 2017 Beau Nouvelle. All rights reserved.
//
import UIKit
import SimpleCheckbox
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
addCheckboxSubviews()
}
func addCheckboxSubviews() {
// circle
let circleBox = Checkbox(frame: CGRect(x: 30, y: 40, width: 25, height: 25))
circleBox.borderStyle = .circle
circleBox.checkmarkStyle = .circle
circleBox.borderLineWidth = 1
circleBox.uncheckedBorderColor = .lightGray
circleBox.checkedBorderColor = .blue
circleBox.checkmarkSize = 0.8
circleBox.checkmarkColor = .blue
circleBox.addTarget(self, action: #selector(circleBoxValueChanged(sender:)), for: .valueChanged)
view.addSubview(circleBox)
// square
let squareBox = Checkbox(frame: CGRect(x: 30, y: 80, width: 25, height: 25))
squareBox.tintColor = .black
squareBox.borderStyle = .square
squareBox.checkmarkStyle = .square
squareBox.uncheckedBorderColor = .lightGray
squareBox.borderLineWidth = 1
squareBox.valueChanged = { (value) in
print("squarebox value change: \(value)")
}
view.addSubview(squareBox)
// cross
let crossBox = Checkbox(frame: CGRect(x: 30, y: 120, width: 25, height: 25))
crossBox.borderStyle = .square
crossBox.checkmarkStyle = .cross
crossBox.checkmarkSize = 0.7
crossBox.borderCornerRadius = 5
crossBox.valueChanged = { (value) in
print("crossBox value change: \(value)")
}
view.addSubview(crossBox)
// tick
let tickBox = Checkbox(frame: CGRect(x: 30, y: 160, width: 25, height: 25))
tickBox.borderStyle = .square
tickBox.checkmarkStyle = .tick
tickBox.checkmarkSize = 0.7
tickBox.valueChanged = { (value) in
print("tickBox value change: \(value)")
}
view.addSubview(tickBox)
// Emoji
let emojiBox = Checkbox(frame: CGRect(x: 30, y: 160, width: 25, height: 25))
emojiBox.borderStyle = .square
emojiBox.emoji = "🥰"
emojiBox.checkmarkSize = 0.7
emojiBox.valueChanged = { (value) in
print("emojiBox value change: \(value)")
}
view.addSubview(emojiBox)
}
// target action example
@objc func circleBoxValueChanged(sender: Checkbox) {
print("circleBox value change: \(sender.isChecked)")
}
}
| mit | 4cb16dc114be35393f91e83492271100 | 31.37037 | 104 | 0.617086 | 4.263415 | false | false | false | false |
longitachi/ZLPhotoBrowser | Sources/Edit/ZLEditImageViewController.swift | 1 | 68012 | //
// ZLEditImageViewController.swift
// ZLPhotoBrowser
//
// Created by long on 2020/8/26.
//
// Copyright (c) 2020 Long Zhang <[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
public class ZLEditImageModel: NSObject {
public let drawPaths: [ZLDrawPath]
public let mosaicPaths: [ZLMosaicPath]
public let editRect: CGRect?
public let angle: CGFloat
public let brightness: Float
public let contrast: Float
public let saturation: Float
public let selectRatio: ZLImageClipRatio?
public let selectFilter: ZLFilter?
public let textStickers: [(state: ZLTextStickerState, index: Int)]?
public let imageStickers: [(state: ZLImageStickerState, index: Int)]?
public init(
drawPaths: [ZLDrawPath],
mosaicPaths: [ZLMosaicPath],
editRect: CGRect?,
angle: CGFloat,
brightness: Float,
contrast: Float,
saturation: Float,
selectRatio: ZLImageClipRatio?,
selectFilter: ZLFilter,
textStickers: [(state: ZLTextStickerState, index: Int)]?,
imageStickers: [(state: ZLImageStickerState, index: Int)]?
) {
self.drawPaths = drawPaths
self.mosaicPaths = mosaicPaths
self.editRect = editRect
self.angle = angle
self.brightness = brightness
self.contrast = contrast
self.saturation = saturation
self.selectRatio = selectRatio
self.selectFilter = selectFilter
self.textStickers = textStickers
self.imageStickers = imageStickers
super.init()
}
}
open class ZLEditImageViewController: UIViewController {
static let maxDrawLineImageWidth: CGFloat = 600
static let shadowColorFrom = UIColor.black.withAlphaComponent(0.35).cgColor
static let shadowColorTo = UIColor.clear.cgColor
static let ashbinSize = CGSize(width: 160, height: 80)
private let tools: [ZLEditImageConfiguration.EditTool]
private let adjustTools: [ZLEditImageConfiguration.AdjustTool]
private var animate = false
private var originalImage: UIImage
// 图片可编辑rect
private var editRect: CGRect
private var selectRatio: ZLImageClipRatio?
private var editImage: UIImage
private var editImageWithoutAdjust: UIImage
private var editImageAdjustRef: UIImage?
private lazy var containerView: UIView = {
let view = UIView()
view.clipsToBounds = true
return view
}()
// Show image.
private lazy var imageView: UIImageView = {
let view = UIImageView(image: originalImage)
view.contentMode = .scaleAspectFit
view.clipsToBounds = true
view.backgroundColor = .black
return view
}()
// Show draw lines.
private lazy var drawingImageView: UIImageView = {
let view = UIImageView()
view.contentMode = .scaleAspectFit
view.isUserInteractionEnabled = true
return view
}()
// Show text and image stickers.
private lazy var stickersContainer = UIView()
// 处理好的马赛克图片
private var mosaicImage: UIImage?
// 显示马赛克图片的layer
private var mosaicImageLayer: CALayer?
// 显示马赛克图片的layer的mask
private var mosaicImageLayerMaskLayer: CAShapeLayer?
private var selectedTool: ZLEditImageConfiguration.EditTool?
private var selectedAdjustTool: ZLEditImageConfiguration.AdjustTool?
private lazy var editToolCollectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: 30, height: 30)
layout.minimumLineSpacing = 20
layout.minimumInteritemSpacing = 20
layout.scrollDirection = .horizontal
let view = UICollectionView(frame: .zero, collectionViewLayout: layout)
view.backgroundColor = .clear
view.delegate = self
view.dataSource = self
view.showsHorizontalScrollIndicator = false
ZLEditToolCell.zl.register(view)
return view
}()
private var drawColorCollectionView: UICollectionView?
private var filterCollectionView: UICollectionView?
private var adjustCollectionView: UICollectionView?
private var adjustSlider: ZLAdjustSlider?
private let drawColors: [UIColor]
private var currentDrawColor = ZLPhotoConfiguration.default().editImageConfiguration.defaultDrawColor
private var drawPaths: [ZLDrawPath]
private var redoDrawPaths: [ZLDrawPath]
private var mosaicPaths: [ZLMosaicPath]
private var redoMosaicPaths: [ZLMosaicPath]
private let canRedo = ZLPhotoConfiguration.default().editImageConfiguration.canRedo
// collectionview 中的添加滤镜的小图
private var thumbnailFilterImages: [UIImage] = []
// 选择滤镜后对原图添加滤镜后的图片
private var filterImages: [String: UIImage] = [:]
private var currentFilter: ZLFilter
private var stickers: [UIView] = []
private var isScrolling = false
private var shouldLayout = true
private var imageStickerContainerIsHidden = true
private var angle: CGFloat
private var brightness: Float
private var contrast: Float
private var saturation: Float
private lazy var panGes: UIPanGestureRecognizer = {
let pan = UIPanGestureRecognizer(target: self, action: #selector(drawAction(_:)))
pan.maximumNumberOfTouches = 1
pan.delegate = self
return pan
}()
private var toolViewStateTimer: Timer?
// 第一次进入界面时,布局后frame,裁剪dimiss动画使用
var originalFrame: CGRect = .zero
var imageSize: CGSize {
if angle == -90 || angle == -270 {
return CGSize(width: originalImage.size.height, height: originalImage.size.width)
}
return originalImage.size
}
@objc public var drawColViewH: CGFloat = 50
@objc public var filterColViewH: CGFloat = 80
@objc public var adjustColViewH: CGFloat = 60
@objc public lazy var cancelBtn: ZLEnlargeButton = {
let btn = ZLEnlargeButton(type: .custom)
btn.setImage(.zl.getImage("zl_retake"), for: .normal)
btn.addTarget(self, action: #selector(cancelBtnClick), for: .touchUpInside)
btn.adjustsImageWhenHighlighted = false
btn.enlargeInset = 30
return btn
}()
@objc public lazy var mainScrollView: UIScrollView = {
let view = UIScrollView()
view.backgroundColor = .black
view.minimumZoomScale = 1
view.maximumZoomScale = 3
view.delegate = self
return view
}()
// 上方渐变阴影层
@objc public lazy var topShadowView = UIView()
@objc public lazy var topShadowLayer: CAGradientLayer = {
let layer = CAGradientLayer()
layer.colors = [ZLEditImageViewController.shadowColorFrom, ZLEditImageViewController.shadowColorTo]
layer.locations = [0, 1]
return layer
}()
// 下方渐变阴影层
@objc public lazy var bottomShadowView = UIView()
@objc public lazy var bottomShadowLayer: CAGradientLayer = {
let layer = CAGradientLayer()
layer.colors = [ZLEditImageViewController.shadowColorTo, ZLEditImageViewController.shadowColorFrom]
layer.locations = [0, 1]
return layer
}()
@objc public lazy var doneBtn: UIButton = {
let btn = UIButton(type: .custom)
btn.titleLabel?.font = ZLLayout.bottomToolTitleFont
btn.backgroundColor = .zl.bottomToolViewBtnNormalBgColor
btn.setTitle(localLanguageTextValue(.editFinish), for: .normal)
btn.setTitleColor(.zl.bottomToolViewDoneBtnNormalTitleColor, for: .normal)
btn.addTarget(self, action: #selector(doneBtnClick), for: .touchUpInside)
btn.layer.masksToBounds = true
btn.layer.cornerRadius = ZLLayout.bottomToolBtnCornerRadius
return btn
}()
@objc public lazy var revokeBtn: UIButton = {
let btn = UIButton(type: .custom)
btn.setImage(.zl.getImage("zl_revoke_disable"), for: .disabled)
btn.setImage(.zl.getImage("zl_revoke"), for: .normal)
btn.adjustsImageWhenHighlighted = false
btn.isEnabled = false
btn.isHidden = true
btn.addTarget(self, action: #selector(revokeBtnClick), for: .touchUpInside)
return btn
}()
@objc public var redoBtn: UIButton?
@objc public lazy var ashbinView: UIView = {
let view = UIView()
view.backgroundColor = .zl.trashCanBackgroundNormalColor
view.layer.cornerRadius = 15
view.layer.masksToBounds = true
view.isHidden = true
return view
}()
@objc public lazy var ashbinImgView = UIImageView(image: .zl.getImage("zl_ashbin"), highlightedImage: .zl.getImage("zl_ashbin_open"))
@objc public var drawLineWidth: CGFloat = 5
@objc public var mosaicLineWidth: CGFloat = 25
@objc public var editFinishBlock: ((UIImage, ZLEditImageModel?) -> Void)?
@objc public var cancelEditBlock: (() -> Void)?
override public var prefersStatusBarHidden: Bool {
return true
}
override public var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .portrait
}
deinit {
cleanToolViewStateTimer()
zl_debugPrint("ZLEditImageViewController deinit")
}
@objc public class func showEditImageVC(
parentVC: UIViewController?,
animate: Bool = false,
image: UIImage,
editModel: ZLEditImageModel? = nil,
cancel: (() -> Void)? = nil,
completion: ((UIImage, ZLEditImageModel?) -> Void)?
) {
let tools = ZLPhotoConfiguration.default().editImageConfiguration.tools
if ZLPhotoConfiguration.default().showClipDirectlyIfOnlyHasClipTool,
tools.count == 1,
tools.contains(.clip) {
let vc = ZLClipImageViewController(image: image, editRect: editModel?.editRect, angle: editModel?.angle ?? 0, selectRatio: editModel?.selectRatio)
vc.clipDoneBlock = { angle, editRect, ratio in
let m = ZLEditImageModel(
drawPaths: [],
mosaicPaths: [],
editRect: editRect,
angle: angle,
brightness: 0,
contrast: 0,
saturation: 0,
selectRatio: ratio,
selectFilter: .normal,
textStickers: nil,
imageStickers: nil
)
completion?(image.zl.clipImage(angle: angle, editRect: editRect, isCircle: ratio.isCircle) ?? image, m)
}
vc.cancelClipBlock = cancel
vc.animate = animate
vc.modalPresentationStyle = .fullScreen
parentVC?.present(vc, animated: animate, completion: nil)
} else {
let vc = ZLEditImageViewController(image: image, editModel: editModel)
vc.editFinishBlock = { ei, editImageModel in
completion?(ei, editImageModel)
}
vc.cancelEditBlock = cancel
vc.animate = animate
vc.modalPresentationStyle = .fullScreen
parentVC?.present(vc, animated: animate, completion: nil)
}
}
@objc public init(image: UIImage, editModel: ZLEditImageModel? = nil) {
let editConfig = ZLPhotoConfiguration.default().editImageConfiguration
originalImage = image.zl.fixOrientation()
editImage = originalImage
editImageWithoutAdjust = originalImage
editRect = editModel?.editRect ?? CGRect(origin: .zero, size: image.size)
drawColors = editConfig.drawColors
currentFilter = editModel?.selectFilter ?? .normal
drawPaths = editModel?.drawPaths ?? []
redoDrawPaths = drawPaths
mosaicPaths = editModel?.mosaicPaths ?? []
redoMosaicPaths = mosaicPaths
angle = editModel?.angle ?? 0
brightness = editModel?.brightness ?? 0
contrast = editModel?.contrast ?? 0
saturation = editModel?.saturation ?? 0
selectRatio = editModel?.selectRatio
var ts = editConfig.tools
if ts.contains(.imageSticker), editConfig.imageStickerContainerView == nil {
ts.removeAll { $0 == .imageSticker }
}
tools = ts
adjustTools = editConfig.adjustTools
selectedAdjustTool = editConfig.adjustTools.first
super.init(nibName: nil, bundle: nil)
if !drawColors.contains(currentDrawColor) {
currentDrawColor = drawColors.first!
}
let teStic = editModel?.textStickers ?? []
let imStic = editModel?.imageStickers ?? []
var stickers: [UIView?] = Array(repeating: nil, count: teStic.count + imStic.count)
teStic.forEach { cache in
let v = ZLTextStickerView(from: cache.state)
stickers[cache.index] = v
}
imStic.forEach { cache in
let v = ZLImageStickerView(from: cache.state)
stickers[cache.index] = v
}
self.stickers = stickers.compactMap { $0 }
}
@available(*, unavailable)
public required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override open func viewDidLoad() {
super.viewDidLoad()
setupUI()
rotationImageView()
if tools.contains(.filter) {
generateFilterImages()
}
}
override open func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
guard shouldLayout else {
return
}
shouldLayout = false
zl_debugPrint("edit image layout subviews")
var insets = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0)
if #available(iOS 11.0, *) {
insets = self.view.safeAreaInsets
}
insets.top = max(20, insets.top)
mainScrollView.frame = view.bounds
resetContainerViewFrame()
topShadowView.frame = CGRect(x: 0, y: 0, width: view.zl.width, height: 150)
topShadowLayer.frame = topShadowView.bounds
cancelBtn.frame = CGRect(x: 30, y: insets.top + 10, width: 28, height: 28)
bottomShadowView.frame = CGRect(x: 0, y: view.zl.height - 140 - insets.bottom, width: view.zl.width, height: 140 + insets.bottom)
bottomShadowLayer.frame = bottomShadowView.bounds
if canRedo, let redoBtn = redoBtn {
redoBtn.frame = CGRect(x: view.zl.width - 15 - 35, y: 30, width: 35, height: 30)
revokeBtn.frame = CGRect(x: redoBtn.zl.left - 10 - 35, y: 30, width: 35, height: 30)
} else {
revokeBtn.frame = CGRect(x: view.zl.width - 15 - 35, y: 30, width: 35, height: 30)
}
drawColorCollectionView?.frame = CGRect(x: 20, y: 20, width: revokeBtn.zl.left - 20 - 10, height: drawColViewH)
adjustCollectionView?.frame = CGRect(x: 20, y: 10, width: view.zl.width - 40, height: adjustColViewH)
adjustSlider?.frame = CGRect(x: view.zl.width - 60, y: view.zl.height / 2 - 100, width: 60, height: 200)
filterCollectionView?.frame = CGRect(x: 20, y: 0, width: view.zl.width - 40, height: filterColViewH)
ashbinView.frame = CGRect(
x: (view.zl.width - Self.ashbinSize.width) / 2,
y: view.zl.height - Self.ashbinSize.height - 40,
width: Self.ashbinSize.width,
height: Self.ashbinSize.height
)
ashbinImgView.frame = CGRect(
x: (Self.ashbinSize.width - 25) / 2,
y: 15,
width: 25,
height: 25
)
let toolY: CGFloat = 85
let doneBtnH = ZLLayout.bottomToolBtnH
let doneBtnW = localLanguageTextValue(.editFinish).zl.boundingRect(font: ZLLayout.bottomToolTitleFont, limitSize: CGSize(width: CGFloat.greatestFiniteMagnitude, height: doneBtnH)).width + 20
doneBtn.frame = CGRect(x: view.zl.width - 20 - doneBtnW, y: toolY - 2, width: doneBtnW, height: doneBtnH)
editToolCollectionView.frame = CGRect(x: 20, y: toolY, width: view.zl.width - 20 - 20 - doneBtnW - 20, height: 30)
if !drawPaths.isEmpty {
drawLine()
}
if !mosaicPaths.isEmpty {
generateNewMosaicImage()
}
if let index = drawColors.firstIndex(where: { $0 == self.currentDrawColor }) {
drawColorCollectionView?.scrollToItem(at: IndexPath(row: index, section: 0), at: .centeredHorizontally, animated: false)
}
}
override open func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
shouldLayout = true
}
private func generateFilterImages() {
let size: CGSize
let ratio = (originalImage.size.width / originalImage.size.height)
let fixLength: CGFloat = 200
if ratio >= 1 {
size = CGSize(width: fixLength * ratio, height: fixLength)
} else {
size = CGSize(width: fixLength, height: fixLength / ratio)
}
let thumbnailImage = originalImage.zl.resize_vI(size) ?? originalImage
DispatchQueue.global().async {
let filters = ZLPhotoConfiguration.default().editImageConfiguration.filters
self.thumbnailFilterImages = filters.map { $0.applier?(thumbnailImage) ?? thumbnailImage }
ZLMainAsync {
self.filterCollectionView?.reloadData()
self.filterCollectionView?.performBatchUpdates {} completion: { _ in
if let index = filters.firstIndex(where: { $0 == self.currentFilter }) {
self.filterCollectionView?.scrollToItem(at: IndexPath(row: index, section: 0), at: .centeredHorizontally, animated: false)
}
}
}
}
}
private func resetContainerViewFrame() {
mainScrollView.setZoomScale(1, animated: true)
imageView.image = editImage
let editSize = editRect.size
let scrollViewSize = mainScrollView.frame.size
let ratio = min(scrollViewSize.width / editSize.width, scrollViewSize.height / editSize.height)
let w = ratio * editSize.width * mainScrollView.zoomScale
let h = ratio * editSize.height * mainScrollView.zoomScale
containerView.frame = CGRect(x: max(0, (scrollViewSize.width - w) / 2), y: max(0, (scrollViewSize.height - h) / 2), width: w, height: h)
mainScrollView.contentSize = containerView.frame.size
if selectRatio?.isCircle == true {
let mask = CAShapeLayer()
let path = UIBezierPath(arcCenter: CGPoint(x: w / 2, y: h / 2), radius: w / 2, startAngle: 0, endAngle: .pi * 2, clockwise: true)
mask.path = path.cgPath
containerView.layer.mask = mask
} else {
containerView.layer.mask = nil
}
let scaleImageOrigin = CGPoint(x: -editRect.origin.x * ratio, y: -editRect.origin.y * ratio)
let scaleImageSize = CGSize(width: imageSize.width * ratio, height: imageSize.height * ratio)
imageView.frame = CGRect(origin: scaleImageOrigin, size: scaleImageSize)
mosaicImageLayer?.frame = imageView.bounds
mosaicImageLayerMaskLayer?.frame = imageView.bounds
drawingImageView.frame = imageView.frame
stickersContainer.frame = imageView.frame
// 针对于长图的优化
if (editRect.height / editRect.width) > (view.frame.height / view.frame.width * 1.1) {
let widthScale = view.frame.width / w
mainScrollView.maximumZoomScale = widthScale
mainScrollView.zoomScale = widthScale
mainScrollView.contentOffset = .zero
} else if editRect.width / editRect.height > 1 {
mainScrollView.maximumZoomScale = max(3, view.frame.height / h)
}
originalFrame = view.convert(containerView.frame, from: mainScrollView)
isScrolling = false
}
private func setupUI() {
view.backgroundColor = .black
view.addSubview(mainScrollView)
mainScrollView.addSubview(containerView)
containerView.addSubview(imageView)
containerView.addSubview(drawingImageView)
containerView.addSubview(stickersContainer)
topShadowView.layer.addSublayer(topShadowLayer)
view.addSubview(topShadowView)
topShadowView.addSubview(cancelBtn)
bottomShadowView.layer.addSublayer(bottomShadowLayer)
view.addSubview(bottomShadowView)
bottomShadowView.addSubview(editToolCollectionView)
bottomShadowView.addSubview(doneBtn)
if tools.contains(.draw) {
let drawColorLayout = UICollectionViewFlowLayout()
let drawColorItemWidth: CGFloat = 30
drawColorLayout.itemSize = CGSize(width: drawColorItemWidth, height: drawColorItemWidth)
drawColorLayout.minimumLineSpacing = 15
drawColorLayout.minimumInteritemSpacing = 15
drawColorLayout.scrollDirection = .horizontal
let drawColorTopBottomInset = (drawColViewH - drawColorItemWidth) / 2
drawColorLayout.sectionInset = UIEdgeInsets(top: drawColorTopBottomInset, left: 0, bottom: drawColorTopBottomInset, right: 0)
let drawCV = UICollectionView(frame: .zero, collectionViewLayout: drawColorLayout)
drawCV.backgroundColor = .clear
drawCV.delegate = self
drawCV.dataSource = self
drawCV.isHidden = true
drawCV.showsHorizontalScrollIndicator = false
bottomShadowView.addSubview(drawCV)
ZLDrawColorCell.zl.register(drawCV)
drawColorCollectionView = drawCV
}
if tools.contains(.filter) {
if let applier = currentFilter.applier {
let image = applier(originalImage)
editImage = image
editImageWithoutAdjust = image
filterImages[currentFilter.name] = image
}
let filterLayout = UICollectionViewFlowLayout()
filterLayout.itemSize = CGSize(width: filterColViewH - 20, height: filterColViewH)
filterLayout.minimumLineSpacing = 15
filterLayout.minimumInteritemSpacing = 15
filterLayout.scrollDirection = .horizontal
let filterCV = UICollectionView(frame: .zero, collectionViewLayout: filterLayout)
filterCV.backgroundColor = .clear
filterCV.delegate = self
filterCV.dataSource = self
filterCV.isHidden = true
filterCV.showsHorizontalScrollIndicator = false
bottomShadowView.addSubview(filterCV)
ZLFilterImageCell.zl.register(filterCV)
filterCollectionView = filterCV
}
if tools.contains(.adjust) {
editImage = editImage.zl.adjust(brightness: brightness, contrast: contrast, saturation: saturation) ?? editImage
let adjustLayout = UICollectionViewFlowLayout()
adjustLayout.itemSize = CGSize(width: adjustColViewH, height: adjustColViewH)
adjustLayout.minimumLineSpacing = 10
adjustLayout.minimumInteritemSpacing = 10
adjustLayout.scrollDirection = .horizontal
let adjustCV = UICollectionView(frame: .zero, collectionViewLayout: adjustLayout)
adjustCV.backgroundColor = .clear
adjustCV.delegate = self
adjustCV.dataSource = self
adjustCV.isHidden = true
adjustCV.showsHorizontalScrollIndicator = false
bottomShadowView.addSubview(adjustCV)
ZLAdjustToolCell.zl.register(adjustCV)
adjustCollectionView = adjustCV
adjustSlider = ZLAdjustSlider()
if let selectedAdjustTool = selectedAdjustTool {
changeAdjustTool(selectedAdjustTool)
}
adjustSlider?.beginAdjust = {}
adjustSlider?.valueChanged = { [weak self] value in
self?.adjustValueChanged(value)
}
adjustSlider?.endAdjust = { [weak self] in
self?.endAdjust()
}
adjustSlider?.isHidden = true
view.addSubview(adjustSlider!)
}
bottomShadowView.addSubview(revokeBtn)
if canRedo {
let btn = UIButton(type: .custom)
btn.setImage(.zl.getImage("zl_redo_disable"), for: .disabled)
btn.setImage(.zl.getImage("zl_redo"), for: .normal)
btn.adjustsImageWhenHighlighted = false
btn.isEnabled = false
btn.isHidden = true
btn.addTarget(self, action: #selector(redoBtnClick), for: .touchUpInside)
bottomShadowView.addSubview(btn)
redoBtn = btn
}
view.addSubview(ashbinView)
ashbinView.addSubview(ashbinImgView)
let asbinTipLabel = UILabel(frame: CGRect(x: 0, y: Self.ashbinSize.height - 34, width: Self.ashbinSize.width, height: 34))
asbinTipLabel.font = .zl.font(ofSize: 12)
asbinTipLabel.textAlignment = .center
asbinTipLabel.textColor = .white
asbinTipLabel.text = localLanguageTextValue(.textStickerRemoveTips)
asbinTipLabel.numberOfLines = 2
asbinTipLabel.lineBreakMode = .byCharWrapping
ashbinView.addSubview(asbinTipLabel)
if tools.contains(.mosaic) {
mosaicImage = editImage.zl.mosaicImage()
mosaicImageLayer = CALayer()
mosaicImageLayer?.contents = mosaicImage?.cgImage
imageView.layer.addSublayer(mosaicImageLayer!)
mosaicImageLayerMaskLayer = CAShapeLayer()
mosaicImageLayerMaskLayer?.strokeColor = UIColor.blue.cgColor
mosaicImageLayerMaskLayer?.fillColor = nil
mosaicImageLayerMaskLayer?.lineCap = .round
mosaicImageLayerMaskLayer?.lineJoin = .round
imageView.layer.addSublayer(mosaicImageLayerMaskLayer!)
mosaicImageLayer?.mask = mosaicImageLayerMaskLayer
}
if tools.contains(.imageSticker) {
let imageStickerView = ZLPhotoConfiguration.default().editImageConfiguration.imageStickerContainerView
imageStickerView?.hideBlock = { [weak self] in
self?.setToolView(show: true)
self?.imageStickerContainerIsHidden = true
}
imageStickerView?.selectImageBlock = { [weak self] image in
self?.addImageStickerView(image)
}
}
let tapGes = UITapGestureRecognizer(target: self, action: #selector(tapAction(_:)))
tapGes.delegate = self
view.addGestureRecognizer(tapGes)
view.addGestureRecognizer(panGes)
mainScrollView.panGestureRecognizer.require(toFail: panGes)
stickers.forEach { view in
self.stickersContainer.addSubview(view)
if let tv = view as? ZLTextStickerView {
tv.frame = tv.originFrame
self.configTextSticker(tv)
} else if let iv = view as? ZLImageStickerView {
iv.frame = iv.originFrame
self.configImageSticker(iv)
}
}
}
private func rotationImageView() {
let transform = CGAffineTransform(rotationAngle: angle.zl.toPi)
imageView.transform = transform
drawingImageView.transform = transform
stickersContainer.transform = transform
}
@objc private func cancelBtnClick() {
dismiss(animated: animate) {
self.cancelEditBlock?()
}
}
private func drawBtnClick() {
let isSelected = selectedTool != .draw
if isSelected {
selectedTool = .draw
} else {
selectedTool = nil
}
drawColorCollectionView?.isHidden = !isSelected
revokeBtn.isHidden = !isSelected
revokeBtn.isEnabled = !drawPaths.isEmpty
redoBtn?.isHidden = !isSelected
redoBtn?.isEnabled = drawPaths.count != redoDrawPaths.count
filterCollectionView?.isHidden = true
adjustCollectionView?.isHidden = true
adjustSlider?.isHidden = true
}
private func clipBtnClick() {
let currentEditImage = buildImage()
let vc = ZLClipImageViewController(image: currentEditImage, editRect: editRect, angle: angle, selectRatio: selectRatio)
let rect = mainScrollView.convert(containerView.frame, to: view)
vc.presentAnimateFrame = rect
vc.presentAnimateImage = currentEditImage.zl.clipImage(angle: angle, editRect: editRect, isCircle: selectRatio?.isCircle ?? false)
vc.modalPresentationStyle = .fullScreen
vc.clipDoneBlock = { [weak self] angle, editFrame, selectRatio in
guard let `self` = self else { return }
let oldAngle = self.angle
let oldContainerSize = self.stickersContainer.frame.size
if self.angle != angle {
self.angle = angle
self.rotationImageView()
}
self.editRect = editFrame
self.selectRatio = selectRatio
self.resetContainerViewFrame()
self.reCalculateStickersFrame(oldContainerSize, oldAngle, angle)
}
vc.cancelClipBlock = { [weak self] () in
self?.resetContainerViewFrame()
}
present(vc, animated: false) {
self.mainScrollView.alpha = 0
self.topShadowView.alpha = 0
self.bottomShadowView.alpha = 0
self.adjustSlider?.alpha = 0
}
}
private func imageStickerBtnClick() {
ZLPhotoConfiguration.default().editImageConfiguration.imageStickerContainerView?.show(in: view)
setToolView(show: false)
imageStickerContainerIsHidden = false
}
private func textStickerBtnClick() {
showInputTextVC { [weak self] text, textColor, bgColor in
self?.addTextStickersView(text, textColor: textColor, bgColor: bgColor)
}
}
private func mosaicBtnClick() {
let isSelected = selectedTool != .mosaic
if isSelected {
selectedTool = .mosaic
} else {
selectedTool = nil
}
drawColorCollectionView?.isHidden = true
filterCollectionView?.isHidden = true
adjustCollectionView?.isHidden = true
adjustSlider?.isHidden = true
revokeBtn.isHidden = !isSelected
revokeBtn.isEnabled = !mosaicPaths.isEmpty
redoBtn?.isHidden = !isSelected
redoBtn?.isEnabled = mosaicPaths.count != redoMosaicPaths.count
}
private func filterBtnClick() {
let isSelected = selectedTool != .filter
if isSelected {
selectedTool = .filter
} else {
selectedTool = nil
}
drawColorCollectionView?.isHidden = true
revokeBtn.isHidden = true
filterCollectionView?.isHidden = !isSelected
adjustCollectionView?.isHidden = true
adjustSlider?.isHidden = true
}
private func adjustBtnClick() {
let isSelected = selectedTool != .adjust
if isSelected {
selectedTool = .adjust
} else {
selectedTool = nil
}
drawColorCollectionView?.isHidden = true
revokeBtn.isHidden = true
filterCollectionView?.isHidden = true
adjustCollectionView?.isHidden = !isSelected
adjustSlider?.isHidden = !isSelected
generateAdjustImageRef()
}
private func changeAdjustTool(_ tool: ZLEditImageConfiguration.AdjustTool) {
selectedAdjustTool = tool
switch tool {
case .brightness:
adjustSlider?.value = brightness
case .contrast:
adjustSlider?.value = contrast
case .saturation:
adjustSlider?.value = saturation
}
generateAdjustImageRef()
}
@objc private func doneBtnClick() {
var textStickers: [(ZLTextStickerState, Int)] = []
var imageStickers: [(ZLImageStickerState, Int)] = []
for (index, view) in stickersContainer.subviews.enumerated() {
if let ts = view as? ZLTextStickerView, let _ = ts.label.text {
textStickers.append((ts.state, index))
} else if let ts = view as? ZLImageStickerView {
imageStickers.append((ts.state, index))
}
}
var hasEdit = true
if drawPaths.isEmpty, editRect.size == imageSize, angle == 0, mosaicPaths.isEmpty, imageStickers.isEmpty, textStickers.isEmpty, currentFilter.applier == nil, brightness == 0, contrast == 0, saturation == 0 {
hasEdit = false
}
var resImage = originalImage
var editModel: ZLEditImageModel?
if hasEdit {
let hud = ZLProgressHUD(style: ZLPhotoUIConfiguration.default().hudStyle)
hud.show()
resImage = buildImage()
resImage = resImage.zl.clipImage(angle: angle, editRect: editRect, isCircle: selectRatio?.isCircle ?? false) ?? resImage
editModel = ZLEditImageModel(
drawPaths: drawPaths,
mosaicPaths: mosaicPaths,
editRect: editRect,
angle: angle,
brightness: brightness,
contrast: contrast,
saturation: saturation,
selectRatio: selectRatio,
selectFilter: currentFilter,
textStickers: textStickers,
imageStickers: imageStickers
)
hud.hide()
}
dismiss(animated: animate) {
self.editFinishBlock?(resImage, editModel)
}
}
@objc private func revokeBtnClick() {
if selectedTool == .draw {
guard !drawPaths.isEmpty else {
return
}
drawPaths.removeLast()
revokeBtn.isEnabled = !drawPaths.isEmpty
redoBtn?.isEnabled = drawPaths.count != redoDrawPaths.count
drawLine()
} else if selectedTool == .mosaic {
guard !mosaicPaths.isEmpty else {
return
}
mosaicPaths.removeLast()
revokeBtn.isEnabled = !mosaicPaths.isEmpty
redoBtn?.isEnabled = mosaicPaths.count != redoMosaicPaths.count
generateNewMosaicImage()
}
}
@objc private func redoBtnClick() {
if selectedTool == .draw {
guard drawPaths.count < redoDrawPaths.count else {
return
}
let path = redoDrawPaths[drawPaths.count]
drawPaths.append(path)
revokeBtn.isEnabled = !drawPaths.isEmpty
redoBtn?.isEnabled = drawPaths.count != redoDrawPaths.count
drawLine()
} else if selectedTool == .mosaic {
guard mosaicPaths.count < redoMosaicPaths.count else {
return
}
let path = redoMosaicPaths[mosaicPaths.count]
mosaicPaths.append(path)
revokeBtn.isEnabled = !mosaicPaths.isEmpty
redoBtn?.isEnabled = mosaicPaths.count != redoMosaicPaths.count
generateNewMosaicImage()
}
}
@objc private func tapAction(_ tap: UITapGestureRecognizer) {
if bottomShadowView.alpha == 1 {
setToolView(show: false)
} else {
setToolView(show: true)
}
}
@objc private func drawAction(_ pan: UIPanGestureRecognizer) {
if selectedTool == .draw {
let point = pan.location(in: drawingImageView)
if pan.state == .began {
setToolView(show: false)
let originalRatio = min(mainScrollView.frame.width / originalImage.size.width, mainScrollView.frame.height / originalImage.size.height)
let ratio = min(mainScrollView.frame.width / editRect.width, mainScrollView.frame.height / editRect.height)
let scale = ratio / originalRatio
// 缩放到最初的size
var size = drawingImageView.frame.size
size.width /= scale
size.height /= scale
if angle == -90 || angle == -270 {
swap(&size.width, &size.height)
}
var toImageScale = ZLEditImageViewController.maxDrawLineImageWidth / size.width
if editImage.size.width / editImage.size.height > 1 {
toImageScale = ZLEditImageViewController.maxDrawLineImageWidth / size.height
}
let path = ZLDrawPath(pathColor: currentDrawColor, pathWidth: drawLineWidth / mainScrollView.zoomScale, ratio: ratio / originalRatio / toImageScale, startPoint: point)
drawPaths.append(path)
redoDrawPaths = drawPaths
} else if pan.state == .changed {
let path = drawPaths.last
path?.addLine(to: point)
drawLine()
} else if pan.state == .cancelled || pan.state == .ended {
setToolView(show: true, delay: 0.5)
revokeBtn.isEnabled = !drawPaths.isEmpty
redoBtn?.isEnabled = false
}
} else if selectedTool == .mosaic {
let point = pan.location(in: imageView)
if pan.state == .began {
setToolView(show: false)
var actualSize = editRect.size
if angle == -90 || angle == -270 {
swap(&actualSize.width, &actualSize.height)
}
let ratio = min(mainScrollView.frame.width / editRect.width, mainScrollView.frame.height / editRect.height)
let pathW = mosaicLineWidth / mainScrollView.zoomScale
let path = ZLMosaicPath(pathWidth: pathW, ratio: ratio, startPoint: point)
mosaicImageLayerMaskLayer?.lineWidth = pathW
mosaicImageLayerMaskLayer?.path = path.path.cgPath
mosaicPaths.append(path)
redoMosaicPaths = mosaicPaths
} else if pan.state == .changed {
let path = mosaicPaths.last
path?.addLine(to: point)
mosaicImageLayerMaskLayer?.path = path?.path.cgPath
} else if pan.state == .cancelled || pan.state == .ended {
setToolView(show: true, delay: 0.5)
revokeBtn.isEnabled = !mosaicPaths.isEmpty
redoBtn?.isEnabled = false
generateNewMosaicImage()
}
}
}
// 生成一个没有调整参数前的图片
private func generateAdjustImageRef() {
editImageAdjustRef = generateNewMosaicImage(inputImage: editImageWithoutAdjust, inputMosaicImage: editImageWithoutAdjust.zl.mosaicImage())
}
private func adjustValueChanged(_ value: Float) {
guard let selectedAdjustTool = selectedAdjustTool, let editImageAdjustRef = editImageAdjustRef else {
return
}
var resultImage: UIImage?
switch selectedAdjustTool {
case .brightness:
if brightness == value {
return
}
brightness = value
resultImage = editImageAdjustRef.zl.adjust(brightness: value, contrast: contrast, saturation: saturation)
case .contrast:
if contrast == value {
return
}
contrast = value
resultImage = editImageAdjustRef.zl.adjust(brightness: brightness, contrast: value, saturation: saturation)
case .saturation:
if saturation == value {
return
}
saturation = value
resultImage = editImageAdjustRef.zl.adjust(brightness: brightness, contrast: contrast, saturation: value)
}
guard let resultImage = resultImage else {
return
}
editImage = resultImage
imageView.image = editImage
}
private func endAdjust() {
if tools.contains(.mosaic) {
generateNewMosaicImageLayer()
if !mosaicPaths.isEmpty {
generateNewMosaicImage()
}
}
}
private func setToolView(show: Bool, delay: TimeInterval? = nil) {
cleanToolViewStateTimer()
if let delay = delay {
toolViewStateTimer = Timer.scheduledTimer(timeInterval: delay, target: ZLWeakProxy(target: self), selector: #selector(setToolViewShow_timerFunc(show:)), userInfo: ["show": show], repeats: false)
RunLoop.current.add(toolViewStateTimer!, forMode: .common)
} else {
setToolViewShow_timerFunc(show: show)
}
}
@objc private func setToolViewShow_timerFunc(show: Bool) {
var flag = show
if let toolViewStateTimer = toolViewStateTimer {
let userInfo = toolViewStateTimer.userInfo as? [String: Any]
flag = userInfo?["show"] as? Bool ?? true
cleanToolViewStateTimer()
}
topShadowView.layer.removeAllAnimations()
bottomShadowView.layer.removeAllAnimations()
adjustSlider?.layer.removeAllAnimations()
if flag {
UIView.animate(withDuration: 0.25) {
self.topShadowView.alpha = 1
self.bottomShadowView.alpha = 1
self.adjustSlider?.alpha = 1
}
} else {
UIView.animate(withDuration: 0.25) {
self.topShadowView.alpha = 0
self.bottomShadowView.alpha = 0
self.adjustSlider?.alpha = 0
}
}
}
private func cleanToolViewStateTimer() {
toolViewStateTimer?.invalidate()
toolViewStateTimer = nil
}
private func showInputTextVC(_ text: String? = nil, textColor: UIColor? = nil, bgColor: UIColor? = nil, completion: @escaping ((String, UIColor, UIColor) -> Void)) {
// Calculate image displayed frame on the screen.
var r = mainScrollView.convert(view.frame, to: containerView)
r.origin.x += mainScrollView.contentOffset.x / mainScrollView.zoomScale
r.origin.y += mainScrollView.contentOffset.y / mainScrollView.zoomScale
let scale = imageSize.width / imageView.frame.width
r.origin.x *= scale
r.origin.y *= scale
r.size.width *= scale
r.size.height *= scale
let isCircle = selectRatio?.isCircle ?? false
let bgImage = buildImage()
.zl.clipImage(angle: angle, editRect: editRect, isCircle: isCircle)?
.zl.clipImage(angle: 0, editRect: r, isCircle: isCircle)
let vc = ZLInputTextViewController(image: bgImage, text: text, textColor: textColor, bgColor: bgColor)
vc.endInput = { text, textColor, bgColor in
completion(text, textColor, bgColor)
}
vc.modalPresentationStyle = .fullScreen
showDetailViewController(vc, sender: nil)
}
private func getStickerOriginFrame(_ size: CGSize) -> CGRect {
let scale = mainScrollView.zoomScale
// Calculate the display rect of container view.
let x = (mainScrollView.contentOffset.x - containerView.frame.minX) / scale
let y = (mainScrollView.contentOffset.y - containerView.frame.minY) / scale
let w = view.frame.width / scale
let h = view.frame.height / scale
// Convert to text stickers container view.
let r = containerView.convert(CGRect(x: x, y: y, width: w, height: h), to: stickersContainer)
let originFrame = CGRect(x: r.minX + (r.width - size.width) / 2, y: r.minY + (r.height - size.height) / 2, width: size.width, height: size.height)
return originFrame
}
/// Add image sticker
private func addImageStickerView(_ image: UIImage) {
let scale = mainScrollView.zoomScale
let size = ZLImageStickerView.calculateSize(image: image, width: view.frame.width)
let originFrame = getStickerOriginFrame(size)
let imageSticker = ZLImageStickerView(image: image, originScale: 1 / scale, originAngle: -angle, originFrame: originFrame)
stickersContainer.addSubview(imageSticker)
imageSticker.frame = originFrame
view.layoutIfNeeded()
configImageSticker(imageSticker)
}
/// Add text sticker
private func addTextStickersView(_ text: String, textColor: UIColor, bgColor: UIColor) {
guard !text.isEmpty else { return }
let scale = mainScrollView.zoomScale
let size = ZLTextStickerView.calculateSize(text: text, width: view.frame.width)
let originFrame = getStickerOriginFrame(size)
let textSticker = ZLTextStickerView(text: text, textColor: textColor, bgColor: bgColor, originScale: 1 / scale, originAngle: -angle, originFrame: originFrame)
stickersContainer.addSubview(textSticker)
textSticker.frame = originFrame
configTextSticker(textSticker)
}
private func configTextSticker(_ textSticker: ZLTextStickerView) {
textSticker.delegate = self
mainScrollView.pinchGestureRecognizer?.require(toFail: textSticker.pinchGes)
mainScrollView.panGestureRecognizer.require(toFail: textSticker.panGes)
panGes.require(toFail: textSticker.panGes)
}
private func configImageSticker(_ imageSticker: ZLImageStickerView) {
imageSticker.delegate = self
mainScrollView.pinchGestureRecognizer?.require(toFail: imageSticker.pinchGes)
mainScrollView.panGestureRecognizer.require(toFail: imageSticker.panGes)
panGes.require(toFail: imageSticker.panGes)
}
private func reCalculateStickersFrame(_ oldSize: CGSize, _ oldAngle: CGFloat, _ newAngle: CGFloat) {
let currSize = stickersContainer.frame.size
let scale: CGFloat
if Int(newAngle - oldAngle) % 180 == 0 {
scale = currSize.width / oldSize.width
} else {
scale = currSize.height / oldSize.width
}
stickersContainer.subviews.forEach { view in
(view as? ZLStickerViewAdditional)?.addScale(scale)
}
}
private func drawLine() {
let originalRatio = min(mainScrollView.frame.width / originalImage.size.width, mainScrollView.frame.height / originalImage.size.height)
let ratio = min(mainScrollView.frame.width / editRect.width, mainScrollView.frame.height / editRect.height)
let scale = ratio / originalRatio
// 缩放到最初的size
var size = drawingImageView.frame.size
size.width /= scale
size.height /= scale
if angle == -90 || angle == -270 {
swap(&size.width, &size.height)
}
var toImageScale = ZLEditImageViewController.maxDrawLineImageWidth / size.width
if editImage.size.width / editImage.size.height > 1 {
toImageScale = ZLEditImageViewController.maxDrawLineImageWidth / size.height
}
size.width *= toImageScale
size.height *= toImageScale
UIGraphicsBeginImageContextWithOptions(size, false, editImage.scale)
let context = UIGraphicsGetCurrentContext()
// 去掉锯齿
context?.setAllowsAntialiasing(true)
context?.setShouldAntialias(true)
for path in drawPaths {
path.drawPath()
}
drawingImageView.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
private func generateNewMosaicImageLayer() {
mosaicImage = editImage.zl.mosaicImage()
mosaicImageLayer?.removeFromSuperlayer()
mosaicImageLayer = CALayer()
mosaicImageLayer?.frame = imageView.bounds
mosaicImageLayer?.contents = mosaicImage?.cgImage
imageView.layer.insertSublayer(mosaicImageLayer!, below: mosaicImageLayerMaskLayer)
mosaicImageLayer?.mask = mosaicImageLayerMaskLayer
}
/// 传入inputImage 和 inputMosaicImage则代表仅想要获取新生成的mosaic图片
@discardableResult
private func generateNewMosaicImage(inputImage: UIImage? = nil, inputMosaicImage: UIImage? = nil) -> UIImage? {
let renderRect = CGRect(origin: .zero, size: originalImage.size)
UIGraphicsBeginImageContextWithOptions(originalImage.size, false, originalImage.scale)
if inputImage != nil {
inputImage?.draw(in: renderRect)
} else {
var drawImage: UIImage?
if tools.contains(.filter), let image = filterImages[currentFilter.name] {
drawImage = image
} else {
drawImage = originalImage
}
if tools.contains(.adjust), brightness != 0 || contrast != 0 || saturation != 0 {
drawImage = drawImage?.zl.adjust(brightness: brightness, contrast: contrast, saturation: saturation)
}
drawImage?.draw(in: renderRect)
}
let context = UIGraphicsGetCurrentContext()
mosaicPaths.forEach { path in
context?.move(to: path.startPoint)
path.linePoints.forEach { point in
context?.addLine(to: point)
}
context?.setLineWidth(path.path.lineWidth / path.ratio)
context?.setLineCap(.round)
context?.setLineJoin(.round)
context?.setBlendMode(.clear)
context?.strokePath()
}
var midImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let midCgImage = midImage?.cgImage else {
return nil
}
midImage = UIImage(cgImage: midCgImage, scale: editImage.scale, orientation: .up)
UIGraphicsBeginImageContextWithOptions(originalImage.size, false, originalImage.scale)
// 由于生成的mosaic图片可能在边缘区域出现空白部分,导致合成后会有黑边,所以在最下面先画一张原图
originalImage.draw(in: renderRect)
(inputMosaicImage ?? mosaicImage)?.draw(in: renderRect)
midImage?.draw(in: renderRect)
let temp = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let cgi = temp?.cgImage else {
return nil
}
let image = UIImage(cgImage: cgi, scale: editImage.scale, orientation: .up)
if inputImage != nil {
return image
}
editImage = image
imageView.image = image
mosaicImageLayerMaskLayer?.path = nil
return image
}
private func buildImage() -> UIImage {
UIGraphicsBeginImageContextWithOptions(editImage.size, false, editImage.scale)
editImage.draw(at: .zero)
drawingImageView.image?.draw(in: CGRect(origin: .zero, size: originalImage.size))
if !stickersContainer.subviews.isEmpty, let context = UIGraphicsGetCurrentContext() {
let scale = imageSize.width / stickersContainer.frame.width
stickersContainer.subviews.forEach { view in
(view as? ZLStickerViewAdditional)?.resetState()
}
context.concatenate(CGAffineTransform(scaleX: scale, y: scale))
stickersContainer.layer.render(in: context)
context.concatenate(CGAffineTransform(scaleX: 1 / scale, y: 1 / scale))
}
let temp = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let cgi = temp?.cgImage else {
return editImage
}
return UIImage(cgImage: cgi, scale: editImage.scale, orientation: .up)
}
func finishClipDismissAnimate() {
mainScrollView.alpha = 1
UIView.animate(withDuration: 0.1) {
self.topShadowView.alpha = 1
self.bottomShadowView.alpha = 1
self.adjustSlider?.alpha = 1
}
}
}
// MARK: UIGestureRecognizerDelegate
extension ZLEditImageViewController: UIGestureRecognizerDelegate {
public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
guard imageStickerContainerIsHidden else {
return false
}
if gestureRecognizer is UITapGestureRecognizer {
if bottomShadowView.alpha == 1 {
let p = gestureRecognizer.location(in: view)
return !bottomShadowView.frame.contains(p)
} else {
return true
}
} else if gestureRecognizer is UIPanGestureRecognizer {
guard let selectedTool = selectedTool else {
return false
}
return (selectedTool == .draw || selectedTool == .mosaic) && !isScrolling
}
return true
}
}
// MARK: scroll view delegate
extension ZLEditImageViewController: UIScrollViewDelegate {
public func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return containerView
}
public func scrollViewDidZoom(_ scrollView: UIScrollView) {
let offsetX = (scrollView.frame.width > scrollView.contentSize.width) ? (scrollView.frame.width - scrollView.contentSize.width) * 0.5 : 0
let offsetY = (scrollView.frame.height > scrollView.contentSize.height) ? (scrollView.frame.height - scrollView.contentSize.height) * 0.5 : 0
containerView.center = CGPoint(x: scrollView.contentSize.width * 0.5 + offsetX, y: scrollView.contentSize.height * 0.5 + offsetY)
}
public func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
isScrolling = false
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
guard scrollView == mainScrollView else {
return
}
isScrolling = true
}
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
guard scrollView == mainScrollView else {
return
}
isScrolling = decelerate
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
guard scrollView == mainScrollView else {
return
}
isScrolling = false
}
public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
guard scrollView == mainScrollView else {
return
}
isScrolling = false
}
}
// MARK: collection view data source & delegate
extension ZLEditImageViewController: UICollectionViewDataSource, UICollectionViewDelegate {
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView == editToolCollectionView {
return tools.count
} else if collectionView == drawColorCollectionView {
return drawColors.count
} else if collectionView == filterCollectionView {
return thumbnailFilterImages.count
} else {
return adjustTools.count
}
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == editToolCollectionView {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ZLEditToolCell.zl.identifier, for: indexPath) as! ZLEditToolCell
let toolType = tools[indexPath.row]
cell.icon.isHighlighted = false
cell.toolType = toolType
cell.icon.isHighlighted = toolType == selectedTool
return cell
} else if collectionView == drawColorCollectionView {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ZLDrawColorCell.zl.identifier, for: indexPath) as! ZLDrawColorCell
let c = drawColors[indexPath.row]
cell.color = c
if c == currentDrawColor {
cell.bgWhiteView.layer.transform = CATransform3DMakeScale(1.2, 1.2, 1)
} else {
cell.bgWhiteView.layer.transform = CATransform3DIdentity
}
return cell
} else if collectionView == filterCollectionView {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ZLFilterImageCell.zl.identifier, for: indexPath) as! ZLFilterImageCell
let image = thumbnailFilterImages[indexPath.row]
let filter = ZLPhotoConfiguration.default().editImageConfiguration.filters[indexPath.row]
cell.nameLabel.text = filter.name
cell.imageView.image = image
if currentFilter === filter {
cell.nameLabel.textColor = .zl.imageEditorToolTitleTintColor
} else {
cell.nameLabel.textColor = .zl.imageEditorToolTitleNormalColor
}
return cell
} else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ZLAdjustToolCell.zl.identifier, for: indexPath) as! ZLAdjustToolCell
let tool = adjustTools[indexPath.row]
cell.imageView.isHighlighted = false
cell.adjustTool = tool
let isSelected = tool == selectedAdjustTool
cell.imageView.isHighlighted = isSelected
if isSelected {
cell.nameLabel.textColor = .zl.imageEditorToolTitleTintColor
} else {
cell.nameLabel.textColor = .zl.imageEditorToolTitleNormalColor
}
return cell
}
}
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if collectionView == editToolCollectionView {
let toolType = tools[indexPath.row]
switch toolType {
case .draw:
drawBtnClick()
case .clip:
clipBtnClick()
case .imageSticker:
imageStickerBtnClick()
case .textSticker:
textStickerBtnClick()
case .mosaic:
mosaicBtnClick()
case .filter:
filterBtnClick()
case .adjust:
adjustBtnClick()
}
} else if collectionView == drawColorCollectionView {
currentDrawColor = drawColors[indexPath.row]
} else if collectionView == filterCollectionView {
currentFilter = ZLPhotoConfiguration.default().editImageConfiguration.filters[indexPath.row]
func adjustImage(_ image: UIImage) -> UIImage {
guard tools.contains(.adjust), brightness != 0 || contrast != 0 || saturation != 0 else {
return image
}
return image.zl.adjust(brightness: brightness, contrast: contrast, saturation: saturation) ?? image
}
if let image = filterImages[currentFilter.name] {
editImage = adjustImage(image)
editImageWithoutAdjust = image
} else {
let image = currentFilter.applier?(originalImage) ?? originalImage
editImage = adjustImage(image)
editImageWithoutAdjust = image
filterImages[currentFilter.name] = image
}
if tools.contains(.mosaic) {
generateNewMosaicImageLayer()
if mosaicPaths.isEmpty {
imageView.image = editImage
} else {
generateNewMosaicImage()
}
} else {
imageView.image = editImage
}
} else {
let tool = adjustTools[indexPath.row]
if tool != selectedAdjustTool {
changeAdjustTool(tool)
}
}
collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
collectionView.reloadData()
}
}
// MARK: ZLTextStickerViewDelegate
extension ZLEditImageViewController: ZLTextStickerViewDelegate {
func stickerBeginOperation(_ sticker: UIView) {
setToolView(show: false)
ashbinView.layer.removeAllAnimations()
ashbinView.isHidden = false
var frame = ashbinView.frame
let diff = view.frame.height - frame.minY
frame.origin.y += diff
ashbinView.frame = frame
frame.origin.y -= diff
UIView.animate(withDuration: 0.25) {
self.ashbinView.frame = frame
}
stickersContainer.subviews.forEach { view in
if view !== sticker {
(view as? ZLStickerViewAdditional)?.resetState()
(view as? ZLStickerViewAdditional)?.gesIsEnabled = false
}
}
}
func stickerOnOperation(_ sticker: UIView, panGes: UIPanGestureRecognizer) {
let point = panGes.location(in: view)
if ashbinView.frame.contains(point) {
ashbinView.backgroundColor = .zl.trashCanBackgroundTintColor
ashbinImgView.isHighlighted = true
if sticker.alpha == 1 {
sticker.layer.removeAllAnimations()
UIView.animate(withDuration: 0.25) {
sticker.alpha = 0.5
}
}
} else {
ashbinView.backgroundColor = .zl.trashCanBackgroundNormalColor
ashbinImgView.isHighlighted = false
if sticker.alpha != 1 {
sticker.layer.removeAllAnimations()
UIView.animate(withDuration: 0.25) {
sticker.alpha = 1
}
}
}
}
func stickerEndOperation(_ sticker: UIView, panGes: UIPanGestureRecognizer) {
setToolView(show: true)
ashbinView.layer.removeAllAnimations()
ashbinView.isHidden = true
let point = panGes.location(in: view)
if ashbinView.frame.contains(point) {
(sticker as? ZLStickerViewAdditional)?.moveToAshbin()
}
stickersContainer.subviews.forEach { view in
(view as? ZLStickerViewAdditional)?.gesIsEnabled = true
}
}
func stickerDidTap(_ sticker: UIView) {
stickersContainer.subviews.forEach { view in
if view !== sticker {
(view as? ZLStickerViewAdditional)?.resetState()
}
}
}
func sticker(_ textSticker: ZLTextStickerView, editText text: String) {
showInputTextVC(text, textColor: textSticker.textColor, bgColor: textSticker.bgColor) { [weak self] text, textColor, bgColor in
guard let `self` = self else { return }
if text.isEmpty {
textSticker.moveToAshbin()
} else {
textSticker.startTimer()
guard textSticker.text != text || textSticker.textColor != textColor || textSticker.bgColor != bgColor else {
return
}
textSticker.text = text
textSticker.textColor = textColor
textSticker.bgColor = bgColor
let newSize = ZLTextStickerView.calculateSize(text: text, width: self.view.frame.width)
textSticker.changeSize(to: newSize)
}
}
}
}
// MARK: 涂鸦path
public class ZLDrawPath: NSObject {
private let pathColor: UIColor
private let path: UIBezierPath
private let ratio: CGFloat
private let shapeLayer: CAShapeLayer
init(pathColor: UIColor, pathWidth: CGFloat, ratio: CGFloat, startPoint: CGPoint) {
self.pathColor = pathColor
path = UIBezierPath()
path.lineWidth = pathWidth / ratio
path.lineCapStyle = .round
path.lineJoinStyle = .round
path.move(to: CGPoint(x: startPoint.x / ratio, y: startPoint.y / ratio))
shapeLayer = CAShapeLayer()
shapeLayer.lineCap = .round
shapeLayer.lineJoin = .round
shapeLayer.lineWidth = pathWidth / ratio
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = pathColor.cgColor
shapeLayer.path = path.cgPath
self.ratio = ratio
super.init()
}
func addLine(to point: CGPoint) {
path.addLine(to: CGPoint(x: point.x / ratio, y: point.y / ratio))
shapeLayer.path = path.cgPath
}
func drawPath() {
pathColor.set()
path.stroke()
}
}
// MARK: 马赛克path
public class ZLMosaicPath: NSObject {
let path: UIBezierPath
let ratio: CGFloat
let startPoint: CGPoint
var linePoints: [CGPoint] = []
init(pathWidth: CGFloat, ratio: CGFloat, startPoint: CGPoint) {
path = UIBezierPath()
path.lineWidth = pathWidth
path.lineCapStyle = .round
path.lineJoinStyle = .round
path.move(to: startPoint)
self.ratio = ratio
self.startPoint = CGPoint(x: startPoint.x / ratio, y: startPoint.y / ratio)
super.init()
}
func addLine(to point: CGPoint) {
path.addLine(to: point)
linePoints.append(CGPoint(x: point.x / ratio, y: point.y / ratio))
}
}
| mit | e9a7f7b151c32dbf21978a053aae64f9 | 37.622501 | 215 | 0.610221 | 5.010224 | false | false | false | false |
MrBendel/OFWNutella | OFWNutella/OFWNutella/src/AppDelegate.swift | 1 | 6232 | //
// AppDelegate.swift
// OFWNutella
//
// Created by apoes on 6/9/16.
// Copyright © 2016 apoes. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var rootViewController: RootViewController?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
application.statusBarHidden = true
window = UIWindow(frame: UIScreenBounds)
if let w = window {
rootViewController = RootViewController()
w.rootViewController = rootViewController;
w.makeKeyAndVisible()
}
// set the managed context
// controller.managedObjectContext = self.managedObjectContext
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 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:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.andythedesigner.www.OFWNutella" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("OFWNutella", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| apache-2.0 | 75e5ee086147283e641df6c9cbbfb76e | 50.925 | 289 | 0.740652 | 5.6697 | false | false | false | false |
baottran/nSURE | nSURE/PFEditNameController.swift | 1 | 2253 | //
// PFEditNameController.swift
// nSURE
//
// Created by Bao Tran on 6/30/15.
// Copyright (c) 2015 Sprout Designs. All rights reserved.
//
import UIKit
protocol PFEditNameControllerDelegate: class {
func pfEditNameController(firstName: String, lastName: String)
}
class PFEditNameController: UITableViewController {
@IBOutlet weak var firstNameField: UITextField!
@IBOutlet weak var lastNameField: UITextField!
weak var customer: PFObject?
weak var delelgate: PFEditNameControllerDelegate?
override func viewDidAppear(animated: Bool) {
if let currentCustomer = customer {
let firstName = currentCustomer["firstName"] as! String
let lastName = currentCustomer["lastName"] as! String
firstNameField.text = firstName
lastNameField.text = lastName
}
}
@IBAction func save(){
if allFieldsComplted() == true {
if let currentCustomer = customer {
currentCustomer["firstName"] = firstNameField.text
currentCustomer["lastName"] = lastNameField.text
currentCustomer.saveInBackgroundWithBlock{ success, error in
if (success) {
// self.delelgate?.pfEditNameController(self.firstNameField.text, lastName: self.lastNameField.text)
self.navigationController?.popViewControllerAnimated(true)
} else {
print("couldn't save customer name", terminator: "")
}
}
}
} else {
presentAlert()
}
}
func allFieldsComplted() -> Bool{
if firstNameField.text == "" || lastNameField.text == "" {
return false
} else {
return true
}
}
func presentAlert(){
let alertController = UIAlertController(title: "Error", message: "Please complete all fields", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
}
| mit | 5fbcd84a57ac20ca6f592e6dcb68d64f | 32.132353 | 148 | 0.611185 | 5.120455 | false | false | false | false |
sjrmanning/Birdsong | Source/Socket.swift | 1 | 6318 | //
// Socket.swift
// Pods
//
// Created by Simon Manning on 23/06/2016.
//
//
import Foundation
import Starscream
public final class Socket {
// MARK: - Convenience aliases
public typealias Payload = [String: Any]
// MARK: - Properties
fileprivate var socket: WebSocket
public var enableLogging = true
public var onConnect: (() -> ())?
public var onDisconnect: ((Error?) -> ())?
fileprivate(set) public var channels: [String: Channel] = [:]
fileprivate static let HeartbeatInterval = Int64(30 * NSEC_PER_SEC)
fileprivate static let HeartbeatPrefix = "hb-"
fileprivate var heartbeatQueue: DispatchQueue
fileprivate var awaitingResponses = [String: Push]()
public var isConnected: Bool {
return socket.isConnected
}
// MARK: - Initialisation
public init(url: URL, params: [String: String]? = nil) {
heartbeatQueue = DispatchQueue(label: "com.ecksd.birdsong.hbqueue", attributes: [])
socket = WebSocket(url: buildURL(url, params: params))
socket.delegate = self
}
public convenience init(url: String, params: [String: String]? = nil) {
if let parsedURL = URL(string: url) {
self.init(url: parsedURL, params: params)
}
else {
print("[Birdsong] Invalid URL in init. Defaulting to localhost URL.")
self.init()
}
}
public convenience init(prot: String = "http", host: String = "localhost", port: Int = 4000,
path: String = "socket", transport: String = "websocket",
params: [String: String]? = nil, selfSignedSSL: Bool = false) {
let url = "\(prot)://\(host):\(port)/\(path)/\(transport)"
self.init(url: url, params: params)
}
// MARK: - Connection
public func connect() {
if socket.isConnected {
return
}
log("Connecting to: \(socket.currentURL)")
socket.connect()
}
public func disconnect() {
if !socket.isConnected {
return
}
log("Disconnecting from: \(socket.currentURL)")
socket.disconnect()
}
// MARK: - Channels
public func channel(_ topic: String, payload: Payload = [:]) -> Channel {
let channel = Channel(socket: self, topic: topic, params: payload)
channels[topic] = channel
return channel
}
public func remove(_ channel: Channel) {
channel.leave()?.receive("ok") { [weak self] response in
self?.channels.removeValue(forKey: channel.topic)
}
}
// MARK: - Heartbeat
func sendHeartbeat() {
guard socket.isConnected else {
return
}
let ref = Socket.HeartbeatPrefix + UUID().uuidString
_ = send(Push(Event.Heartbeat, topic: "phoenix", payload: [:], ref: ref))
queueHeartbeat()
}
func queueHeartbeat() {
let time = DispatchTime.now() + Double(Socket.HeartbeatInterval) / Double(NSEC_PER_SEC)
heartbeatQueue.asyncAfter(deadline: time) {
self.sendHeartbeat()
}
}
// MARK: - Sending data
func send(_ event: String, topic: String, payload: Payload) -> Push {
let push = Push(event, topic: topic, payload: payload)
return send(push)
}
func send(_ message: Push) -> Push {
if !socket.isConnected {
message.handleNotConnected()
return message
}
do {
let data = try message.toJson()
log("Sending: \(message.payload)")
if let ref = message.ref {
awaitingResponses[ref] = message
socket.write(data: data, completion: nil)
}
} catch let error as NSError {
log("Failed to send message: \(error)")
message.handleParseError()
}
return message
}
// MARK: - Event constants
struct Event {
static let Heartbeat = "heartbeat"
static let Join = "phx_join"
static let Leave = "phx_leave"
static let Reply = "phx_reply"
static let Error = "phx_error"
static let Close = "phx_close"
}
}
// MARK: - WebSocketDelegate
extension Socket: WebSocketDelegate {
public func websocketDidConnect(socket: WebSocketClient) {
log("Connected to: \(self.socket.currentURL)")
onConnect?()
queueHeartbeat()
}
public func websocketDidDisconnect(socket: WebSocketClient, error: Error?) {
log("Disconnected from: \(self.socket.currentURL)")
onDisconnect?(error)
// Reset state.
awaitingResponses.removeAll()
channels.removeAll()
}
public func websocketDidReceiveMessage(socket: WebSocketClient, text: String) {
if let data = text.data(using: String.Encoding.utf8),
let response = Response(data: data) {
defer {
awaitingResponses.removeValue(forKey: response.ref)
}
log("Received message: \(response.payload)")
if let push = awaitingResponses[response.ref] {
push.handleResponse(response)
}
channels[response.topic]?.received(response)
} else {
fatalError("Couldn't parse response: \(text)")
}
}
public func websocketDidReceiveData(socket: WebSocketClient, data: Data) {
log("Received data: \(data)")
}
}
// MARK: - Logging
extension Socket {
fileprivate func log(_ message: String) {
if enableLogging {
print("[Birdsong]: \(message)")
}
}
}
// MARK: - Private URL helpers
private func buildURL(_ url: URL, params: [String: String]?) -> URL {
guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false),
let params = params else {
return url
}
var queryItems = [URLQueryItem]()
params.forEach({
queryItems.append(URLQueryItem(name: $0, value: $1))
})
components.queryItems = queryItems
guard let url = components.url else { fatalError("Problem with the URL") }
return url
}
| mit | 8fd9fd171d3ebdc50156068a1d1e6de3 | 27.205357 | 96 | 0.570434 | 4.669623 | false | false | false | false |
CoderLiLe/Swift | 字符串构造/main.swift | 1 | 2609 | //
// main.swift
// 字符串构造
//
// Created by LiLe on 15/2/28.
// Copyright (c) 2015年 LiLe. All rights reserved.
//
import Foundation
/*
计算字符串长度:
C:
char *stringValue = "abc李";
printf("%tu", strlen(stringValue));
打印结果6
OC:
NSString *stringValue = @"abc李";
NSLog(@"%tu", stringValue.length);
打印结果4, 以UTF16计算
*/
var stringValue = "abc李"
print(stringValue.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
// 打印结果6, 和C语言一样计算字节数
/*
字符串拼接
C:
char str1[] = "abc";
char *str2 = "bcd";
char *str = strcat(str1, str2);
OC:
NSMutableString *str1 = [NSMutableString stringWithString:@"abc"];
NSString *str2 = @"bcd";
[str1 appendString:str2];
NSLog(@"%@", str1);
*/
var str1 = "abc";
var str2 = "lnj";
var str = str1 + str2;
print(str)
/*
格式化字符串
C: 相当麻烦, 指针, 下标等方式
OC:
NSInteger index = 1;
NSString *str1 = [NSMutableString stringWithFormat:@"http://ios.LiLe.cn/pic/%tu.png", index];
NSLog(@"%@", str1);
*/
var index = 1
var str3 = "http://www.520it.com/pic/\(index).png"
print(str3)
/*
字符串比较:
OC:
NSString *str1 = @"abc";
NSString *str2 = @"abc";
if ([str1 compare:str2] == NSOrderedSame)
{
NSLog(@"相等");
}else
{
NSLog(@"不相等");
}
if ([str1 isEqualToString:str2])
{
NSLog(@"相等");
}else
{
NSLog(@"不相等");
}
Swift:(== / != / >= / <=), 和C语言的strcmp一样是逐个比较
*/
var str4 = "abc";
var str5 = "abc";
if str4 == str5
{
print("相等");
}else
{
print("不相等");
}
var str6 = "abd";
var str7 = "abc";
if str6 >= str7
{
print("大于等于");
}else
{
print("不大于等于");
}
/*
判断前后缀
OC:
NSString *str = @"http://ios.LiLe.cn";
if ([str hasPrefix:@"http"]) {
NSLog(@"是url");
}
if ([str hasSuffix:@".cn"]) {
NSLog(@"是天朝顶级域名");
}
*/
var str8 = "http://www.520it.com"
if str8.hasPrefix("http") {
print("是url");
}
if str8.hasSuffix(".com") {
print("是顶级域名");
}
/*
大小写转换
OC:
NSString *str = @"abc.txt";
NSLog(@"%@", [str uppercaseString]);
NSLog(@"%@", [str lowercaseString]);
*/
var str9 = "abc.txt";
print(str9.uppercaseString)
print(str9.lowercaseString)
/*
转换为基本数据类型
OC:
NSString *str = @"250";
NSInteger number = [str integerValue];
NSLog(@"%tu", number);
*/
var str10 = "250"
// 如果str不能转换为整数, 那么可选类型返回nil
// str = "250sb" 不能转换所以可能为nil
var number:Int? = Int(str10)
if number != nil
{
// 以前的版本println会自动拆包, 现在的不会
print(number!)
}
| mit | b7d9f9163aad154941712f0ea3ddc4f6 | 13.363057 | 93 | 0.616851 | 2.591954 | false | false | false | false |
danbennett/DBRepo | Example/DBRepoExample/ViewController.swift | 1 | 924 | //
// ViewController.swift
// DBRepoExample
//
// Created by Daniel Bennett on 10/07/2016.
// Copyright © 2016 Dan Bennett. All rights reserved.
//
import UIKit
import DBRepo
class ViewController: UIViewController {
var repo: protocol<RepoLifetimeType, RepoQueryType, RepoSavingType>!
override func viewDidLoad() {
super.viewDidLoad()
// Note: Use error handling!
// 1. Fetch existing object...
let results = try! repo.fetch(Entity.self, predicate: nil)
// If non exist ...
if results.count == 0 {
// 2. Begin write.
repo.beginWrite()
// 3. Create entity.
let entity = try! self.repo.addEntity(Entity)
entity.entityId = "unique id here"
// 4. End write.
try! repo.endWrite()
}
}
}
| mit | 50a955e2b2bd973123376046e831875f | 20.97619 | 72 | 0.531961 | 4.569307 | false | false | false | false |
eggswift/ESTabBarController | ESTabBarControllerExample/ESTabBarControllerExample/Content/Tips/ExampleAnimateTipsContentView.swift | 1 | 1896 | //
// ExampleAnimateTipsContentView.swift
// ESTabBarControllerExample
//
// Created by lihao on 2017/2/10.
// Copyright © 2018年 Egg Swift. All rights reserved.
//
import UIKit
class ExampleAnimateTipsContentView: ExampleBackgroundContentView {
var duration = 0.3
override func badgeChangedAnimation(animated: Bool, completion: (() -> ())?) {
super.badgeChangedAnimation(animated: animated, completion: nil)
notificationAnimation()
}
func notificationAnimation() {
let impliesAnimation = CAKeyframeAnimation(keyPath: "transform.translation.y")
impliesAnimation.values = [0.0 ,-8.0, 4.0, -4.0, 3.0, -2.0, 0.0]
impliesAnimation.duration = duration * 2
impliesAnimation.calculationMode = CAAnimationCalculationMode.cubic
imageView.layer.add(impliesAnimation, forKey: nil)
}
}
class ExampleAnimateTipsContentView2: ExampleAnimateTipsContentView {
override func notificationAnimation() {
let impliesAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
impliesAnimation.values = [1.0 ,1.4, 0.9, 1.15, 0.95, 1.02, 1.0]
impliesAnimation.duration = duration * 2
impliesAnimation.calculationMode = CAAnimationCalculationMode.cubic
self.badgeView.layer.add(impliesAnimation, forKey: nil)
}
}
class ExampleAnimateTipsContentView3: ExampleAnimateTipsContentView {
override init(frame: CGRect) {
super.init(frame: frame)
badgeColor = UIColor.clear
badgeView.imageView.image = UIImage.init(named: "tips2")?.resizableImage(withCapInsets: UIEdgeInsets.init(top: 10, left: 10, bottom: 25, right: 25)).withRenderingMode(.alwaysTemplate)
badgeView.tintColor = UIColor.lightGray
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 2718d035544974dd3c0b6b4385d977e9 | 34.055556 | 191 | 0.695193 | 4.292517 | false | false | false | false |
thongtran715/Find-Friends | Pods/Bond/Bond/Extensions/iOS/UIDatePicker+Bond.swift | 16 | 2224 | //
// The MIT License (MIT)
//
// Copyright (c) 2015 Srdan Rasic (@srdanrasic)
//
// 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
extension UIDatePicker {
private struct AssociatedKeys {
static var DateKey = "bnd_DateKey"
}
public var bnd_date: Observable<NSDate> {
if let bnd_date: AnyObject = objc_getAssociatedObject(self, &AssociatedKeys.DateKey) {
return bnd_date as! Observable<NSDate>
} else {
let bnd_date = Observable<NSDate>(self.date)
objc_setAssociatedObject(self, &AssociatedKeys.DateKey, bnd_date, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
var updatingFromSelf: Bool = false
bnd_date.observeNew { [weak self] (date: NSDate) in
if !updatingFromSelf {
self?.date = date
}
}
self.bnd_controlEvent.filter { $0 == UIControlEvents.ValueChanged }.observe { [weak self, weak bnd_date] event in
guard let unwrappedSelf = self, let bnd_date = bnd_date else { return }
updatingFromSelf = true
bnd_date.next(unwrappedSelf.date)
updatingFromSelf = false
}
return bnd_date
}
}
}
| mit | 0673b9750c3ea573f521e5c5eefc9a7e | 37.344828 | 129 | 0.697842 | 4.326848 | false | false | false | false |
chadsy/onebusaway-iphone | Pods/PromiseKit/Categories/CoreLocation/CLGeocoder+Promise.swift | 7 | 2211 | import CoreLocation.CLGeocoder
#if !COCOAPODS
import PromiseKit
#endif
/**
To import the `CLGeocoder` category:
use_frameworks!
pod "PromiseKit/CoreLocation"
And then in your sources:
import PromiseKit
*/
extension CLGeocoder {
public func reverseGeocodeLocation(location: CLLocation) -> PlacemarkPromise {
return PlacemarkPromise.go { resolve in
reverseGeocodeLocation(location, completionHandler: resolve)
}
}
public func geocode(addressDictionary: [String: String]) -> PlacemarkPromise {
return PlacemarkPromise.go { resolve in
geocodeAddressDictionary(addressDictionary, completionHandler: resolve)
}
}
public func geocode(addressString: String) -> PlacemarkPromise {
return PlacemarkPromise.go { resolve in
geocodeAddressString(addressString, completionHandler: resolve)
}
}
public func geocode(addressString: String, region: CLRegion?) -> PlacemarkPromise {
return PlacemarkPromise.go { resolve in
geocodeAddressString(addressString, inRegion: region, completionHandler: resolve)
}
}
}
extension CLError: CancellableErrorType {
public var cancelled: Bool {
return self == .GeocodeCanceled
}
}
public class PlacemarkPromise: Promise<CLPlacemark> {
public func allResults() -> Promise<[CLPlacemark]> {
return then(on: zalgo) { _ in return self.placemarks }
}
private var placemarks: [CLPlacemark]!
private class func go(@noescape body: (([CLPlacemark]?, NSError?) -> Void) -> Void) -> PlacemarkPromise {
var promise: PlacemarkPromise!
promise = PlacemarkPromise { fulfill, reject in
body { placemarks, error in
if let error = error {
reject(error)
} else {
promise.placemarks = placemarks
fulfill(placemarks!.first!)
}
}
}
return promise
}
private override init(@noescape resolvers: (fulfill: (CLPlacemark) -> Void, reject: (ErrorType) -> Void) throws -> Void) {
super.init(resolvers: resolvers)
}
}
| apache-2.0 | 675433ce1ad73339af1f342a8eea6e0c | 28.878378 | 126 | 0.635911 | 4.990971 | false | false | false | false |
Egibide-DAM/swift | 02_ejemplos/08_extensiones_protocolos_genericos/01_extensiones/02_anyadir_inicializadores.playground/Contents.swift | 1 | 714 | struct Size {
var width = 0.0, height = 0.0
}
struct Point {
var x = 0.0, y = 0.0
}
struct Rect {
var origin = Point()
var size = Size()
}
let defaultRect = Rect()
let memberwiseRect = Rect(origin: Point(x: 2.0, y: 2.0),
size: Size(width: 5.0, height: 5.0))
extension Rect {
init(center: Point, size: Size) {
let originX = center.x - (size.width / 2)
let originY = center.y - (size.height / 2)
self.init(origin: Point(x: originX, y: originY), size: size)
}
}
let centerRect = Rect(center: Point(x: 4.0, y: 4.0),
size: Size(width: 3.0, height: 3.0))
// centerRect's origin is (2.5, 2.5) and its size is (3.0, 3.0)
| apache-2.0 | 034c51209e961982f0084cc450f578e7 | 24.5 | 68 | 0.54902 | 2.902439 | false | false | false | false |
Jamnitzer/MBJ_ImageProcessing | MBJ_ImageProcessing/MBJ_ImageProcessing/MBJTextureUtilities.swift | 1 | 2377 | //
// UIImage+MBETextureUtilities.m
// ImageProcessing
//
// Created by Warren Moore on 10/8/14.
// Copyright (c) 2014 Metal By Example. All rights reserved.
//------------------------------------------------------------------------
// converted to Swift by Jamnitzer (Jim Wrenholt)
//------------------------------------------------------------------------
import Foundation
import UIKit
import Metal
//------------------------------------------------------------------------------
class MBJTextureUtilities
{
//------------------------------------------------------------------------
class func imageWithMTLTexture(texture:MTLTexture) -> UIImage?
{
assert(texture.pixelFormat == MTLPixelFormat.RGBA8Unorm,
"Pixel format of texture must be MTLPixelFormatBGRA8Unorm to create UIImage")
let width = Int(texture.width)
let height = Int(texture.height)
let imageByteCount = width * height * 4
let imageBytes = malloc(imageByteCount)
let bytesPerRow = width * 4
let region = MTLRegionMake2D(0, 0, width, height)
texture.getBytes(imageBytes, bytesPerRow:bytesPerRow, fromRegion:region, mipmapLevel:0)
let provider = CGDataProviderCreateWithData(nil,
imageBytes, imageByteCount, nil) // MBJReleaseDataCallback ?
let bitsPerComponent = 8
let bitsPerPixel = 32
let colorSpaceRef = CGColorSpaceCreateDeviceRGB()
let bitmapInfo:CGBitmapInfo = CGBitmapInfo(rawValue:
CGImageAlphaInfo.PremultipliedLast.rawValue | CGBitmapInfo.ByteOrder32Big.rawValue)
let renderingIntent:CGColorRenderingIntent = .RenderingIntentDefault
let imageRef = CGImageCreate(width, height,
bitsPerComponent, bitsPerPixel, bytesPerRow,
colorSpaceRef,
bitmapInfo,
provider,
nil,
false,
renderingIntent)
let image = UIImage(CGImage:imageRef!, scale:0.0, orientation:UIImageOrientation.DownMirrored)
return image;
}
//------------------------------------------------------------------------
}
//------------------------------------------------------------------------------
| mit | 157a1ac60932b48941dd81fbce4faa82 | 39.288136 | 102 | 0.501052 | 6.28836 | false | false | false | false |
gaoleegin/SwiftLianxi | TheNextPlayGround(鸡汤之后).playground/Contents.swift | 1 | 1954 | //: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
//常量和变量π
let maximumNumOfLoginAttempts = 10;
let currentLoginAttempt = 0;
var welcomeMessage:String = "哈哈哈"
//:常量和变量的命名
let 🍋 = "哈哈"
print("this is a package\(🍋)")
let minValue1 = uint.min
let maxValue1 = uint.max
let minValue2 = UInt8.min
let maxValue2 = UInt8.max
let minValue3 = Int.min
let maxValue3 = Int.max
//数值型字面量
let decimaInteger = 17;
let binaryInteger = 0b10001;
let octalInteger = 0o21
let hexadecimalInteger = 0x11
//通常来讲,及时代码中的整数常量和变量已知非负,也请使用int类型,总是使用默认的整数类型可以保证你的整数类型常量和变量可以直接被复用,并且可以匹配整数类字面量的了行推断
//整数转换:如果数字超出了常量或者是变量可存储的范围
typealias AutoSample = UInt16
let minValue4 = AutoSample.min
let maxValue4 = AutoSample.max
//关键字 typealias 就是给一个类型定义一个别名 布尔值
//Swift有一个基本的布尔值,叫做bool
let orangesareorange = true
let turnipsdelicious = false
if orangesareorange{
print("正确")
} else{
print("错误")
}
//元祖(tuples)把多个值组合成一个复合值,元祖内的值的类型可以是任何类型,并不要求是相同的类型,
//元组在临时组织值的时候很有用,但是并不适合创建复杂的数据结构,如果你的数据结构不是临时使用,请使用类或者结构体而不是元组
//可选类型(optionals)
//有值,等于X
//没有值
let poss:String = "123"
//toInt已经舍弃了
let possibleNumber = "123"
var serverceCode:Int?
serverceCode = nil
//在Swift和OC中的的nil的区别
// 在OC中:nil是一个不存在对象的指针
// 在Swift中:nil不是一个指针,用来表示值的缺失
| apache-2.0 | 9c71d299236dd158ee5eee99af583c2f | 12.173469 | 86 | 0.746708 | 2.587174 | false | false | false | false |
ktatroe/MPA-Horatio | Horatio/Horatio/Classes/Operations/CalendarCondition.swift | 2 | 2235 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
This file shows an example of implementing the OperationCondition protocol.
*/
import EventKit
/// A condition for verifying access to the user's calendar.
public struct CalendarCondition: OperationCondition {
public static let name = "Calendar"
public static let entityTypeKey = "EKEntityType"
public static let isMutuallyExclusive = false
let entityType: EKEntityType
public init(entityType: EKEntityType) {
self.entityType = entityType
}
public func dependencyForOperation(_ operation: Operation) -> Foundation.Operation? {
return CalendarPermissionOperation(entityType: entityType)
}
public func evaluateForOperation(_ operation: Operation, completion: @escaping (OperationConditionResult) -> Void) {
switch EKEventStore.authorizationStatus(for: entityType) {
case .authorized:
completion(.satisfied)
default:
// We are not authorized to access entities of this type.
let error = NSError(code: .conditionFailed, userInfo: [
OperationConditionKey: type(of: self).name,
type(of: self).entityTypeKey: entityType.rawValue
])
completion(.failed(error))
}
}
}
/**
A private `Operation` that will request access to the user's Calendar/Reminders,
if it has not already been granted.
*/
private class CalendarPermissionOperation: Operation {
let entityType: EKEntityType
let store = EKEventStore()
init(entityType: EKEntityType) {
self.entityType = entityType
super.init()
addCondition(AlertPresentation())
}
override func execute() {
let status = EKEventStore.authorizationStatus(for: entityType)
switch status {
case .notDetermined:
DispatchQueue.main.async {
self.store.requestAccess(to: self.entityType) { granted, error in
self.finish()
}
}
default:
finish()
}
}
}
| mit | 10dd4e45a530c1c27cf8b33888e460ab | 28.773333 | 120 | 0.633229 | 5.459658 | false | false | false | false |
TobogganApps/TAOverlayView | Pod/Classes/TAOverlayView.swift | 1 | 3317 | /*
Copyright © 2016 Toboggan Apps LLC. 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
/// View with a black, semi-transparent overlay that can have subtracted "holes" to view behind the overlay.
/// Optionally add ``subtractedPaths`` to initialize the overlay with holes. More paths can be subtracted later using ``subtractFromView``.
public class TAOverlayView: UIView {
/// The paths that have been subtracted from the view.
fileprivate var subtractions: [UIBezierPath] = []
/// Use to init the overlay.
///
/// - parameter frame: The frame to use for the semi-transparent overlay.
/// - parameter subtractedPaths: The paths to subtract from the overlay initially. These are optional (not adding them creates a plain overlay). More paths can be subtracted later using ``subtractFromView``.
///
public init(frame: CGRect, subtractedPaths: [TABaseSubtractionPath]? = nil) {
super.init(frame: frame)
// Set a semi-transparent, black background.
self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.85)
// Create the initial layer from the view bounds.
let maskLayer = CAShapeLayer()
maskLayer.frame = self.bounds
maskLayer.fillColor = UIColor.black.cgColor
let path = UIBezierPath(rect: self.bounds)
maskLayer.path = path.cgPath
maskLayer.fillRule = kCAFillRuleEvenOdd
// Set the mask of the view.
self.layer.mask = maskLayer
if let paths = subtractedPaths {
// Subtract any given paths.
self.subtractFromView(paths: paths)
}
}
override public func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
// Allow touches in "holes" of the overlay to be sent to the views behind it.
for path in self.subtractions {
if path.contains(point) {
return false
}
}
return true
}
/// Subtracts the given ``paths`` from the view.
public func subtractFromView(paths: [TABaseSubtractionPath]) {
if let layer = self.layer.mask as? CAShapeLayer, let oldPath = layer.path {
// Start off with the old/current path.
let newPath = UIBezierPath(cgPath: oldPath)
// Subtract each of the new paths.
for path in paths {
self.subtractions.append(path.bezierPath)
newPath.append(path.bezierPath)
}
// Update the layer.
layer.path = newPath.cgPath
self.layer.mask = layer
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | b38a737abccfe4908b7b5479c1b807e1 | 36.258427 | 211 | 0.641435 | 4.771223 | false | false | false | false |
SASAbus/SASAbus-ios | SASAbus/View/BottomSheet/BottomSheetViewController.swift | 1 | 22826 | import UIKit
/**
* The base delegate protocol for Pulley delegates.
*/
@objc protocol BottomSheetDelegate: class {
@objc optional func drawerPositionDidChange(drawer: BottomSheetViewController)
@objc optional func makeUIAdjustmentsForFullscreen(progress: CGFloat)
@objc optional func offsetChanged(distance: CGFloat, offset: CGFloat)
}
/**
* View controllers in the drawer can implement this to receive changes in state or provide values for the different drawer positions.
*/
@objc protocol BottomSheetDrawerViewControllerDelegate: BottomSheetDelegate {
func collapsedDrawerHeight() -> CGFloat
func partialRevealDrawerHeight() -> CGFloat
}
/**
* View controllers that are the main content can implement this to receive changes in state.
*/
@objc protocol BottomSheetPrimaryContentControllerDelegate: BottomSheetDelegate {
// Not currently used for anything, but it's here for parity with the hopes that it'll one day be used.
}
/**
Represents a Pulley drawer position.
- Collapsed: When the drawer is in its smallest form, at the bottom of the screen.
- PartiallyRevealed: When the drawer is partially revealed.
- Open: When the drawer is fully open.
*/
public enum BottomSheetPosition {
case collapsed
case partiallyRevealed
case open
}
private let kPulleyDefaultCollapsedHeight: CGFloat = 68.0
private let kPulleyDefaultPartialRevealHeight: CGFloat = 264.0
class BottomSheetViewController: MasterViewController, UIScrollViewDelegate, BottomSheetPassthroughScrollViewDelegate {
// Interface Builder
/// When using with Interface Builder only! Connect a containing view to this outlet.
@IBOutlet var primaryContentContainerView: UIView!
/// When using with Interface Builder only! Connect a containing view to this outlet.
@IBOutlet var drawerContentContainerView: UIView!
var backgroundImage: UIImageView! = UIImageView()
// Internal
private let primaryContentContainer: UIView = UIView()
private let drawerContentContainer: UIView = UIView()
private let drawerShadowView: UIView = UIView()
public let drawerScrollView: BottomSheetPassthroughScrollView = BottomSheetPassthroughScrollView()
private let backgroundDimmingView: UIView = UIView()
private var dimmingViewTapRecognizer: UITapGestureRecognizer?
/// The current content view controller (shown behind the drawer).
private(set) var primaryContentViewController: UIViewController! {
willSet {
guard let controller = primaryContentViewController else {
return
}
controller.view.removeFromSuperview()
controller.removeFromParentViewController()
}
didSet {
guard let controller = primaryContentViewController else {
return
}
let view = controller.view
view!.translatesAutoresizingMaskIntoConstraints = true
self.primaryContentContainer.addSubview(view!)
self.addChildViewController(controller)
if self.isViewLoaded {
self.view.setNeedsLayout()
}
}
}
/// The current drawer view controller (shown in the drawer).
private(set) var drawerContentViewController: UIViewController! {
willSet {
guard let controller = drawerContentViewController else {
return
}
controller.view.removeFromSuperview()
controller.removeFromParentViewController()
}
didSet {
guard let controller = drawerContentViewController else {
return
}
controller.view.translatesAutoresizingMaskIntoConstraints = true
self.drawerContentContainer.addSubview(controller.view)
self.addChildViewController(controller)
if self.isViewLoaded {
self.view.setNeedsLayout()
}
}
}
// The content view controller and drawer controller can receive delegate events already.
// This lets another object observe the changes, if needed.
public weak var delegate: BottomSheetDelegate?
// The current position of the drawer.
public private(set) var drawerPosition: BottomSheetPosition = .collapsed
// The inset from the top of the view controller when fully open.
public var topInset: CGFloat = 200 {
didSet {
if self.isViewLoaded {
self.view.setNeedsLayout()
}
}
}
// The corner radius for the drawer.
public var drawerCornerRadius: CGFloat = 0 {
didSet {
if self.isViewLoaded {
self.view.setNeedsLayout()
}
}
}
// The opacity of the drawer shadow.
public var shadowOpacity: Float = 0.1 {
didSet {
if self.isViewLoaded {
self.view.setNeedsLayout()
}
}
}
// The radius of the drawer shadow.
public var shadowRadius: CGFloat = 3.0 {
didSet {
if self.isViewLoaded {
self.view.setNeedsLayout()
}
}
}
// The opaque color of the background dimming view.
public var backgroundDimmingColor: UIColor = UIColor.black {
didSet {
if self.isViewLoaded {
backgroundDimmingView.backgroundColor = backgroundDimmingColor
}
}
}
// The maximum amount of opacity when dimming.
public var backgroundDimmingOpacity: CGFloat = 0.5 {
didSet {
if self.isViewLoaded {
self.scrollViewDidScroll(drawerScrollView)
}
}
}
/**
Initialize the drawer controller programmtically.
- parameter contentViewController: The content view controller. This view controller is shown behind the drawer.
- parameter drawerViewController: The view controller to display inside the drawer.
- note: The drawer VC is 20pts too tall in order to have some extra space for the bounce animation.
Make sure your constraints / content layout take this into account.
- returns: A newly created Pulley drawer.
*/
required public init(contentViewController: UIViewController, drawerViewController: UIViewController) {
super.init(nibName: nil, title: nil)
({
self.primaryContentViewController = contentViewController
self.drawerContentViewController = drawerViewController
})()
}
/**
Initialize the drawer controller from Interface Builder.
- note: Usage notes: Make 2 container views in Interface Builder and connect their
outlets to -primaryContentContainerView and -drawerContentContainerView.
Then use embed segues to place your content/drawer view controllers into the appropriate container.
- parameter aDecoder: The NSCoder to decode from.
- returns: A newly created Pulley drawer.
*/
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override func loadView() {
super.loadView()
// IB Support
if primaryContentContainerView != nil {
primaryContentContainerView.removeFromSuperview()
}
if drawerContentContainerView != nil {
drawerContentContainerView.removeFromSuperview()
}
// Setup
primaryContentContainer.backgroundColor = UIColor.white
drawerScrollView.bounces = false
drawerScrollView.delegate = self
drawerScrollView.clipsToBounds = false
drawerScrollView.showsVerticalScrollIndicator = false
drawerScrollView.showsHorizontalScrollIndicator = false
drawerScrollView.delaysContentTouches = true
drawerScrollView.canCancelContentTouches = true
drawerScrollView.backgroundColor = UIColor.clear
drawerScrollView.decelerationRate = UIScrollViewDecelerationRateFast
drawerScrollView.touchDelegate = self
drawerShadowView.layer.shadowOpacity = shadowOpacity
drawerShadowView.layer.shadowRadius = shadowRadius
drawerShadowView.backgroundColor = UIColor.clear
drawerContentContainer.backgroundColor = UIColor.clear
backgroundDimmingView.backgroundColor = backgroundDimmingColor
backgroundDimmingView.isUserInteractionEnabled = false
backgroundDimmingView.alpha = 0.0
dimmingViewTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(dimmingViewTapRecognizerAction(gestureRecognizer:)))
backgroundDimmingView.addGestureRecognizer(dimmingViewTapRecognizer!)
drawerScrollView.addSubview(drawerShadowView)
drawerScrollView.addSubview(drawerContentContainer)
primaryContentContainer.backgroundColor = UIColor.white
self.view.backgroundColor = UIColor.white
backgroundImage.contentMode = .scaleAspectFill
self.view.addSubview(primaryContentContainer)
self.view.addSubview(backgroundDimmingView)
self.view.addSubview(backgroundImage)
self.view.addSubview(drawerScrollView)
}
public override func viewDidLoad() {
super.viewDidLoad()
// IB Support
if primaryContentViewController == nil || drawerContentViewController == nil {
assert(primaryContentContainerView != nil && drawerContentContainerView != nil,
"When instantiating from Interface Builder you must provide container views with an embedded view controller.")
// Locate main content VC
for child in self.childViewControllers {
if child.view == primaryContentContainerView.subviews.first {
primaryContentViewController = child
}
if child.view == drawerContentContainerView.subviews.first {
drawerContentViewController = child
}
}
assert(primaryContentViewController != nil && drawerContentViewController != nil,
"Container views must contain an embedded view controller.")
}
scrollViewDidScroll(drawerScrollView)
}
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// Layout main content
primaryContentContainer.frame = self.view.bounds
backgroundDimmingView.frame = self.view.bounds
// Layout scrollview
drawerScrollView.frame = CGRect(x: 0, y: topInset, width: self.view.bounds.width, height: self.view.bounds.height - topInset)
// Layout container
var collapsedHeight: CGFloat = kPulleyDefaultCollapsedHeight
var partialRevealHeight: CGFloat = kPulleyDefaultPartialRevealHeight
if let drawerVCCompliant = drawerContentViewController as? BottomSheetDrawerViewControllerDelegate {
collapsedHeight = drawerVCCompliant.collapsedDrawerHeight()
partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight()
}
let lowestStop = [(self.view.bounds.size.height - topInset), collapsedHeight, partialRevealHeight].min() ?? 0
let bounceOverflowMargin: CGFloat = 20
drawerContentContainer.frame = CGRect(x: 0, y: drawerScrollView.bounds.height - lowestStop,
width: drawerScrollView.bounds.width, height: drawerScrollView.bounds.height + bounceOverflowMargin)
drawerShadowView.frame = drawerContentContainer.frame
drawerScrollView.contentSize = CGSize(width: drawerScrollView.bounds.width,
height: (drawerScrollView.bounds.height - lowestStop) + drawerScrollView.bounds.height)
// Update rounding mask and shadows
let borderPath = UIBezierPath(roundedRect: drawerContentContainer.bounds,
byRoundingCorners: [.topLeft, .topRight], cornerRadii:
CGSize(width: drawerCornerRadius, height: drawerCornerRadius)).cgPath
let cardMaskLayer = CAShapeLayer()
cardMaskLayer.path = borderPath
cardMaskLayer.fillColor = UIColor.white.cgColor
cardMaskLayer.backgroundColor = UIColor.clear.cgColor
drawerContentContainer.layer.mask = cardMaskLayer
drawerShadowView.layer.shadowPath = borderPath
// Make VC views match frames
primaryContentViewController.view.frame = primaryContentContainer.bounds
drawerContentViewController.view.frame = CGRect(
x: drawerContentContainer.bounds.minX,
y: drawerContentContainer.bounds.minY,
width: drawerContentContainer.bounds.width,
height: drawerContentContainer.bounds.height
)
}
// MARK: Configuration Updates
/**
Set the drawer position, with an option to animate.
- parameter position: The position to set the drawer to.
- parameter animated: Whether or not to animate the change. (Default: true)
*/
public func setDrawerPosition(position: BottomSheetPosition, animated: Bool = true) {
drawerPosition = position
var collapsedHeight: CGFloat = kPulleyDefaultCollapsedHeight
var partialRevealHeight: CGFloat = kPulleyDefaultPartialRevealHeight
if let drawerVCCompliant = drawerContentViewController as? BottomSheetDrawerViewControllerDelegate {
collapsedHeight = drawerVCCompliant.collapsedDrawerHeight()
partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight()
}
let stopToMoveTo: CGFloat
switch drawerPosition {
case .collapsed:
stopToMoveTo = collapsedHeight
case .partiallyRevealed:
stopToMoveTo = partialRevealHeight
case .open:
stopToMoveTo = (self.view.bounds.size.height - topInset)
}
let drawerStops = [(self.view.bounds.size.height - topInset), collapsedHeight, partialRevealHeight]
let lowestStop = drawerStops.min() ?? 0
if animated {
UIView.animate(withDuration: 0.2, delay: 0.0, options: .curveEaseOut, animations: { [weak self] () -> Void in
self?.drawerScrollView.setContentOffset(CGPoint(x: 0, y: stopToMoveTo - lowestStop), animated: false)
if let drawer = self {
drawer.delegate?.drawerPositionDidChange?(drawer: drawer)
(drawer.drawerContentViewController as? BottomSheetDrawerViewControllerDelegate)?.drawerPositionDidChange?(drawer: drawer)
(drawer.primaryContentViewController as? BottomSheetPrimaryContentControllerDelegate)?.drawerPositionDidChange?(drawer: drawer)
drawer.view.layoutIfNeeded()
}
}, completion: nil)
} else {
drawerScrollView.setContentOffset(CGPoint(x: 0, y: stopToMoveTo - lowestStop), animated: false)
delegate?.drawerPositionDidChange?(drawer: self)
(drawerContentViewController as? BottomSheetDrawerViewControllerDelegate)?.drawerPositionDidChange?(drawer: self)
(primaryContentViewController as? BottomSheetPrimaryContentControllerDelegate)?.drawerPositionDidChange?(drawer: self)
}
}
/**
Change the current primary content view controller (The one behind the drawer)
- parameter controller: The controller to replace it with
- parameter animated: Whether or not to animate the change. Defaults to true.
*/
public func setPrimaryContentViewController(controller: UIViewController, animated: Bool = true) {
if animated {
UIView.transition(with: primaryContentContainer, duration: 0.5, options:
UIViewAnimationOptions.transitionCrossDissolve, animations: { [weak self] () -> Void in
self?.primaryContentViewController = controller
}, completion: nil)
} else {
primaryContentViewController = controller
}
}
/**
Change the current drawer content view controller (The one inside the drawer)
- parameter controller: The controller to replace it with
- parameter animated: Whether or not to animate the change.
*/
public func setDrawerContentViewController(controller: UIViewController, animated: Bool = true) {
if animated {
UIView.transition(with: drawerContentContainer, duration: 0.5, options:
UIViewAnimationOptions.transitionCrossDissolve, animations: { [weak self] () -> Void in
self?.drawerContentViewController = controller
self?.setDrawerPosition(position: self?.drawerPosition ?? .collapsed, animated: false)
}, completion: nil)
} else {
drawerContentViewController = controller
setDrawerPosition(position: drawerPosition, animated: false)
}
}
// MARK: Actions
func dimmingViewTapRecognizerAction(gestureRecognizer: UITapGestureRecognizer) {
if gestureRecognizer == dimmingViewTapRecognizer {
if gestureRecognizer.state == .began {
self.setDrawerPosition(position: .collapsed, animated: true)
}
}
}
// MARK: UIScrollViewDelegate
private var lastDragTargetContentOffset: CGPoint = CGPoint.zero
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if scrollView == drawerScrollView {
// Find the closest anchor point and snap there.
var collapsedHeight: CGFloat = kPulleyDefaultCollapsedHeight
var partialRevealHeight: CGFloat = kPulleyDefaultPartialRevealHeight
if let drawerVCCompliant = drawerContentViewController as? BottomSheetDrawerViewControllerDelegate {
collapsedHeight = drawerVCCompliant.collapsedDrawerHeight()
partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight()
}
let drawerStops = [(self.view.bounds.size.height - topInset), collapsedHeight, partialRevealHeight]
let lowestStop = drawerStops.min() ?? 0
let distanceFromBottomOfView = lowestStop + lastDragTargetContentOffset.y
var currentClosestStop = lowestStop
for currentStop in drawerStops {
if abs(currentStop - distanceFromBottomOfView) < abs(currentClosestStop - distanceFromBottomOfView) {
currentClosestStop = currentStop
}
}
if abs(Float(currentClosestStop - (self.view.bounds.size.height - topInset))) <= Float.ulpOfOne {
setDrawerPosition(position: .open, animated: true)
} else if abs(Float(currentClosestStop - collapsedHeight)) <= Float.ulpOfOne {
setDrawerPosition(position: .collapsed, animated: true)
} else {
setDrawerPosition(position: .partiallyRevealed, animated: true)
}
}
}
public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint,
targetContentOffset: UnsafeMutablePointer<CGPoint>) {
if scrollView == drawerScrollView {
lastDragTargetContentOffset = targetContentOffset.pointee
// Halt intertia
targetContentOffset.pointee = scrollView.contentOffset
}
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView == drawerScrollView {
var partialRevealHeight: CGFloat = kPulleyDefaultPartialRevealHeight
var collapsedHeight: CGFloat = kPulleyDefaultCollapsedHeight
if let drawerVCCompliant = drawerContentViewController as? BottomSheetDrawerViewControllerDelegate {
collapsedHeight = drawerVCCompliant.collapsedDrawerHeight()
partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight()
}
let drawerStops = [(self.view.bounds.size.height - topInset), collapsedHeight, partialRevealHeight]
let lowestStop = drawerStops.min() ?? 0
var progress: CGFloat = 0
if scrollView.contentOffset.y > partialRevealHeight - lowestStop {
// Calculate percentage between partial and full reveal
let fullRevealHeight = (self.view.bounds.size.height - topInset)
progress = (scrollView.contentOffset.y - (partialRevealHeight - lowestStop)) / (fullRevealHeight - (partialRevealHeight))
delegate?.makeUIAdjustmentsForFullscreen?(progress: progress)
(drawerContentViewController as? BottomSheetDrawerViewControllerDelegate)?.makeUIAdjustmentsForFullscreen?(progress: progress)
(primaryContentViewController as? BottomSheetPrimaryContentControllerDelegate)?.makeUIAdjustmentsForFullscreen?(progress: progress)
backgroundDimmingView.alpha = progress * backgroundDimmingOpacity
backgroundDimmingView.isUserInteractionEnabled = true
} else {
if backgroundDimmingView.alpha >= 0.001 {
backgroundDimmingView.alpha = 0.0
delegate?.makeUIAdjustmentsForFullscreen?(progress: 0.0)
(drawerContentViewController as? BottomSheetDrawerViewControllerDelegate)?.makeUIAdjustmentsForFullscreen?(progress: 0.0)
(primaryContentViewController as? BottomSheetPrimaryContentControllerDelegate)?.makeUIAdjustmentsForFullscreen?(progress: 0.0)
backgroundDimmingView.isUserInteractionEnabled = false
}
}
delegate?.offsetChanged?(distance: scrollView.contentOffset.y + lowestStop, offset: progress)
(drawerContentViewController as? BottomSheetDrawerViewControllerDelegate)?
.offsetChanged?(distance: scrollView.contentOffset.y + lowestStop, offset: progress)
(primaryContentViewController as? BottomSheetPrimaryContentControllerDelegate)?
.offsetChanged?(distance: scrollView.contentOffset.y + lowestStop, offset: progress)
}
}
// MARK: Touch Passthrough ScrollView Delegate
func shouldTouchPassthroughScrollView(scrollView: BottomSheetPassthroughScrollView, point: CGPoint) -> Bool {
let contentDrawerLocation = drawerContentContainer.frame.origin.y
if point.y < contentDrawerLocation {
return true
}
return false
}
func viewToReceiveTouch(scrollView: BottomSheetPassthroughScrollView) -> UIView {
if drawerPosition == .open {
return backgroundDimmingView
}
return primaryContentContainer
}
}
| gpl-3.0 | c16f53f414aaf1229793f0d9b66dbc61 | 38.628472 | 147 | 0.676334 | 5.723671 | false | false | false | false |
maurovc/MyMarvel | MyMarvel/SiriUtils.swift | 1 | 2475 | //
// SiriUtils.swift
// MyMarvel
//
// Created by Mauro Vime Castillo on 26/10/16.
// Copyright © 2016 Mauro Vime Castillo. All rights reserved.
//
import Foundation
import CoreSpotlight
import MobileCoreServices
/// Class used to index and parse an action triggered by a spotlight search.
class SiriUtils: NSObject {
static let sharedUtils = SiriUtils()
let heroType = "com.myMarvel.hero"
var currentHero: String?
var activity: NSUserActivity?
func reset() {
currentHero = nil
}
}
//MARK: Indexing method
extension SiriUtils {
func indexHero(hero: Hero) {
let attributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeJSON as String)
attributeSet.title = hero.name ?? ""
attributeSet.contentDescription = hero.descr ?? ""
attributeSet.metadataModificationDate = NSDate()
if let data = hero.imageData {
attributeSet.thumbnailData = data
}
let item = CSSearchableItem(uniqueIdentifier: "hero/" + "\(hero.identifier ?? 0)", domainIdentifier: heroType, attributeSet: attributeSet)
CSSearchableIndex.defaultSearchableIndex().indexSearchableItems([item]) { (error: NSError?) -> Void in
}
}
}
//MARK: Parsing methods
extension SiriUtils {
func parseUserActivityAction(userActivity: NSUserActivity, delegate: AppDelegate) -> Bool {
reset()
if let itemActivityIdentifier = userActivity.userInfo?["kCSSearchableItemActivityIdentifier"] as? String {
if itemActivityIdentifier.hasPrefix("hero/") {
let identifier = itemActivityIdentifier.componentsSeparatedByString("hero/").last ?? ""
return setOpenHero(identifier, delegate: delegate)
}
}
return false
}
func setOpenHero(heroId: String, delegate: AppDelegate) -> Bool {
currentHero = heroId
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let navVC = storyboard.instantiateViewControllerWithIdentifier(HeroListCollectionViewController.navIdentifier) as! UINavigationController
let detailVC = storyboard.instantiateViewControllerWithIdentifier(HeroDetailViewController.identifier) as! HeroDetailViewController
navVC.pushViewController(detailVC, animated: false)
delegate.window!.rootViewController = navVC
return true
}
}
| mit | 0e19c26b24b97a5c8e339f5d1537b43d | 31.12987 | 146 | 0.67017 | 5.13278 | false | false | false | false |
mohssenfathi/MTLImage | MTLImage/Sources/Core/FilterGroup.swift | 1 | 8682 | //
// FilterGroup.swift
// Pods
//
// Created by Mohssen Fathi on 4/8/16.
//
//
import UIKit
public
class FilterGroup: MTLObject, NSCoding {
deinit {
texture = nil
input = nil
context.source = nil
}
override public init() {
super.init()
title = "Filter Group"
}
public var image: UIImage? {
if let filter = filters.last as? Filter {
return filter.image
}
else if let filterGroup = filters.last as? FilterGroup {
return filterGroup.image
}
return input?.texture?.image
}
public var filters = [MTLObject]()
public func filter(_ image: UIImage) -> UIImage? {
let filter = self.copy() as! FilterGroup
let picture = Picture(image: image.copy() as! UIImage)
picture --> filter
picture.needsUpdate = true
filter.filters.last?.processIfNeeded()
let filteredImage = filter.image
picture.removeAllTargets()
filter.removeAllTargets()
filter.removeAll()
picture.pipeline = nil
filter.context.source = nil
return filteredImage
}
func save() {
DataManager.sharedManager.save(self, completion: nil)
}
func updateFilterIndexes() {
// for i in 0 ..< filters.count {
// filters[i].index = i
// }
}
public func add(_ filter: MTLObject) {
if let last = filters.last {
last.removeAllTargets()
last.addTarget(filter)
} else {
let currentInput = input
input?.removeAllTargets() // Might not want to do this
input = currentInput
input?.addTarget(filter)
}
for target in targets {
filter.addTarget(target)
}
filters.append(filter)
updateFilterIndexes()
}
public func insert(_ filter: MTLObject, index: Int) {
assert(index < filters.count)
if index == 0 {
filter > filters.first!
filters.first?.input?.addTarget(filter)
filters.first?.input?.removeTarget(filters.first!)
}
else {
let previous = filters[index - 1]
for target in previous.targets {
filter.addTarget(target)
}
previous.removeAllTargets()
previous.addTarget(filter)
}
filters.insert(filter, at: index)
updateFilterIndexes()
}
public func remove(_ filter: MTLObject) {
let targets = filter.targets
let input = filter.input
filter.input?.removeTarget(filter)
filter.removeAllTargets()
for target in targets {
input?.addTarget(target)
}
filters.removeObject(filter)
needsUpdate = true
}
public func removeAll() {
for filter in filters {
filter.removeAllTargets()
}
input?.removeAllTargets()
for target in targets {
input?.addTarget(target)
}
filters.removeAll()
}
public func move(_ fromIndex: Int, toIndex: Int) {
if fromIndex == toIndex { return }
filters.swapAt(fromIndex, toIndex)
rebuildFilterChain()
}
func rebuildFilterChain() {
if filters.count == 0 { return }
input?.removeAllTargets()
for filter in filters {
filter.removeAllTargets()
}
input?.addTarget(filters.first!)
for i in 1 ..< filters.count {
filters[i - 1].addTarget(filters[i])
}
for target in targets {
filters.last?.addTarget(target)
}
filters.first?.needsUpdate = true
}
func printFilters() {
var chain: String = ""
chain += ((input?.title)! + " --> ")
for filter in filters {
if filter.targets.count > 1 {
chain += "["
for target in filter.targets {
chain += (target.title + ", ")
}
chain += "] --> "
} else {
chain += (targets.first!.title + " --> ")
}
}
if targets.count > 1 {
chain += "["
for target in targets {
chain += (target.title + ", ")
}
chain += "]"
}
else {
chain += (targets.first!.title + " --> ")
}
print(chain)
}
// MARK: - MTLInput
public override func addTarget(_ target: Output) {
targets.append(target)
if let filter = filters.last {
filter.removeAllTargets()
for target in targets {
filter.addTarget(target)
}
} else {
input?.removeAllTargets()
for target in targets { input?.addTarget(target) }
}
needsUpdate = true
}
public override func removeTarget(_ target: Output) {
// TODO: remove from targets
filters.last?.removeTarget(target)
}
public override func removeAllTargets() {
filters.last?.removeAllTargets()
targets.removeAll()
}
public override var needsUpdate: Bool {
set {
for filter in filters {
filter.needsUpdate = newValue
}
}
get {
if filters.last == nil { return false }
return (filters.last?.needsUpdate)!
}
}
// MARK: - MTLOutput
public override var input: Input? {
didSet {
rebuildFilterChain()
}
}
public var category: String = ""
public var filterDescription: String = ""
// MARK: - NSCoding
public func encode(with aCoder: NSCoder) {
aCoder.encode(title , forKey: "title")
aCoder.encode(identifier, forKey: "identifier")
aCoder.encode(category, forKey: "category")
aCoder.encode(filterDescription, forKey: "filterDescription")
aCoder.encode(filters , forKey: "filters")
}
required public init?(coder aDecoder: NSCoder) {
super.init()
identifier = aDecoder.decodeObject(forKey: "identifier") as! String
title = aDecoder.decodeObject(forKey: "title") as! String
filters = aDecoder.decodeObject(forKey: "filters") as! [Filter]
if let cat = aDecoder.decodeObject(forKey: "category") as? String {
category = cat
}
if let fDesc = aDecoder.decodeObject(forKey: "filterDescription") as? String {
filterDescription = fDesc
}
rebuildFilterChain()
}
// MARK: - Copying
public override func copy() -> Any {
let filterGroup = FilterGroup()
filterGroup.title = title
filterGroup.identifier = identifier
for filter in filters {
filterGroup.add(filter.copy() as! MTLObject)
}
return filterGroup
}
}
public func += (filterGroup: FilterGroup, filter: MTLObject) {
filterGroup.add(filter)
}
public func -= (filterGroup: FilterGroup, filter: MTLObject) {
filterGroup.remove(filter)
}
public func > (left: FilterGroup, right: FilterGroup) {
for target in left.targets {
right.addTarget(target)
}
left.removeAllTargets()
left.addTarget(right)
}
extension Array where Element: Equatable {
mutating func removeObject(_ object: Element) {
if let index = self.index(of: object) {
self.remove(at: index)
}
}
mutating func removeObjectsInArray(_ array: [Element]) {
for object in array {
self.removeObject(object)
}
}
}
extension Array where Element: Equatable {
public func unique() -> [Element] {
var arrayCopy = self
arrayCopy.uniqInPlace()
return arrayCopy
}
mutating public func uniqInPlace() {
var seen = [Element]()
var index = 0
for element in self {
if seen.contains(element) {
remove(at: index)
} else {
seen.append(element)
index += 1
}
}
}
}
| mit | 65f0ca9f1632613140b4bcca32325e13 | 23.948276 | 86 | 0.511748 | 4.972509 | false | false | false | false |
tokyovigilante/CesiumKit | CesiumKit/Scene/Fog.swift | 1 | 5927 | //
// Fog.swift
// CesiumKit
//
// Created by Ryan Walklin on 30/04/2016.
// Copyright © 2016 Test Toast. All rights reserved.
//
import Foundation
/**
* Blends the atmosphere to geometry far from the camera for horizon views. Allows for additional
* performance improvements by rendering less geometry and dispatching less terrain requests.
*
* @alias Fog
* @constructor
*/
class Fog {
/**
* <code>true</code> if fog is enabled, <code>false</code> otherwise.
* @type {Boolean}
* @default true
*/
var enabled = true
/**
* A scalar that determines the density of the fog. Terrain that is in full fog are culled.
* The density of the fog increases as this number approaches 1.0 and becomes less dense as it approaches zero.
* The more dense the fog is, the more aggressively the terrain is culled. For example, if the camera is a height of
* 1000.0m above the ellipsoid, increasing the value to 3.0e-4 will cause many tiles close to the viewer be culled.
* Decreasing the value will push the fog further from the viewer, but decrease performance as more of the terrain is rendered.
* @type {Number}
* @default 2.0e-4
*/
var density = 3.0e-4
/**
* A factor used to increase the screen space error of terrain tiles when they are partially in fog. The effect is to reduce
* the number of terrain tiles requested for rendering. If set to zero, the feature will be disabled. If the value is increased
* for mountainous regions, less tiles will need to be requested, but the terrain meshes near the horizon may be a noticeably
* lower resolution. If the value is increased in a relatively flat area, there will be little noticeable change on the horizon.
* @type {Number}
* @default 2.0
*/
var screenSpaceErrorFactor = 4.0
// These values were found by sampling the density at certain views and finding at what point culled tiles impacted the view at the horizon.
fileprivate let heightsTable = [359.393, 800.749, 1275.6501, 2151.1192, 3141.7763, 4777.5198, 6281.2493, 12364.307, 15900.765, 49889.0549, 78026.8259, 99260.7344, 120036.3873, 151011.0158, 156091.1953, 203849.3112, 274866.9803, 319916.3149, 493552.0528, 628733.5874]
fileprivate var densityTable = [2.0e-5, 2.0e-4, 1.0e-4, 7.0e-5, 5.0e-5, 4.0e-5, 3.0e-5, 1.9e-5, 1.0e-5, 8.5e-6, 6.2e-6, 5.8e-6, 5.3e-6, 5.2e-6, 5.1e-6, 4.2e-6, 4.0e-6, 3.4e-6, 2.6e-6, 2.2e-6]
fileprivate var tableLastIndex = 0
fileprivate let tableStartDensity: Double
fileprivate let tableEndDensity: Double
init () {
// Scale densities by 1e6 to bring lowest value to ~1. Prevents divide by zero.
for i in 0..<densityTable.count {
densityTable[i] *= 1.0e6
}
// Change range to [0, 1].
tableStartDensity = densityTable[1]
tableEndDensity = densityTable.last!
let difference = tableStartDensity - tableEndDensity
for i in 0..<densityTable.count {
densityTable[i] = (densityTable[i] - tableEndDensity) / difference
}
}
fileprivate func findInterval (_ height: Double) -> Int {
let length = heightsTable.count
if height < heightsTable[0] {
tableLastIndex = 0
return tableLastIndex
} else if height > heightsTable[length - 1] {
tableLastIndex = length - 2
return tableLastIndex
}
// Take advantage of temporal coherence by checking current, next and previous intervals
// for containment of time.
if height >= heightsTable[tableLastIndex] {
if tableLastIndex + 1 < length && height < heightsTable[tableLastIndex + 1] {
return tableLastIndex
} else if tableLastIndex + 2 < length && height < heightsTable[tableLastIndex + 2] {
tableLastIndex += 1
return tableLastIndex
}
} else if (tableLastIndex - 1 >= 0 && height >= heightsTable[tableLastIndex - 1]) {
tableLastIndex -= 1
return tableLastIndex
}
// The above failed so do a linear search.
var i = 0
for j in 0..<(length - 2) {
i = j
if height >= heightsTable[i] && height < heightsTable[i + 1] {
break
}
}
tableLastIndex = i
return tableLastIndex
}
func update (_ frameState: inout FrameState) {
frameState.fog.enabled = enabled
if !enabled {
return
}
let camera = frameState.camera!
let positionCartographic = camera.positionCartographic
// Turn off fog in space.
if positionCartographic.height > 800000.0 || frameState.mode != .scene3D {
frameState.fog.enabled = false
return
}
let height = positionCartographic.height
let i = findInterval(height)
let t = Math.clamp((height - heightsTable[i]) / (heightsTable[i + 1] - heightsTable[i]), min: 0.0, max: 1.0)
var density = Math.lerp(p: densityTable[i], q: densityTable[i + 1], time: t)
// Again, scale value to be in the range of densityTable (prevents divide by zero) and change to new range.
let startDensity = self.density * 1.0e6
let endDensity = (startDensity / tableStartDensity) * tableEndDensity
density = (density * (startDensity - endDensity)) * 1.0e-6
// Fade fog in as the camera tilts toward the horizon.
let positionNormal = camera.positionWC.normalize()
let dot = Math.clamp(camera.directionWC.dot(positionNormal), min: 0.0, max: 1.0)
density *= 1.0 - dot
frameState.fog.density = density
frameState.fog.sse = screenSpaceErrorFactor
}
}
| apache-2.0 | 9bedd1518eae001be4072e463b1bae03 | 40.152778 | 270 | 0.62268 | 3.916722 | false | false | false | false |
lavenderofme/MySina | Sina/Sina/Classes/Main/BaseViewController.swift | 1 | 1422 | //
// BaseViewController.swift
// Sina
//
// Created by shasha on 15/11/9.
// Copyright © 2015年 shasha. All rights reserved.
//
import UIKit
class BaseViewController: UITableViewController {
var login: Bool = true
var visitorView: VisitorView?
override func loadView()
{
super.loadView()
login ? super.loadView() : setupVisitorView()
}
func setupVisitorView()
{
// 1.添加访客视图
visitorView = VisitorView.visitorView()
view = visitorView
// 2.监听按钮点击
visitorView?.registerButton.addTarget(self, action: Selector("registerButtonClick"), forControlEvents: UIControlEvents.TouchUpInside)
visitorView?.loginButton.addTarget(self, action: Selector("loginButtonClick"), forControlEvents: UIControlEvents.TouchUpInside)
// 3.添加导航栏按钮
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("registerButtonClick"))
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("loginButtonClick"))
}
// MARK: - 监听按钮点击
@objc private func registerButtonClick()
{
LQYLog("")
}
@objc private func loginButtonClick()
{
LQYLog("")
}
}
| apache-2.0 | 94524e0dd1a10cc36564dbe5bcc24d07 | 28.586957 | 161 | 0.661278 | 4.913357 | false | false | false | false |
ahoppen/swift | stdlib/public/Distributed/DistributedActorSystem.swift | 1 | 26627 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020-2021 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
//
//===----------------------------------------------------------------------===//
import Swift
import _Concurrency
/// A distributed actor system is what enables all functionality of distributed actors.
///
/// Distributed actors must always be associated with a concrete distributed actor system,
/// and do so by declaring a `typealias ActorSystem = ...`, or by having a module wide
/// `typealias DefaultDistributedActorSystem` declared which then applies to all distributed
/// actors that do not declare a specific type alias in their bodies.
@available(SwiftStdlib 5.7, *)
public protocol DistributedActorSystem: Sendable {
/// The identity used by actors that communicate via this transport
associatedtype ActorID: Sendable & Hashable
associatedtype InvocationEncoder: DistributedTargetInvocationEncoder
associatedtype InvocationDecoder: DistributedTargetInvocationDecoder
/// The type of the result handler which will be offered the results
/// returned by a distributed function invocation called via
/// `executeDistributedTarget`.
associatedtype ResultHandler: DistributedTargetInvocationResultHandler
/// The serialization requirement that will be applied to all distributed targets used with this system.
// TODO: constrain SerializationRequirement in typesystem to only be ok with protocol or class here
associatedtype SerializationRequirement
where SerializationRequirement == InvocationEncoder.SerializationRequirement,
SerializationRequirement == InvocationDecoder.SerializationRequirement,
SerializationRequirement == ResultHandler.SerializationRequirement
// ==== ---------------------------------------------------------------------
// - MARK: Resolving actors by identity
/// Resolve a local or remote actor address to a real actor instance, or throw if unable to.
/// The returned value is either a local actor or proxy to a remote actor.
///
/// Resolving an actor is called when a specific distributed actors `init(from:)`
/// decoding initializer is invoked. Once the actor's identity is deserialized
/// using the `decodeIdentity(from:)` call, it is fed into this function, which
/// is responsible for resolving the identity to a remote or local actor reference.
///
/// If the resolve fails, meaning that it cannot locate a local actor managed for
/// this identity, managed by this transport, nor can a remote actor reference
/// be created for this identity on this transport, then this function must throw.
///
/// If this function returns correctly, the returned actor reference is immediately
/// usable. It may not necessarily imply the strict *existence* of a remote actor
/// the identity was pointing towards, e.g. when a remote system allocates actors
/// lazily as they are first time messaged to, however this should not be a concern
/// of the sending side.
///
/// Detecting liveness of such remote actors shall be offered / by transport libraries
/// by other means, such as "watching an actor for termination" or similar.
func resolve<Act>(id: ActorID, as actorType: Act.Type) throws -> Act?
where Act: DistributedActor,
Act.ID == ActorID
// ==== ---------------------------------------------------------------------
// - MARK: Actor Lifecycle
/// Create an `ActorID` for the passed actor type.
///
/// This function is invoked by an distributed actor during its initialization,
/// and the returned address value is stored along with it for the time of its
/// lifetime.
///
/// The address MUST uniquely identify the actor, and allow resolving it.
/// E.g. if an actor is created under address `addr1` then immediately invoking
/// `system.resolve(id: addr1, as: Greeter.self)` MUST return a reference
/// to the same actor.
func assignID<Act>(_ actorType: Act.Type) -> ActorID
where Act: DistributedActor,
Act.ID == ActorID
/// Invoked during a distributed actor's initialization, as soon as it becomes fully initialized.
///
/// The system is expected to store the reference to this actor, and maintain an `ActorID: DistributedActor`
/// mapping for the purpose of implementing the `resolve(id:as:)` method.
///
/// The system usually should NOT retain the passed reference, and it will be informed via
/// `resignID(_:)` when the actor has been deallocated so it can remove the stale reference from its
/// internal `ActorID: DistributedActor` mapping.
///
/// The `actor.id` of the passed actor must be an `ActorID` that this system previously has assigned.
///
/// If `actorReady` gets called with some unknown ID, it should crash immediately as it signifies some
/// very unexpected use of the system.
///
/// - Parameter actor: reference to the (local) actor that was just fully initialized.
func actorReady<Act>(_ actor: Act)
where Act: DistributedActor,
Act.ID == ActorID
/// Called during when a distributed actor is deinitialized, or fails to initialize completely (e.g. by throwing
/// out of an `init` that did not completely initialize all of the actors stored properties yet).
///
/// This method is guaranteed to be called at-most-once for a given id (assuming IDs are unique,
/// and not re-cycled by the system), i.e. if it is called during a failure to initialize completely,
/// the call from the actor's deinitializer will not happen (as under these circumstances, `deinit` will be run).
///
/// If `resignID` gets called with some unknown ID, it should crash immediately as it signifies some
/// very unexpected use of the system.
///
/// - Parameter id: the id of an actor managed by this system that has begun its `deinit`.
func resignID(_ id: ActorID)
// ==== ---------------------------------------------------------------------
// - MARK: Remote Method Invocations
/// Invoked by the Swift runtime when a distributed remote call is about to be made.
///
/// The returned `DistributedTargetInvocation` will be populated with all
/// arguments, generic substitutions, and specific error and return types
/// that are associated with this specific invocation.
func makeInvocationEncoder() -> InvocationEncoder
// /// Invoked by the Swift runtime when making a remote call.
// ///
// /// The `arguments` are the arguments container that was previously created
// /// by `makeInvocationEncoder` and has been populated with all arguments.
// ///
// /// This method should perform the actual remote function call, and await for its response.
// ///
// /// ## Errors
// /// This method is allowed to throw because of underlying transport or serialization errors,
// /// as well as by re-throwing the error received from the remote callee (if able to).
// func remoteCall<Act, Err, Res>(
// on actor: Act,
// target: RemoteCallTarget,
// invocation: inout InvocationEncoder,
// throwing: Err.Type,
// returning: Res.Type
// ) async throws -> Res
// where Act: DistributedActor,
// Act.ID == ActorID,
// Err: Error,
// Res: SerializationRequirement
// /// Invoked by the Swift runtime when making a remote call.
// ///
// /// The `arguments` are the arguments container that was previously created
// /// by `makeInvocationEncoder` and has been populated with all arguments.
// ///
// /// This method should perform the actual remote function call, and await for its response.
// ///
// /// ## Errors
// /// This method is allowed to throw because of underlying transport or serialization errors,
// /// as well as by re-throwing the error received from the remote callee (if able to).
// func remoteCallVoid<Act, Err>(
// on actor: Act,
// target: RemoteCallTarget,
// invocation: inout InvocationEncoder,
// throwing: Err.Type
// ) async throws -> Res
// where Act: DistributedActor,
// Act.ID == ActorID,
// Err: Error
/// Implementation synthesized by the compiler.
/// Not intended to be invoked explicitly from user code!
//
// Implementation notes:
// The `metatype` must be the type of `Value`, and it must conform to
// `SerializationRequirement`. If it does not, the method will crash at
// runtime. This is because we cannot express
// `Value: SerializationRequirement`, however the generic `Value` is still
// useful since it allows us to avoid boxing the value into an existential,
// before we'd right away unbox it as first thing in the implementation of
// this function.
func invokeHandlerOnReturn(
handler: ResultHandler,
resultBuffer: UnsafeRawPointer,
metatype: Any.Type
) async throws
}
// ==== ----------------------------------------------------------------------------------------------------------------
// MARK: Execute Distributed Methods
@available(SwiftStdlib 5.7, *)
extension DistributedActorSystem {
/// Prepare and execute a call to the distributed function identified by the passed arguments,
/// on the passed `actor`, and collect its results using the `ResultHandler`.
///
/// This method encapsulates multiple steps that are invoked in executing a distributed function,
/// into one very efficient implementation. The steps involved are:
///
/// - looking up the distributed function based on its name
/// - decoding, in an efficient manner, all arguments from the `Args` container into a well-typed representation
/// - using that representation to perform the call on the target method
///
/// The reason for this API using a `ResultHandler` rather than returning values directly,
/// is that thanks to this approach it can avoid any existential boxing, and can serve the most
/// latency sensitive-use-cases.
///
/// - Parameters:
/// - actor: actor on which the remote call should invoke the target
/// - target: the target (method) identifier that should be invoked
/// - invocationDecoder: used to obtain all arguments to be used to perform
/// the target invocation
/// - handler: used to provide a type-safe way for library code to handle
/// the values returned by the target invocation.
/// - Throws: if the target location, invocation argument decoding, or
/// some other mismatch between them happens. In general, this
/// method is allowed to throw in any situation that might otherwise
/// result in an illegal or unexpected invocation being performed.
public func executeDistributedTarget<Act>(
on actor: Act,
target: RemoteCallTarget,
invocationDecoder: inout InvocationDecoder,
handler: Self.ResultHandler
) async throws where Act: DistributedActor {
// NOTE: Implementation could be made more efficient because we still risk
// demangling a RemoteCallTarget identity (if it is a mangled name) multiple
// times. We would prefer to store if it is a mangled name, demangle, and
// always refer to that demangled repr perhaps? We do cache the resulting
// pretty formatted name of the call target, but perhaps we can do better.
// Get the expected parameter count of the func
let targetName = target.identifier
let nameUTF8 = Array(targetName.utf8)
// Gen the generic environment (if any) associated with the target.
let genericEnv = nameUTF8.withUnsafeBufferPointer { nameUTF8 in
_getGenericEnvironmentOfDistributedTarget(nameUTF8.baseAddress!,
UInt(nameUTF8.endIndex))
}
var substitutionsBuffer: UnsafeMutablePointer<Any.Type>? = nil
var witnessTablesBuffer: UnsafeRawPointer? = nil
var numWitnessTables: Int = 0
defer {
substitutionsBuffer?.deallocate()
witnessTablesBuffer?.deallocate()
}
if let genericEnv = genericEnv {
let subs = try invocationDecoder.decodeGenericSubstitutions()
if subs.isEmpty {
throw ExecuteDistributedTargetError(
message: "Cannot call generic method without generic argument substitutions")
}
substitutionsBuffer = .allocate(capacity: subs.count)
for (offset, substitution) in subs.enumerated() {
let element = substitutionsBuffer?.advanced(by: offset)
element?.initialize(to: substitution)
}
(witnessTablesBuffer, numWitnessTables) = _getWitnessTablesFor(environment: genericEnv,
genericArguments: substitutionsBuffer!)
if numWitnessTables < 0 {
throw ExecuteDistributedTargetError(
message: "Generic substitutions \(subs) do not satisfy generic requirements of \(target) (\(targetName))")
}
}
let paramCount = nameUTF8.withUnsafeBufferPointer { nameUTF8 in
__getParameterCount(nameUTF8.baseAddress!, UInt(nameUTF8.endIndex))
}
guard paramCount >= 0 else {
throw ExecuteDistributedTargetError(
message: """
Failed to decode distributed invocation target expected parameter count,
error code: \(paramCount)
mangled name: \(targetName)
""")
}
// Prepare buffer for the parameter types to be decoded into:
let argumentTypesBuffer = UnsafeMutableBufferPointer<Any.Type>.allocate(capacity: Int(paramCount))
defer {
argumentTypesBuffer.deallocate()
}
// Demangle and write all parameter types into the prepared buffer
let decodedNum = nameUTF8.withUnsafeBufferPointer { nameUTF8 in
__getParameterTypeInfo(
nameUTF8.baseAddress!, UInt(nameUTF8.endIndex),
genericEnv,
substitutionsBuffer,
argumentTypesBuffer.baseAddress!._rawValue, Int(paramCount))
}
// Fail if the decoded parameter types count seems off and fishy
guard decodedNum == paramCount else {
throw ExecuteDistributedTargetError(
message: """
Failed to decode the expected number of params of distributed invocation target, error code: \(decodedNum)
(decoded: \(decodedNum), expected params: \(paramCount)
mangled name: \(targetName)
""")
}
// Copy the types from the buffer into a Swift Array
var argumentTypes: [Any.Type] = []
do {
argumentTypes.reserveCapacity(Int(decodedNum))
for argumentType in argumentTypesBuffer {
argumentTypes.append(argumentType)
}
}
// Decode the return type
func allocateReturnTypeBuffer<R>(_: R.Type) -> UnsafeRawPointer? {
return UnsafeRawPointer(UnsafeMutablePointer<R>.allocate(capacity: 1))
}
guard let returnTypeFromTypeInfo: Any.Type = _getReturnTypeInfo(mangledMethodName: targetName,
genericEnv: genericEnv,
genericArguments: substitutionsBuffer) else {
throw ExecuteDistributedTargetError(
message: "Failed to decode distributed target return type")
}
guard let resultBuffer = _openExistential(returnTypeFromTypeInfo, do: allocateReturnTypeBuffer) else {
throw ExecuteDistributedTargetError(
message: "Failed to allocate buffer for distributed target return type")
}
func destroyReturnTypeBuffer<R>(_: R.Type) {
resultBuffer.assumingMemoryBound(to: R.self).deallocate()
}
defer {
_openExistential(returnTypeFromTypeInfo, do: destroyReturnTypeBuffer)
}
do {
let returnType = try invocationDecoder.decodeReturnType() ?? returnTypeFromTypeInfo
// let errorType = try invocationDecoder.decodeErrorType() // TODO(distributed): decide how to use?
// Execute the target!
try await _executeDistributedTarget(
on: actor,
targetName, UInt(targetName.count),
argumentDecoder: &invocationDecoder,
argumentTypes: argumentTypesBuffer.baseAddress!._rawValue,
resultBuffer: resultBuffer._rawValue,
substitutions: UnsafeRawPointer(substitutionsBuffer),
witnessTables: witnessTablesBuffer,
numWitnessTables: UInt(numWitnessTables)
)
if returnType == Void.self {
try await handler.onReturnVoid()
} else {
try await self.invokeHandlerOnReturn(
handler: handler,
resultBuffer: resultBuffer,
metatype: returnType
)
}
} catch {
try await handler.onThrow(error: error)
}
}
}
/// Represents a 'target' of a distributed call, such as a `distributed func` or
/// `distributed` computed property. Identification schemes may vary between
/// systems, and are subject to evolution.
///
/// Actor systems generally should treat the `identifier` as an opaque string,
/// and pass it along to the remote system for in their `remoteCall`
/// implementation. Alternative approaches are possible, where the identifiers
/// are either compressed, cached, or represented in other ways, as long as the
/// recipient system is able to determine which target was intended to be
/// invoked.
///
/// The string representation will attempt to pretty print the target identifier,
/// however its exact format is not specified and may change in future versions.
@available(SwiftStdlib 5.7, *)
public struct RemoteCallTarget: CustomStringConvertible, Hashable {
private let _identifier: String
public init(_ identifier: String) {
self._identifier = identifier
}
/// The underlying identifier of the target, returned as-is.
public var identifier: String {
return _identifier
}
/// Attempts to pretty format the underlying target identifier.
/// If unable to, returns the raw underlying identifier.
public var description: String {
if let name = _getFunctionFullNameFromMangledName(mangledName: _identifier) {
return name
} else {
return "\(_identifier)"
}
}
}
@available(SwiftStdlib 5.7, *)
@_silgen_name("swift_distributed_execute_target")
func _executeDistributedTarget<D: DistributedTargetInvocationDecoder>(
on actor: AnyObject, // DistributedActor
_ targetName: UnsafePointer<UInt8>, _ targetNameLength: UInt,
argumentDecoder: inout D,
argumentTypes: Builtin.RawPointer,
resultBuffer: Builtin.RawPointer,
substitutions: UnsafeRawPointer?,
witnessTables: UnsafeRawPointer?,
numWitnessTables: UInt
) async throws
/// Used to encode an invocation of a distributed target (method or computed property).
///
/// ## Forming an invocation
///
/// On the sending-side an instance of an invocation is constructed by the runtime,
/// and calls to: `recordGenericSubstitution`, `recordArgument`, `recordReturnType`,
/// `recordErrorType`, and finally `doneRecording` are made (in this order).
///
/// If the return type of the target is `Void` the `recordReturnType` is not invoked.
///
/// If the error type thrown by the target is not defined the `recordErrorType` is not invoked.
///
/// An invocation implementation may decide to perform serialization right-away in the
/// `record...` invocations, or it may choose to delay doing so until the invocation is passed
/// to the `remoteCall`. This decision largely depends on if serialization is allowed to happen
/// on the caller's task, and if any smarter encoding can be used once all parameter calls have been
/// recorded (e.g. it may be possible to run-length encode values of certain types etc.)
///
/// Once encoded, the system should use some underlying transport mechanism to send the
/// bytes serialized by the invocation to the remote peer.
///
/// ## Decoding an invocation
/// Since every actor system is going to deal with a concrete invocation type, they may
/// implement decoding them whichever way is most optimal for the given system.
///
/// Once decided, the invocation must be passed to `executeDistributedTarget`
/// which will decode the substitutions, argument values, return and error types (in that order).
///
/// Note that the decoding will be provided the specific types that the sending side used to preform the call,
/// so decoding can rely on simply invoking e.g. `Codable` (if that is the `SerializationRequirement`) decoding
/// entry points on the provided types.
@available(SwiftStdlib 5.7, *)
public protocol DistributedTargetInvocationEncoder {
associatedtype SerializationRequirement
/// The arguments must be encoded order-preserving, and once `decodeGenericSubstitutions`
/// is called, the substitutions must be returned in the same order in which they were recorded.
mutating func recordGenericSubstitution<T>(_ type: T.Type) throws
// /// Ad-hoc requirement
// ///
// /// Record an argument of `Argument` type.
// /// This will be invoked for every argument of the target, in declaration order.
// mutating func recordArgument<Value: SerializationRequirement>(
// _ argument: DistributedTargetArgument<Value>
// ) throws
/// Record the error type of the distributed method.
/// This method will not be invoked if the target is not throwing.
mutating func recordErrorType<E: Error>(_ type: E.Type) throws
// /// Ad-hoc requirement
// ///
// /// Record the return type of the distributed method.
// /// This method will not be invoked if the target is returning `Void`.
// mutating func recordReturnType<R: SerializationRequirement>(_ type: R.Type) throws
mutating func doneRecording() throws
}
/// Represents an argument passed to a distributed call target.
@available(SwiftStdlib 5.7, *)
public struct RemoteCallArgument<Value> {
/// The "argument label" of the argument.
/// The label is the name visible name used in external calls made to this
/// target, e.g. for `func hello(label name: String)` it is `label`.
///
/// If no label is specified (i.e. `func hi(name: String)`), the `label`,
/// value is empty, however `effectiveLabel` is equal to the `name`.
///
/// In most situations, using `effectiveLabel` is more useful to identify
/// the user-visible name of this argument.
public let label: String?
/// The effective label of this argument, i.e. if no explicit `label` was set
/// this defaults to the `name`. This reflects the semantics of call sites of
/// function declarations without explicit label definitions in Swift.
public var effectiveLabel: String {
return label ?? name
}
/// The internal name of parameter this argument is accessible as in the
/// function body. It is not part of the functions API and may change without
/// breaking the target identifier.
///
/// If the method did not declare an explicit `label`, it is used as the
/// `effectiveLabel`.
public let name: String
/// The value of the argument being passed to the call.
/// As `RemoteCallArgument` is always used in conjunction with
/// `recordArgument` and populated by the compiler, this Value will generally
/// conform to a distributed actor system's `SerializationRequirement`.
public let value: Value
public init(label: String?, name: String, value: Value) {
self.label = label
self.name = name
self.value = value
}
}
/// Decoder that must be provided to `executeDistributedTarget` and is used
/// by the Swift runtime to decode arguments of the invocation.
@available(SwiftStdlib 5.7, *)
public protocol DistributedTargetInvocationDecoder {
associatedtype SerializationRequirement
mutating func decodeGenericSubstitutions() throws -> [Any.Type]
// /// Ad-hoc protocol requirement
// ///
// /// Attempt to decode the next argument from the underlying buffers into pre-allocated storage
// /// pointed at by 'pointer'.
// ///
// /// This method should throw if it has no more arguments available, if decoding the argument failed,
// /// or, optionally, if the argument type we're trying to decode does not match the stored type.
// ///
// /// The result of the decoding operation must be stored into the provided 'pointer' rather than
// /// returning a value. This pattern allows the runtime to use a heavily optimized, pre-allocated
// /// buffer for all the arguments and their expected types. The 'pointer' passed here is a pointer
// /// to a "slot" in that pre-allocated buffer. That buffer will then be passed to a thunk that
// /// performs the actual distributed (local) instance method invocation.
// mutating func decodeNextArgument<Argument: SerializationRequirement>() throws -> Argument
mutating func decodeErrorType() throws -> Any.Type?
/// Attempt to decode the known return type of the distributed invocation.
///
/// It is legal to implement this by returning `nil`, and then the system
/// will take the concrete return type from the located function signature.
mutating func decodeReturnType() throws -> Any.Type?
}
@available(SwiftStdlib 5.7, *)
public protocol DistributedTargetInvocationResultHandler {
associatedtype SerializationRequirement
// func onReturn<Success: SerializationRequirement>(value: Success) async throws
/// Invoked when the distributed target invocation of a `Void` returning
/// function has completed successfully.
func onReturnVoid() async throws
func onThrow<Err: Error>(error: Err) async throws
}
/******************************************************************************/
/******************************** Errors **************************************/
/******************************************************************************/
/// Error protocol to which errors thrown by any `DistributedActorSystem` should conform.
@available(SwiftStdlib 5.7, *)
public protocol DistributedActorSystemError: Error {}
@available(SwiftStdlib 5.7, *)
public struct ExecuteDistributedTargetError: DistributedActorSystemError {
let message: String
public init(message: String) {
self.message = message
}
}
@available(SwiftStdlib 5.7, *)
public struct DistributedActorCodingError: DistributedActorSystemError {
public let message: String
public init(message: String) {
self.message = message
}
public static func missingActorSystemUserInfo<Act>(_ actorType: Act.Type) -> Self
where Act: DistributedActor {
.init(message: "Missing DistributedActorSystem userInfo while decoding")
}
}
| apache-2.0 | 621a459130b85cba1e3bd9382a924d6b | 43.676174 | 123 | 0.691516 | 4.840393 | false | false | false | false |
argon/mas | MasKitTests/OutputListener.swift | 1 | 2884 | //
// OutputListener.swift
// MasKitTests
//
// Created by Ben Chatelain on 1/7/19.
// Copyright © 2019 mas-cli. All rights reserved.
//
import Foundation
/// Test helper for monitoring strings written to stdout. Modified from:
/// https://medium.com/@thesaadismail/eavesdropping-on-swifts-print-statements-57f0215efb42
class OutputListener {
/// consumes the messages on STDOUT
let inputPipe = Pipe()
/// outputs messages back to STDOUT
let outputPipe = Pipe()
/// Buffers strings written to stdout
var contents = ""
init() {
// Set up a read handler which fires when data is written to our inputPipe
inputPipe.fileHandleForReading.readabilityHandler = { [weak self] fileHandle in
strongify(self) { context in
let data = fileHandle.availableData
if let string = String(data: data, encoding: String.Encoding.utf8) {
context.contents += string
}
// Write input back to stdout
context.outputPipe.fileHandleForWriting.write(data)
}
}
}
}
extension OutputListener {
/// Sets up the "tee" of piped output, intercepting stdout then passing it through.
///
/// ## [dup2 documentation](https://linux.die.net/man/2/dup2)
/// `int dup2(int oldfd, int newfd);`
/// `dup2()` makes `newfd` be the copy of `oldfd`, closing `newfd` first if necessary.
func openConsolePipe() {
var dupStatus: Int32
// Copy STDOUT file descriptor to outputPipe for writing strings back to STDOUT
dupStatus = dup2(stdoutFileDescriptor, outputPipe.fileHandleForWriting.fileDescriptor)
// Status should equal newfd
assert(dupStatus == outputPipe.fileHandleForWriting.fileDescriptor)
// Intercept STDOUT with inputPipe
// newFileDescriptor is the pipe's file descriptor and the old file descriptor is STDOUT_FILENO
dupStatus = dup2(inputPipe.fileHandleForWriting.fileDescriptor, stdoutFileDescriptor)
// Status should equal newfd
assert(dupStatus == stdoutFileDescriptor)
// Don't have any tests on stderr yet
// dup2(inputPipe.fileHandleForWriting.fileDescriptor, stderr)
}
/// Tears down the "tee" of piped output.
func closeConsolePipe() {
// Restore stdout
freopen("/dev/stdout", "a", stdout)
[inputPipe.fileHandleForReading, outputPipe.fileHandleForWriting].forEach { file in
file.closeFile()
}
}
}
extension OutputListener {
/// File descriptor for stdout (aka STDOUT_FILENO)
var stdoutFileDescriptor: Int32 {
return FileHandle.standardOutput.fileDescriptor
}
/// File descriptor for stderr (aka STDERR_FILENO)
var stderrFileDescriptor: Int32 {
return FileHandle.standardError.fileDescriptor
}
}
| mit | b5c0df62b25c41de2b1f1f8f17333b2f | 33.321429 | 103 | 0.66077 | 4.642512 | false | false | false | false |
ontouchstart/swift3-playground | Graphing.playgroundbook/Contents/Sources/PlaygroundAPI/Symbol.swift | 1 | 4548 | //
// Symbol.swift
// Charts
//
// Created by Ken Orr on 6/29/16.
// Copyright © 2016 Ken Orr. All rights reserved.
//
import UIKit
/// Types of shapes that can be used to create Symbols.
public enum SymbolShape: Int {
case circle = 0
case square = 1
case triangle = 2
}
/// A symbol used for representing a point on screen.
public class Symbol {
private let symbolDrawable: SymbolDrawable
internal let size: Double
/// Creates a shape-based symbol.
/// - `shape` The type of shape. Defaults to .circle.
/// - `size` The size of the shape. Defaults to 8.0.
public init(shape: SymbolShape = .circle, size: Double = 8.0) {
symbolDrawable = ShapeSymbolDrawable(shape: shape, size: size)
self.size = size
}
/// Creates an image-based symbol.
/// - `imageName` The name of the image in this playgrounds resources.
/// - `size` The size of the image. Defaults to 32.0.
public init(imageNamed imageName: String, size: Double = 32.0) {
symbolDrawable = ImageSymbolDrawable(imageNamed: imageName, size: size)
self.size = size
}
internal func draw(atCenterPoint point: CGPoint, fillColor: UIColor, usingContext context: CGContext) {
symbolDrawable.draw(atCenterPoint: point, fillColor: fillColor, usingContext: context)
}
}
private protocol SymbolDrawable {
func draw(atCenterPoint point: CGPoint, fillColor: UIColor, usingContext context: CGContext)
}
private class ShapeSymbolDrawable: SymbolDrawable {
private var fillColor = Color.blue.uiColor
private let size: Double
private let shape: SymbolShape
private var pathImage: UIImage?
private init(shape: SymbolShape, size: Double) {
self.shape = shape
self.size = size
updatePathImage()
}
private func updatePathImage() {
let rect = CGRect(x: 0, y: 0, width: CGFloat(size), height: CGFloat(size))
let path: UIBezierPath
switch shape {
case .circle:
path = UIBezierPath(ovalIn: rect)
case .square:
path = UIBezierPath(rect: rect)
case .triangle:
path = UIBezierPath()
path.move(to: CGPoint(x: rect.minX, y: rect.maxY))
path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
path.addLine(to: CGPoint(x: rect.midX, y: rect.minY))
path.close()
path.lineJoinStyle = .miter
}
UIGraphicsBeginImageContextWithOptions(CGSize(width: size, height: size), false, 0.0)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(fillColor.cgColor)
path.fill()
pathImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
func draw(atCenterPoint point: CGPoint, fillColor: UIColor, usingContext context: CGContext) {
if (self.fillColor != fillColor) {
self.fillColor = fillColor
updatePathImage()
}
let sizeAsFloat = CGFloat(size)
let x = point.x - sizeAsFloat/2.0
let y = point.y - sizeAsFloat/2.0
let rect = CGRect(x: x, y: y, width: sizeAsFloat, height: sizeAsFloat)
pathImage?.draw(in: rect)
}
}
private class ImageSymbolDrawable: SymbolDrawable {
private let uiImage: UIImage
private let size: Double
init(imageNamed imageName: String, size: Double) {
if let uiImage = UIImage(named: imageName) {
self.uiImage = uiImage
self.size = size
} else {
self.uiImage = #imageLiteral(resourceName: "QuestionMark")
self.size = 24.0
}
}
func draw(atCenterPoint point: CGPoint, fillColor: UIColor, usingContext context: CGContext) {
let imageWidth = uiImage.size.width
let imageHeight = uiImage.size.height
let sizeAsFloat = CGFloat(size)
let widthGreaterThanHeight = uiImage.size.width > uiImage.size.height
let width = widthGreaterThanHeight ? sizeAsFloat : sizeAsFloat * (imageWidth/imageHeight)
let height = widthGreaterThanHeight ? sizeAsFloat * (imageHeight/imageWidth) : sizeAsFloat
let x = point.x - width/2.0
let y = point.y - height/2.0
let rect = CGRect(x: x, y: y, width: width, height: height)
uiImage.draw(in: rect)
}
}
| mit | 112bc9cac7d3897209bba22e46965641 | 30.143836 | 107 | 0.612712 | 4.397485 | false | false | false | false |
codeliling/HXDYWH | dywh/dywh/controllers/ArticleDetailViewController.swift | 1 | 3927 | //
// ArticleDetailViewController.swift
// dywh
//
// Created by lotusprize on 15/5/22.
// Copyright (c) 2015年 geekTeam. All rights reserved.
//
import UIKit
import Haneke
class ArticleDetailViewController: HXWHViewController,UIWebViewDelegate ,UIGestureRecognizerDelegate,UINavigationControllerDelegate,UMSocialUIDelegate{
@IBOutlet weak var webView: UIWebView!
var shareUrl:String!
var articleModel:ArticleModel!
let cache = Shared.imageCache
var image:UIImage?
@IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
var rightButton:UIButton = UIButton(frame: CGRectMake(0, 0, 35, 35))
rightButton.setImage(UIImage(named: "shareIconWhite"), forState: UIControlState.Normal)
rightButton.addTarget(self, action: "shareBtnClick:", forControlEvents: UIControlEvents.TouchUpInside)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView:rightButton)
self.navigationController?.interactivePopGestureRecognizer.enabled = true
webView.delegate = self
let URL = NSURL(string: articleModel.articleImageUrl!)!
let fetcher = NetworkFetcher<UIImage>(URL: URL)
cache.fetch(fetcher: fetcher).onSuccess { image in
// Do something with image
self.image = image
}
self.automaticallyAdjustsScrollViewInsets = false
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.tabBarController?.tabBar.hidden = true
shareUrl = ServerUrl.ServerArticleDetailURL + String(articleModel.articleId)
webView.loadRequest(NSURLRequest(URL:NSURL(string: shareUrl)!))
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.tabBarController?.tabBar.hidden = false
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError) {
activityIndicatorView.stopAnimating()
}
func webViewDidStartLoad(webView: UIWebView) {
activityIndicatorView.hidden = false
activityIndicatorView.startAnimating()
}
func webViewDidFinishLoad(webView: UIWebView) {
activityIndicatorView.stopAnimating()
activityIndicatorView.hidden = true
}
func shareBtnClick(rightButton:UIButton){
println("share content click")
UMSocialSnsService.presentSnsIconSheetView(self, appKey: "556a5c3e67e58e57a3003c8a", shareText: self.articleModel.articleName, shareImage: image, shareToSnsNames: [UMShareToQzone,UMShareToTencent,UMShareToQQ,UMShareToSms,UMShareToWechatFavorite,UMShareToWechatSession,UMShareToWechatTimeline], delegate: self)
UMSocialData.defaultData().extConfig.wechatSessionData.url = self.shareUrl
UMSocialData.defaultData().extConfig.wechatTimelineData.url = self.shareUrl
UMSocialData.defaultData().extConfig.wechatFavoriteData.url = self.shareUrl
UMSocialData.defaultData().extConfig.qqData.url = self.shareUrl
UMSocialData.defaultData().extConfig.qzoneData.url = self.shareUrl
}
func didFinishGetUMSocialDataInViewController(response: UMSocialResponseEntity!) {
println(response.responseCode)
}
func isDirectShareInIconActionSheet() -> Bool {
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | a38b9e310a27f477f59808295a78231d | 35.342593 | 317 | 0.703439 | 5.24032 | false | false | false | false |
rnystrom/GitHawk | Classes/Milestones/GithubClient+Milestones.swift | 1 | 3306 | //
// GithubClient+Milestones.swift
// Freetime
//
// Created by Ryan Nystrom on 11/15/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import Foundation
import Squawk
import GitHubAPI
extension GithubClient {
func fetchMilestones(
owner: String,
repo: String,
completion: @escaping (Result<[Milestone]>) -> Void
) {
client.send(V3MilestoneRequest(owner: owner, repo: repo)) { result in
switch result {
case .success(let response):
let milestones = response.data.sorted { lhs, rhs in
switch (lhs.dueOn, rhs.dueOn) {
case (let lhsDue?, let rhsDue?):
return lhsDue.compare(rhsDue) == .orderedAscending
case (_?, nil):
return true
case (nil, _?):
return false
default:
return lhs.title < rhs.title
}
}
completion(.success(milestones.map {
Milestone(
number: $0.number,
title: $0.title,
dueOn: $0.dueOn,
openIssueCount: $0.openIssues,
totalIssueCount: $0.openIssues + $0.closedIssues
)
}))
case .failure(let error):
completion(.error(error))
}
}
}
func setMilestone(
previous: IssueResult,
owner: String,
repo: String,
number: Int,
milestone: Milestone?
) {
guard milestone != previous.milestone else { return }
let eventTitle: String
let type: IssueMilestoneEventModel.MilestoneType
if let milestone = milestone {
type = .milestoned
eventTitle = milestone.title
} else {
// if removing milestone and there was no previous, just return
guard let previousMilestone = previous.milestone else { return }
eventTitle = previousMilestone.title
type = .demilestoned
}
let newEvent = IssueMilestoneEventModel(
id: UUID().uuidString,
actor: userSession?.username ?? Constants.Strings.unknown,
milestone: eventTitle,
date: Date(),
type: type,
contentSizeCategory: UIContentSizeCategory.preferred,
width: 0 // pay perf cost when asked
)
let optimisticResult = previous.withMilestone(
milestone,
timelinePages: previous.timelinePages(appending: [newEvent])
)
let cache = self.cache
// optimistically update the cache, listeners can react as appropriate
cache.set(value: optimisticResult)
client.send(V3SetMilestonesRequest(
owner: owner,
repo: repo,
number: number,
milestoneNumber: milestone?.number)
) { result in
switch result {
case .success: break
case .failure(let error):
cache.set(value: previous)
Squawk.show(error: error)
}
}
}
}
| mit | 86284b5aca8c398e08d3c9e9a88cf159 | 29.88785 | 78 | 0.514372 | 5.221169 | false | false | false | false |
li13418801337/DouyuTV | DouyuZB/DouyuZB/Classes/Main/PageContentView.swift | 1 | 5496 | //
// PageContentView.swift
// DouyuZB
//
// Created by work on 16/10/20.
// Copyright © 2016年 xiaosi. All rights reserved.
//
import UIKit
protocol PageContentViewDelegate : class {
func pageContentView(contentView : PageContentView , progress : CGFloat, sourceIndex : Int, targetIndex : Int)
}
private let ContentCellID = "ContentwCellID"
class PageContentView: UIView {
//定义属性
private var childVcs : [UIViewController]
private weak var parentViewController : UIViewController?
private var startOffsetX : CGFloat = 0
private var isForbidScrollDelegate = false
weak var delegate : PageContentViewDelegate?
//懒加载属性CollectionView
private lazy var collectionView : UICollectionView = {[weak self]in
//创建layout
let layout = UICollectionViewFlowLayout()
layout.itemSize = (self?.bounds.size)!
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .Horizontal
//创建UICollectionView
let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
collectionView.showsVerticalScrollIndicator = false
collectionView.pagingEnabled = true
collectionView.bounces = false
collectionView.dataSource = self
collectionView.delegate = self
collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellID)
return collectionView
}()
//自定义构造函数
init(frame: CGRect, chidlVcs : [UIViewController], parentViewController : UIViewController?) {
self.childVcs = chidlVcs
self.parentViewController = parentViewController
super.init(frame:frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//设置UI界面
extension PageContentView{
private func setupUI(){
//将所有字控制器添加到父控制器中
for childVc in childVcs {
parentViewController?.addChildViewController(childVc)
}
//添加uicollectionview
addSubview(collectionView)
collectionView.frame = bounds
}
}
//遵守数据源
extension PageContentView : UICollectionViewDataSource{
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVcs.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ContentCellID, forIndexPath: indexPath)
for view in cell.contentView.subviews{
view.removeFromSuperview()
}
let childVc = childVcs[indexPath.item]
childVc.view.frame = cell.contentView.bounds
cell.contentView.addSubview(childVc.view)
return cell
}
}
//遵守代理
extension PageContentView : UICollectionViewDelegate{
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
isForbidScrollDelegate = false
startOffsetX = scrollView.contentOffset.x
}
func scrollViewDidScroll(scrollView: UIScrollView) {
if isForbidScrollDelegate {return}
// 获取数据
//滑动的比例
var progress : CGFloat = 0
//当前的index
var sourceIndex : Int = 0
//目标的index?
var targetIndex : Int = 0
// 判断左滑还是右滑
let currentOffsetX = scrollView.contentOffset.x
let scrollViewW = scrollView.bounds.width
if currentOffsetX > startOffsetX{
//左滑
progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)
sourceIndex = Int(currentOffsetX / scrollViewW)
targetIndex = sourceIndex + 1
if targetIndex >= childVcs.count {
targetIndex = childVcs.count - 1
}
//如果完全滑过去
if currentOffsetX - startOffsetX == scrollViewW {
progress = 1
targetIndex = sourceIndex
}
}else{
//右滑
progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW))
targetIndex = Int(currentOffsetX / scrollViewW)
sourceIndex = targetIndex + 1
if sourceIndex >= childVcs.count {
sourceIndex = childVcs.count - 1
}
}
//将3个属性传递给titleview
// print("progress:\(progress) sourceIndex:\(sourceIndex) targetIndex:\(targetIndex)")
delegate!.pageContentView(self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
//对外暴露的方法
extension PageContentView{
func setCurrentIndex(currentIndex : Int){
isForbidScrollDelegate = true
let offsetX = CGFloat(currentIndex) * collectionView.frame.width
collectionView.setContentOffset(CGPoint(x:offsetX,y:0), animated: false)
}
}
| mit | 35b576e089e50367c5e72209f733cc14 | 26.578125 | 130 | 0.620208 | 6.128472 | false | false | false | false |
jmcd/AvoidMegaController | DemoApp/TodoListViewController.swift | 1 | 1357 | import UIKit
protocol TodoTableViewDataSource: UITableViewDataSource {
var onChange: (() -> ()) { get set }
func itemAtIndexPath(indexPath: NSIndexPath) -> TodoItem
}
class TodoListViewController: UIViewController {
static let cellReuseId = NSUUID().UUIDString
var dataSource: TodoTableViewDataSource?
var showDetail: ((TodoListViewController, TodoItem) -> ())?
private lazy var tableViewDelegate: UITableViewDelegate = {
let d = SimpleSelectableTableViewDelegate()
d.didSelectRowAtIndexPath = { _, indexPath in
if let selectedItem = self.dataSource?.itemAtIndexPath(indexPath) {
self.showDetail?(self, selectedItem)
}
}
return d
}()
private lazy var tableView: UITableView = {
let tv = UITableView()
tv.registerClass(UITableViewCell.self, forCellReuseIdentifier: TodoListViewController.cellReuseId)
tv.dataSource = self.dataSource
tv.delegate = self.tableViewDelegate
self.dataSource?.onChange = { tv.reloadData() }
return tv
}()
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
exposeNavigation()
}
override func viewDidLoad() {
automaticallyAdjustsScrollViewInsets = false
view.addSubviews([tableView])
view.addConstraints(tableView.constraintsMaximizingInView(view, topLayoutGuide: topLayoutGuide, bottomLayoutGuide: bottomLayoutGuide))
}
}
| apache-2.0 | d710f3e76d63572538024eb0366af078 | 25.607843 | 138 | 0.75608 | 4.6 | false | false | false | false |
yanyuqingshi/ios-charts | Charts/Classes/Renderers/HorizontalBarChartRenderer.swift | 1 | 19150 | //
// HorizontalBarChartRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics.CGBase
import UIKit.UIFont
public class HorizontalBarChartRenderer: BarChartRenderer
{
private var xOffset: CGFloat = 0.0;
private var yOffset: CGFloat = 0.0;
public override init(delegate: BarChartRendererDelegate?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler)
{
super.init(delegate: delegate, animator: animator, viewPortHandler: viewPortHandler);
}
internal override func drawDataSet(#context: CGContext, dataSet: BarChartDataSet, index: Int)
{
CGContextSaveGState(context);
var barData = delegate!.barChartRendererData(self);
var trans = delegate!.barChartRenderer(self, transformerForAxis: dataSet.axisDependency);
var drawBarShadowEnabled: Bool = delegate!.barChartIsDrawBarShadowEnabled(self);
var dataSetOffset = (barData.dataSetCount - 1);
var groupSpace = barData.groupSpace;
var groupSpaceHalf = groupSpace / 2.0;
var barSpace = dataSet.barSpace;
var barSpaceHalf = barSpace / 2.0;
var containsStacks = dataSet.isStacked;
var isInverted = delegate!.barChartIsInverted(self, axis: dataSet.axisDependency);
var entries = dataSet.yVals as! [BarChartDataEntry];
var barWidth: CGFloat = 0.5;
var phaseY = _animator.phaseY;
var barRect = CGRect();
var barShadow = CGRect();
var y: Double;
// do the drawing
for (var j = 0, count = Int(ceil(CGFloat(dataSet.entryCount) * _animator.phaseX)); j < count; j++)
{
var e = entries[j];
// calculate the x-position, depending on datasetcount
var x = CGFloat(e.xIndex + j * dataSetOffset) + CGFloat(index)
+ groupSpace * CGFloat(j) + groupSpaceHalf;
var vals = e.values;
if (!containsStacks || vals == nil)
{
y = e.value;
var bottom = x - barWidth + barSpaceHalf;
var top = x + barWidth - barSpaceHalf;
var right = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0);
var left = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0);
// multiply the height of the rect with the phase
if (right > 0)
{
right *= phaseY;
}
else
{
left *= phaseY;
}
barRect.origin.x = left;
barRect.size.width = right - left;
barRect.origin.y = top;
barRect.size.height = bottom - top;
trans.rectValueToPixel(&barRect);
if (!viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width))
{
continue;
}
if (!viewPortHandler.isInBoundsRight(barRect.origin.x))
{
break;
}
// if drawing the bar shadow is enabled
if (drawBarShadowEnabled)
{
barShadow.origin.x = viewPortHandler.contentLeft;
barShadow.origin.y = barRect.origin.y;
barShadow.size.width = viewPortHandler.contentWidth;
barShadow.size.height = barRect.size.height;
CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor);
CGContextFillRect(context, barShadow);
}
// Set the color for the currently drawn value. If the index is out of bounds, reuse colors.
CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor);
CGContextFillRect(context, barRect);
}
else
{
var all = e.value;
// if drawing the bar shadow is enabled
if (drawBarShadowEnabled)
{
y = e.value;
var bottom = x - barWidth + barSpaceHalf;
var top = x + barWidth - barSpaceHalf;
var right = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0);
var left = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0);
// multiply the height of the rect with the phase
if (right > 0)
{
right *= phaseY;
}
else
{
left *= phaseY;
}
barRect.origin.x = left;
barRect.size.width = right - left;
barRect.origin.y = top;
barRect.size.height = bottom - top;
trans.rectValueToPixel(&barRect);
barShadow.origin.x = viewPortHandler.contentLeft;
barShadow.origin.y = barRect.origin.y;
barShadow.size.width = viewPortHandler.contentWidth;
barShadow.size.height = barRect.size.height;
CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor);
CGContextFillRect(context, barShadow);
}
// fill the stack
for (var k = 0; k < vals.count; k++)
{
all -= vals[k];
y = vals[k] + all;
var bottom = x - barWidth + barSpaceHalf;
var top = x + barWidth - barSpaceHalf;
var right = y >= 0.0 ? CGFloat(y) : 0.0;
var left = y <= 0.0 ? CGFloat(y) : 0.0;
// multiply the height of the rect with the phase
if (right > 0)
{
right *= phaseY;
}
else
{
left *= phaseY;
}
barRect.origin.x = left;
barRect.size.width = right - left;
barRect.origin.y = top;
barRect.size.height = bottom - top;
trans.rectValueToPixel(&barRect);
if (k == 0 && !viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width))
{
// Skip to next bar
break;
}
// avoid drawing outofbounds values
if (!viewPortHandler.isInBoundsRight(barRect.origin.x))
{
break;
}
// Set the color for the currently drawn value. If the index is out of bounds, reuse colors.
CGContextSetFillColorWithColor(context, dataSet.colorAt(k).CGColor);
CGContextFillRect(context, barRect);
}
}
}
CGContextRestoreGState(context);
}
internal override func prepareBarHighlight(#x: CGFloat, y: Double, barspacehalf: CGFloat, from: Double, trans: ChartTransformer, inout rect: CGRect)
{
let barWidth: CGFloat = 0.5;
var top = x - barWidth + barspacehalf;
var bottom = x + barWidth - barspacehalf;
var left = y >= from ? CGFloat(y) : CGFloat(from);
var right = y <= from ? CGFloat(y) : CGFloat(from);
rect.origin.x = left;
rect.origin.y = top;
rect.size.width = right - left;
rect.size.height = bottom - top;
trans.rectValueToPixelHorizontal(&rect, phaseY: _animator.phaseY);
}
public override func getTransformedValues(#trans: ChartTransformer, entries: [BarChartDataEntry], dataSetIndex: Int) -> [CGPoint]
{
return trans.generateTransformedValuesHorizontalBarChart(entries, dataSet: dataSetIndex, barData: delegate!.barChartRendererData(self)!, phaseY: _animator.phaseY);
}
public override func drawValues(#context: CGContext)
{
// if values are drawn
if (passesCheck())
{
var barData = delegate!.barChartRendererData(self);
var defaultValueFormatter = delegate!.barChartDefaultRendererValueFormatter(self);
var dataSets = barData.dataSets;
var drawValueAboveBar = delegate!.barChartIsDrawValueAboveBarEnabled(self);
var drawValuesForWholeStackEnabled = delegate!.barChartIsDrawValuesForWholeStackEnabled(self);
var textAlign = drawValueAboveBar ? NSTextAlignment.Left : NSTextAlignment.Right;
let valueOffsetPlus: CGFloat = 5.0;
var posOffset: CGFloat;
var negOffset: CGFloat;
for (var i = 0, count = barData.dataSetCount; i < count; i++)
{
var dataSet = dataSets[i];
if (!dataSet.isDrawValuesEnabled)
{
continue;
}
var isInverted = delegate!.barChartIsInverted(self, axis: dataSet.axisDependency);
var valueFont = dataSet.valueFont;
var valueTextColor = dataSet.valueTextColor;
var yOffset = -valueFont.lineHeight / 2.0;
var formatter = dataSet.valueFormatter;
if (formatter === nil)
{
formatter = defaultValueFormatter;
}
var trans = delegate!.barChartRenderer(self, transformerForAxis: dataSet.axisDependency);
var entries = dataSet.yVals as! [BarChartDataEntry];
var valuePoints = getTransformedValues(trans: trans, entries: entries, dataSetIndex: i);
// if only single values are drawn (sum)
if (!drawValuesForWholeStackEnabled)
{
for (var j = 0, count = Int(ceil(CGFloat(valuePoints.count) * _animator.phaseX)); j < count; j++)
{
if (!viewPortHandler.isInBoundsX(valuePoints[j].x))
{
continue;
}
if (!viewPortHandler.isInBoundsTop(valuePoints[j].y))
{
break;
}
if (!viewPortHandler.isInBoundsBottom(valuePoints[j].y))
{
continue;
}
var val = entries[j].value;
var valueText = formatter!.stringFromNumber(val)!;
// calculate the correct offset depending on the draw position of the value
var valueTextWidth = valueText.sizeWithAttributes([NSFontAttributeName: valueFont]).width;
posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus));
negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus);
if (isInverted)
{
posOffset = -posOffset - valueTextWidth;
negOffset = -negOffset - valueTextWidth;
}
drawValue(
context: context,
value: valueText,
xPos: valuePoints[j].x + (val >= 0.0 ? posOffset : negOffset),
yPos: valuePoints[j].y + yOffset,
font: valueFont,
align: .Left,
color: valueTextColor);
}
}
else
{
// if each value of a potential stack should be drawn
for (var j = 0, count = Int(ceil(CGFloat(valuePoints.count) * _animator.phaseX)); j < count; j++)
{
var e = entries[j];
var vals = e.values;
// we still draw stacked bars, but there is one non-stacked in between
if (vals == nil)
{
if (!viewPortHandler.isInBoundsX(valuePoints[j].x))
{
continue;
}
if (!viewPortHandler.isInBoundsTop(valuePoints[j].y))
{
break;
}
if (!viewPortHandler.isInBoundsBottom(valuePoints[j].y))
{
continue;
}
var val = e.value;
var valueText = formatter!.stringFromNumber(val)!;
// calculate the correct offset depending on the draw position of the value
var valueTextWidth = valueText.sizeWithAttributes([NSFontAttributeName: valueFont]).width;
posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus));
negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus);
if (isInverted)
{
posOffset = -posOffset - valueTextWidth;
negOffset = -negOffset - valueTextWidth;
}
drawValue(
context: context,
value: valueText,
xPos: valuePoints[j].x + (val >= 0.0 ? posOffset : negOffset),
yPos: valuePoints[j].y + yOffset,
font: valueFont,
align: .Left,
color: valueTextColor);
}
else
{
var transformed = [CGPoint]();
var cnt = 0;
var add = e.value;
for (var k = 0; k < vals.count; k++)
{
add -= vals[cnt];
transformed.append(CGPoint(x: (CGFloat(vals[cnt]) + CGFloat(add)) * _animator.phaseY, y: 0.0));
cnt++;
}
trans.pointValuesToPixel(&transformed);
for (var k = 0; k < transformed.count; k++)
{
var val = vals[k];
var valueText = formatter!.stringFromNumber(val)!;
// calculate the correct offset depending on the draw position of the value
var valueTextWidth = valueText.sizeWithAttributes([NSFontAttributeName: valueFont]).width;
posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus));
negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus);
if (isInverted)
{
posOffset = -posOffset - valueTextWidth;
negOffset = -negOffset - valueTextWidth;
}
var x = transformed[k].x + (val >= 0 ? posOffset : negOffset);
var y = valuePoints[j].y;
if (!viewPortHandler.isInBoundsX(x))
{
continue;
}
if (!viewPortHandler.isInBoundsTop(y))
{
break;
}
if (!viewPortHandler.isInBoundsBottom(y))
{
continue;
}
drawValue(context: context,
value: valueText,
xPos: x,
yPos: y + yOffset,
font: valueFont,
align: .Left,
color: valueTextColor);
}
}
}
}
}
}
}
internal override func passesCheck() -> Bool
{
var barData = delegate!.barChartRendererData(self);
if (barData === nil)
{
return false;
}
return CGFloat(barData.yValCount) < CGFloat(delegate!.barChartRendererMaxVisibleValueCount(self)) * viewPortHandler.scaleY;
}
} | apache-2.0 | 764d683eca0b191655d9d4f246dffa8f | 42.328054 | 171 | 0.425796 | 6.693464 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Feature Highlight/TooltipAnchor.swift | 1 | 2569 | import UIKit
final class TooltipAnchor: UIControl {
private enum Constants {
static let horizontalMarginToBounds: CGFloat = 16
static let verticalMarginToBounds: CGFloat = 9
static let stackViewSpacing: CGFloat = 4
static let viewHeight: CGFloat = 40
}
var title: String? {
didSet {
titleLabel.text = title
accessibilityLabel = title
}
}
private lazy var titleLabel: UILabel = {
$0.textColor = .invertedLabel
$0.font = WPStyleGuide.fontForTextStyle(.body)
return $0
}(UILabel())
private lazy var highlightLabel: UILabel = {
$0.font = WPStyleGuide.fontForTextStyle(.body)
$0.text = "✨"
return $0
}(UILabel())
private lazy var stackView: UIStackView = {
$0.addArrangedSubviews([highlightLabel, titleLabel])
$0.spacing = Constants.stackViewSpacing
$0.isUserInteractionEnabled = false
return $0
}(UIStackView())
init() {
super.init(frame: .zero)
commonInit()
}
func toggleVisibility(_ isVisible: Bool) {
UIView.animate(withDuration: 0.2) {
if isVisible {
self.alpha = 1
} else {
self.alpha = 0
}
}
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
private func commonInit() {
setUpViewHierarchy()
configureUI()
}
private func setUpViewHierarchy() {
stackView.translatesAutoresizingMaskIntoConstraints = false
addSubview(stackView)
NSLayoutConstraint.activate([
heightAnchor.constraint(equalToConstant: Constants.viewHeight),
stackView.topAnchor.constraint(equalTo: topAnchor, constant: Constants.verticalMarginToBounds),
stackView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: Constants.horizontalMarginToBounds),
trailingAnchor.constraint(equalTo: stackView.trailingAnchor, constant: Constants.horizontalMarginToBounds),
bottomAnchor.constraint(equalTo: stackView.bottomAnchor, constant: Constants.verticalMarginToBounds)
])
}
private func configureUI() {
backgroundColor = .invertedSystem5
layer.cornerRadius = Constants.viewHeight / 2
addShadow()
}
private func addShadow() {
layer.shadowColor = UIColor.black.cgColor
layer.shadowOffset = CGSize(width: 0, height: 2)
layer.shadowOpacity = 0.5
}
}
| gpl-2.0 | ef179eaedef89130b484da9323c8dcaa | 28.848837 | 119 | 0.625633 | 5.292784 | false | false | false | false |
diwu/LeetCode-Solutions-in-Swift | Solutions/Solutions/Easy/Easy_066_Plus_One.swift | 1 | 715 | /*
https://leetcode.com/problems/plus-one/
#66 Plus One
Level: easy
Given a non-negative number represented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.
Inspired by @zezedi at https://leetcode.com/discuss/14616/is-it-a-simple-code-c
*/
import Foundation
struct Easy_066_Plus_One {
static func plusOne(_ digits: inout [Int]) {
let n = digits.count
for i in (0 ... n-1).reversed() {
if digits[i] == 9 {
digits[i] = 0
} else {
digits[i] += 1
return
}
}
digits[0] = 1
digits.append(0)
}
}
| mit | 6de06177849f2c4119960f32289ef31e | 20.666667 | 86 | 0.566434 | 3.557214 | false | false | false | false |
lenssss/whereAmI | Whereami/Controller/Personal/PersonalEditPasswordViewController.swift | 1 | 6266 | //
// PersonalEditPasswordViewController.swift
// Whereami
//
// Created by A on 16/5/25.
// Copyright © 2016年 WuQifei. All rights reserved.
//
import UIKit
//import MBProgressHUD
import SVProgressHUD
import ReactiveCocoa
class PersonalEditPasswordViewController: UIViewController {
var password:UITextField? = nil
var confirmPassword:UITextField? = nil
private var validPwd:Bool = false
private var validConfirmPwd:Bool = false
override func viewDidLoad() {
super.viewDidLoad()
self.setConfig()
self.setUI()
self.signalAction()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
SVProgressHUD.dismiss()
}
func nextButtonActivited () {
if self.validPwd && self.validConfirmPwd {
self.navigationItem.rightBarButtonItem!.enabled = true
}
else
{
self.navigationItem.rightBarButtonItem!.enabled = false
}
}
func signalAction() {
let passwordSignal:RACSignal = (self.password?.rac_textSignal())!
let confirmPasswordSignal:RACSignal = (self.confirmPassword?.rac_textSignal())!
passwordSignal.filter { (currentStr) -> Bool in
if "\(currentStr)".length > 5 {
return true
}
return false
}.subscribeNext { (finishedStr) -> Void in
self.validPwd = true
self.nextButtonActivited()
}
passwordSignal.filter { (currentStr) -> Bool in
if "\(currentStr)".length > 5 {
return false
}
return true
}.subscribeNext { (finishedStr) -> Void in
self.validPwd = false
self.nextButtonActivited()
}
confirmPasswordSignal.filter { (currentStr) -> Bool in
if "\(currentStr)".length > 5 {
return true
}
return false
}.subscribeNext { (finishedStr) -> Void in
self.validConfirmPwd = true
self.nextButtonActivited()
}
confirmPasswordSignal.filter { (currentStr) -> Bool in
if "\(currentStr)".length > 5 {
return false
}
return true
}.subscribeNext { (finishedStr) -> Void in
self.validConfirmPwd = false
self.nextButtonActivited()
}
}
func setUI(){
let backBtn = TheBackBarButton.initWithAction({
self.pushBack()
})
self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backBtn)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("next",tableName:"Localizable", comment: ""), style: .Done, target: self, action: #selector(self.updateItem))
self.password = UITextField()
self.password?.placeholder = "password"
self.password?.borderStyle = .RoundedRect
self.password?.clearButtonMode = .Always
self.password?.secureTextEntry = true
self.view.addSubview(self.password!)
self.confirmPassword = UITextField()
self.confirmPassword?.placeholder = "confirm password"
self.confirmPassword?.clearButtonMode = .Always
self.confirmPassword?.borderStyle = .RoundedRect
self.confirmPassword?.secureTextEntry = true
self.view.addSubview(self.confirmPassword!)
self.password?.autoPinEdgeToSuperviewEdge(.Top,withInset: 16)
self.password?.autoPinEdgeToSuperviewEdge(.Left,withInset: 0)
self.password?.autoPinEdgeToSuperviewEdge(.Right,withInset: 0)
self.password?.autoPinEdge(.Bottom, toEdge: .Top, ofView: self.confirmPassword!,withOffset: -5)
self.password?.autoSetDimension(.Height, toSize: 44)
self.confirmPassword?.autoPinEdgeToSuperviewEdge(.Left,withInset: 0)
self.confirmPassword?.autoPinEdgeToSuperviewEdge(.Right,withInset: 0)
self.confirmPassword?.autoSetDimension(.Height, toSize: 44)
}
func updateItem(){
if self.password?.text == self.confirmPassword?.text {
let currentUser = UserModel.getCurrentUser()
var dic = [String:AnyObject]()
dic["accountId"] = currentUser?.id
dic["password"] = self.password?.text
// let hub = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
// hub.color = UIColor.clearColor()
SVProgressHUD.setBackgroundColor(UIColor.clearColor())
SVProgressHUD.show()
SocketManager.sharedInstance.sendMsg("accountUpdate", data: dic, onProto: "accountUpdateed") { (code, objs) in
if code == statusCode.Normal.rawValue {
self.runInMainQueue({
// MBProgressHUD.hideHUDForView(self.view, animated: true)
SVProgressHUD.dismiss()
self.pushBack()
})
}
}
}
else{
self.runInMainQueue({
let alertController = UIAlertController(title: "warning", message: "两次输入不同", preferredStyle: .Alert)
let confirmAction = UIAlertAction(title: NSLocalizedString("ok",tableName:"Localizable", comment: ""), style: .Default, handler: { (confirmAction) in
})
alertController.addAction(confirmAction)
self.presentViewController(alertController, animated: true, completion: nil)
})
}
}
func pushBack(){
let viewControllers = self.navigationController?.viewControllers
let index = (viewControllers?.count)! - 2
let viewController = viewControllers![index]
self.navigationController?.popToViewController(viewController, animated: false)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 3f9fe986ac34813d5e5016e8feff5c94 | 35.343023 | 200 | 0.589666 | 5.512346 | false | false | false | false |
pantuspavel/PPEventRegistryAPI | PPEventRegistryAPI/PPEventRegistryAPITests/Classes/Transport/PPTransport+Fixture.swift | 1 | 1343 | //
// PPTransport+Fixture.swift
// PPEventRegistryAPI
//
// Created by Pavel Pantus on 9/25/16.
// Copyright © 2016 Pavel Pantus. All rights reserved.
//
import Foundation
import OHHTTPStubs
@testable import PPEventRegistryAPI
extension PPTransport {
static func stubEmptyResponse() {
stub(condition: { request -> Bool in
true
}) { response -> OHHTTPStubsResponse in
let responseData : [String: Any] = [:]
return OHHTTPStubsResponse(jsonObject: responseData, statusCode: 200, headers: nil)
}.name = "PPTransport Stub: Empty Response"
}
static func stubInvalidResponse() {
stub(condition: { request -> Bool in
true
}) { response -> OHHTTPStubsResponse in
let responseData: [Any] = []
return OHHTTPStubsResponse(jsonObject: responseData, statusCode: 200, headers: nil)
}.name = "PPTransport Stub: Invalid Response"
}
static func stubErrorResponse() {
stub(condition: { request -> Bool in
true
}) { response -> OHHTTPStubsResponse in
let error = NSError(domain: NSURLErrorDomain, code: NSURLErrorNotConnectedToInternet, userInfo: nil)
return OHHTTPStubsResponse(error: error)
}.name = "PPTransport Stub: Error Response"
}
}
| mit | e25875c4b7e3a42f530b6f6f59182ccf | 31.731707 | 112 | 0.635618 | 5.045113 | false | false | false | false |
milseman/swift | test/ClangImporter/optional.swift | 18 | 3672 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/Inputs/custom-modules -emit-silgen -o - %s | %FileCheck %s
// REQUIRES: objc_interop
import ObjectiveC
import Foundation
import objc_ext
import TestProtocols
class A {
@objc func foo() -> String? {
return ""
}
// CHECK-LABEL: sil hidden [thunk] @_T08optional1AC3fooSSSgyFTo : $@convention(objc_method) (A) -> @autoreleased Optional<NSString>
// CHECK: bb0([[SELF:%.*]] : $A):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[T0:%.*]] = function_ref @_T08optional1AC3fooSSSgyF
// CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[BORROWED_SELF_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK-NEXT: destroy_value [[SELF_COPY]]
// CHECK-NEXT: switch_enum [[T1]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
//
// Something branch: project value, translate, inject into result.
// CHECK: [[SOME_BB]]([[STR:%.*]] : $String):
// CHECK: [[T0:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF
// CHECK-NEXT: [[BORROWED_STR:%.*]] = begin_borrow [[STR]]
// CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[BORROWED_STR]])
// CHECK-NEXT: enum $Optional<NSString>, #Optional.some!enumelt.1, [[T1]]
// CHECK-NEXT: end_borrow [[BORROWED_STR:%.*]] from [[STR]]
// CHECK-NEXT: destroy_value [[STR]]
// CHECK-NEXT: br
// Nothing branch: inject nothing into result.
//
// CHECK: [[NONE_BB]]:
// CHECK-NEXT: enum $Optional<NSString>, #Optional.none!enumelt
// CHECK-NEXT: br
// Continuation.
// CHECK: bb3([[T0:%.*]] : $Optional<NSString>):
// CHECK-NEXT: return [[T0]]
@objc func bar(x x : String?) {}
// CHECK-LABEL: sil hidden [thunk] @_T08optional1AC3barySSSg1x_tFTo : $@convention(objc_method) (Optional<NSString>, A) -> ()
// CHECK: bb0([[ARG:%.*]] : $Optional<NSString>, [[SELF:%.*]] : $A):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: switch_enum [[ARG_COPY]] : $Optional<NSString>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
//
// Something branch: project value, translate, inject into result.
// CHECK: [[SOME_BB]]([[NSSTR:%.*]] : $NSString):
// CHECK: [[T0:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
// Make a temporary initialized string that we're going to clobber as part of the conversion process (?).
// CHECK-NEXT: [[NSSTR_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[NSSTR]] : $NSString
// CHECK-NEXT: [[STRING_META:%.*]] = metatype $@thin String.Type
// CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[NSSTR_BOX]], [[STRING_META]])
// CHECK-NEXT: enum $Optional<String>, #Optional.some!enumelt.1, [[T1]]
// CHECK-NEXT: br
//
// Nothing branch: inject nothing into result.
// CHECK: [[NONE_BB]]:
// CHECK: enum $Optional<String>, #Optional.none!enumelt
// CHECK-NEXT: br
// Continuation.
// CHECK: bb3([[T0:%.*]] : $Optional<String>):
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[T1:%.*]] = function_ref @_T08optional1AC3barySSSg1x_tF
// CHECK-NEXT: [[T2:%.*]] = apply [[T1]]([[T0]], [[BORROWED_SELF_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK-NEXT: destroy_value [[SELF_COPY]]
// CHECK-NEXT: return [[T2]] : $()
}
// rdar://15144951
class TestWeak : NSObject {
weak var b : WeakObject? = nil
}
class WeakObject : NSObject {}
| apache-2.0 | 2ce82e283aefaf903cc463d67cdeed34 | 46.076923 | 165 | 0.624728 | 3.221053 | false | false | false | false |
liuxuan30/ios-charts | Source/Charts/Filters/DataApproximator+N.swift | 5 | 4648 | //
// DataApproximator+N.swift
// Charts
//
// Created by M Ivaniushchenko on 9/6/17.
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
extension CGPoint {
fileprivate func distanceToLine(from linePoint1: CGPoint, to linePoint2: CGPoint) -> CGFloat {
let dx = linePoint2.x - linePoint1.x
let dy = linePoint2.y - linePoint1.y
let dividend = abs(dy * self.x - dx * self.y - linePoint1.x * linePoint2.y + linePoint2.x * linePoint1.y)
let divisor = sqrt(dx * dx + dy * dy)
return dividend / divisor
}
}
private struct LineAlt {
let start: Int
let end: Int
var distance: CGFloat = 0
var index: Int = 0
init(start: Int, end: Int, points: [CGPoint]) {
self.start = start
self.end = end
let startPoint = points[start]
let endPoint = points[end]
guard (end > start + 1) else {
return
}
for i in start + 1 ..< end {
let currentPoint = points[i]
let distance = currentPoint.distanceToLine(from: startPoint, to: endPoint)
if distance > self.distance {
self.index = i
self.distance = distance
}
}
}
}
extension LineAlt: Comparable {
static func ==(lhs: LineAlt, rhs: LineAlt) -> Bool {
return (lhs.start == rhs.start) && (lhs.end == rhs.end) && (lhs.index == rhs.index)
}
static func <(lhs: LineAlt, rhs: LineAlt) -> Bool {
return lhs.distance < rhs.distance
}
}
extension DataApproximator {
/// uses the douglas peuker algorithm to reduce the given arraylist of entries to given number of points
/// More algorithm details here - http://psimpl.sourceforge.net/douglas-peucker.html
@objc open class func reduceWithDouglasPeukerN(_ points: [CGPoint], resultCount: Int) -> [CGPoint]
{
// if a shape has 2 or less points it cannot be reduced
if resultCount <= 2 || resultCount >= points.count
{
return points
}
var keep = [Bool](repeating: false, count: points.count)
// first and last always stay
keep[0] = true
keep[points.count - 1] = true
var currentStoredPoints = 2
var queue = [LineAlt]()
let line = LineAlt(start: 0, end: points.count - 1, points: points)
queue.append(line)
repeat {
let line = queue.popLast()!
// store the key
keep[line.index] = true
// check point count tolerance
currentStoredPoints += 1
if (currentStoredPoints == resultCount) {
break;
}
// split the polyline at the key and recurse
let left = LineAlt(start: line.start, end: line.index, points: points)
if (left.index > 0) {
self.insertLine(left, into: &queue)
}
let right = LineAlt(start: line.index, end: line.end, points: points)
if (right.index > 0) {
self.insertLine(right, into: &queue)
}
} while !queue.isEmpty
// create a new array with series, only take the kept ones
let reducedEntries = points.enumerated().compactMap { (index: Int, point: CGPoint) -> CGPoint? in
return keep[index] ? point : nil
}
return reducedEntries
}
// Keeps array sorted
private static func insertLine(_ line: LineAlt, into array: inout [LineAlt]) {
let insertionIndex = self.insertionIndex(for: line, into: &array)
array.insert(line, at: insertionIndex)
}
private static func insertionIndex(for line: LineAlt, into array: inout [LineAlt]) -> Int {
var indices = array.indices
while !indices.isEmpty {
let midIndex = indices.lowerBound.advanced(by: indices.count / 2)
let midLine = array[midIndex]
if midLine == line {
return midIndex
}
else if (line < midLine) {
// perform search in left half
indices = indices.lowerBound..<midIndex
}
else {
// perform search in right half
indices = (midIndex + 1)..<indices.upperBound
}
}
return indices.lowerBound
}
}
| apache-2.0 | 4b862038088b8226f182153171707838 | 29.379085 | 113 | 0.540017 | 4.414055 | false | false | false | false |
josercc/ZHTableViewGroupSwift | Sources/SwiftTableViewGroup/UITableView/TableSection.swift | 1 | 1033 | //
// TableSection.swift
//
//
// Created by 张行 on 2019/7/17.
//
import UIKit.UITableViewCell
public struct TableSection : DataNode {
public var header:TableHeaderView?
public var footer:TableFooterView?
public var cells:[TableCell] = [TableCell]()
public init(@TableSectionBuilder _ block:() -> DataNode) {
if let group = block() as? TableViewRegiterGroup {
self.header = group.header
self.footer = group.footer
self.cells = group.cells
}
}
public func number() -> Int {
var count = 0
for cell in cells {
count += cell.number
}
return count
}
/// 1 2 3
public func cell(index:Int) -> (cell:TableCell, index:Int) {
var count = 0
for cell in cells {
let countIndex = count + cell.number
if index < countIndex {
return (cell, index - count)
}
count = countIndex
}
return (cells[0],0)
}
}
| mit | f5f83dfe21dedc15d8c6cc385f74928f | 24.097561 | 64 | 0.542274 | 4.360169 | false | false | false | false |
Neft-io/neft | packages/neft-runtime-macos/io.neft.mac/Device.swift | 1 | 1457 | import Cocoa
class Device {
var pixelRatio: CGFloat = 1
class func register() {
App.getApp().client.onAction(.deviceLog) {
(reader: Reader) in
App.getApp().renderer.device!.log(reader.getString())
}
App.getApp().client.onAction(.deviceShowKeyboard) {}
App.getApp().client.onAction(.deviceHideKeyboard) {}
}
init() {
let app: ViewController = App.getApp()
// DEVICE_PIXEL_RATIO
let pixelRatio = NSScreen.main()!.backingScaleFactor
self.pixelRatio = pixelRatio
app.client.pushAction(OutAction.devicePixelRatio, pixelRatio)
// DEVICE_IS_PHONE
app.client.pushAction(OutAction.deviceIsPhone, false)
}
func onEvent(_ event: NSEvent) {
let app: ViewController = App.getApp()
var action: OutAction!
switch event.type {
case .leftMouseDown, .rightMouseDown, .otherMouseDown:
action = OutAction.pointerPress
case .mouseMoved, .leftMouseDragged, .rightMouseDragged, .otherMouseDragged:
action = OutAction.pointerMove
case .leftMouseUp, .rightMouseUp, .otherMouseUp:
action = OutAction.pointerRelease
default:
return
}
let point = app.view.convert(event.locationInWindow, from: nil)
app.client.pushAction(action, point.x, point.y)
}
func log(_ val: String) {
NSLog(val)
}
}
| apache-2.0 | 0710c6fa008ba289ee620af8a51f5ccc | 27.568627 | 84 | 0.615649 | 4.349254 | false | false | false | false |
worchyld/FanDuelSample | FanDuelSample/FanDuelSample/FDPlayGameViewController.swift | 1 | 15458 | //
// FDPlayGameViewController.swift
// FanDuelSample
//
// Created by Amarjit on 18/12/2016.
// Copyright © 2016 Amarjit. All rights reserved.
//
import UIKit
import AVFoundation
import AudioToolbox
import Haneke
import SVProgressHUD
struct PlayGameViewModel {
var players: [FDPlayer] = [FDPlayer]()
var score: Int = 0
var formattedScore: String {
return String(self.score)
}
let correct: Int = 5
let incorrect: Int = -2
var currentRound = 0
let maxRounds = 10
init(players:[FDPlayer]) {
self.players = players
}
func shouldMoveToNextRound() -> Bool {
return (self.currentRound < self.maxRounds)
}
func sortPlayersByFPPG() -> [FDPlayer] {
let sorted = self.players.sorted(by: { $0.fppg > $1.fppg })
return sorted
}
}
class FDPlayGameViewController: UIViewController {
let cache = Shared.dataCache
var objects:[FDPlayer] = [FDPlayer]()
var viewModel: PlayGameViewModel!
var audioPlayer = AVAudioPlayer()
let tickSound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "tick", ofType: "wav")!)
var timer = Timer()
var tickTimer = Timer()
@IBOutlet weak var btnMainMenu: UIButton!
@IBOutlet weak var roundLabel: UILabel!
@IBOutlet var playerLabelCollection: [UILabel]!
@IBOutlet var playerBtnCollection: [AnswerButton]!
@IBOutlet var playerScoreLabelCollection: [UILabel]!
@IBOutlet weak var headlineLabel: UILabel!
@IBOutlet weak var progressView: UIProgressView!
@IBOutlet weak var scoreLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.viewModel = PlayGameViewModel.init(players: [FDPlayer]())
self.viewModel.currentRound = 0
self.loadSounds()
self.presetImages()
self.loadNextRound()
self.view.layoutIfNeeded()
}
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.isNavigationBarHidden = true
let _ = self.prefersStatusBarHidden
self.setupUI()
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
self.viewModel = nil
timer.invalidate()
tickTimer.invalidate()
self.audioPlayer.stop()
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if (segue.identifier == "resultsSegue") {
let resultsPage: FDResultsViewController = segue.destination as! FDResultsViewController
resultsPage.viewModel = self.viewModel
}
}
// --------------------------
//
// MARK: - IBActions
//
// --------------------------
@IBAction func buttonPressed(_ sender: AnyObject) {
guard let tag = sender.tag else {
return
}
handlePickedAnswer(tag:tag)
}
@IBAction func menuButtonPressed(_ sender: Any) {
let _ = self.navigationController?.popViewController(animated: true)
}
}
// --------------------------
//
// MARK: - Functions
//
// --------------------------
extension FDPlayGameViewController {
func handlePickedAnswer(tag:Int) {
if (tag <= self.viewModel.players.count) {
timer.invalidate()
self.stopTickingSound()
self.toggleQuizButtons(enabled: false)
let player1: FDPlayer = self.viewModel.players[tag]
var player2: FDPlayer!
var correctTag:Int = 0
if (tag == 0) {
player2 = self.viewModel.players[1]
}
else if (tag == 1) {
player2 = self.viewModel.players[0]
}
else {
print ("Unable to find tag \(tag)")
return
}
if (player1.fppg > player2.fppg) {
print ("Correct")
correctTag = 0
self.viewModel.score += self.viewModel.correct
self.updateScoreLabel()
self.moveToNextQuestion()
}
else {
print ("Incorrect")
correctTag = 1
self.viewModel.score -= self.viewModel.incorrect
self.updateScoreLabel()
self.playerBtnCollection[tag].shake()
let correctBtn:AnswerButton = self.playerBtnCollection[correctTag]
correctBtn.layer.borderWidth = 3
correctBtn.layer.borderColor = UIColor.green.cgColor
animateCorrectAnswer(correctTag, completionHandler: {(success:Bool) -> Void in
if (success) {
self.moveToNextQuestion()
}
})
}
}
}
func moveToNextQuestion() {
if (self.viewModel.shouldMoveToNextRound()) {
self.viewModel.currentRound += 1
self.animateQuestionsOut({(success:Bool) -> Void in
if (success) {
self.updateScoreLabel()
self.loadNextRound()
}
})
}
else {
self.performSegue(withIdentifier: "resultsSegue", sender: self)
}
}
func animateCorrectAnswer(_ tag:Int, completionHandler:@escaping (_ success:Bool) -> Void) {
//
// Animate all btns but correct out
//
UIView.animate(withDuration: 0.60, delay: 0.75, options: .curveEaseOut, animations: {
let _ = self.playerBtnCollection.filter({
$0.tag != tag
}).map({
$0.layer.opacity = 0
})
}, completion: { finished in
if (finished) {
completionHandler(true)
}
})
}
func setupUI() {
for element in playerScoreLabelCollection {
element.layer.opacity = 0
}
for element in playerLabelCollection {
element.layer.opacity = 0
}
for element in playerBtnCollection {
element.layer.opacity = 0
element.isEnabled = false
}
self.headlineLabel.layer.opacity = 0
self.progressView.layer.opacity = 0
self.roundLabel.layer.opacity = 0
}
func presetImages() {
guard let blankAvatar:UIImage = UIImage(named: "avatar_blank") else {
return
}
for element:AnswerButton in self.playerBtnCollection {
element.setBackgroundImage(blankAvatar, for: .normal)
element.sizeToFit()
}
}
func loadImageFor(player:FDPlayer, button:UIButton) {
guard let blankAvatar:UIImage = UIImage(named: "avatar_blank") else {
return
}
guard let imagePath = player.imagePath else {
print ("Can't find imagePath")
return
}
guard let imageURL = URL(string: imagePath) else {
return
}
button.hnk_setBackgroundImageFromURL(imageURL, state: .normal, placeholder: blankAvatar, format: Format<UIImage>(name: "blankAvatar"), failure: nil, success: nil)
button.sizeToFit()
button.layoutIfNeeded()
}
func loadPlayersForRound(completionHandler:(_ success:Bool) -> Void) {
// Shuffle players
let shuffled = self.objects.shuffled()
let p1 = shuffled.first!
let p2 = shuffled.filter({
return $0.remoteid != p1.remoteid
}).first!
self.viewModel.players = [p1,p2]
// set player name labels
for element in self.playerLabelCollection {
switch (element.tag) {
case 0:
guard let fullName = p1.fullName else {
break
}
element.text = fullName
break
case 1:
guard let fullName = p2.fullName else {
break
}
element.text = fullName
break
default:
break
}
element.layoutIfNeeded()
}
// set fppg score labels
for element in self.playerScoreLabelCollection {
switch (element.tag) {
case 0:
element.text = String(p1.fppg)
break
case 1:
element.text = String(p2.fppg)
break
default:
break
}
element.layoutIfNeeded()
}
// set image for button
for element in self.playerBtnCollection {
switch (element.tag) {
case 0:
self.loadImageFor(player: p1, button: element)
break
case 1:
self.loadImageFor(player: p2, button: element)
break
default:
break
}
}
completionHandler(true)
}
func loadNextRound() {
self.progressView.progress = 1.0
let dispatchTime: DispatchTime = DispatchTime.now() + Double(Int64(0.1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
self.loadPlayersForRound(completionHandler: {(success:Bool) -> Void in
if (success) {
self.updateRoundLabel()
UIView.animate(withDuration: 0.25, delay: 0.25, options: .curveEaseIn, animations: {
self.roundLabel.layer.opacity = 1
self.progressView.layer.opacity = 1
}, completion: { finished in
if (finished) {
UIView.animate(withDuration: 0.25, delay: 0.25, options: .curveEaseOut, animations: {
self.roundLabel.layer.opacity = 0
}, completion: { finished in
if (finished) {
self.animateQuestionsIn({(success:Bool) -> Void in
if (success) {
DispatchQueue.main.asyncAfter(deadline: dispatchTime) {
self.startTimer()
}
}
})
}
})
}
})
}
})
}
func animateQuestionsIn(_ completionHandler:@escaping (_ success:Bool) -> Void)
{
self.progressView.progress = 1.0
UIView.animate(withDuration: 0.35, delay: 0.25, options: .curveEaseIn, animations: {
self.progressView.layer.opacity = 1
self.headlineLabel.layer.opacity = 1
}, completion: { finished in
if (finished) {
UIView.animate(withDuration: 0.75, delay: 0.75, options: .curveEaseIn, animations: {
for element in self.playerLabelCollection {
element.layer.opacity = 1
}
for element in self.playerBtnCollection {
element.layer.opacity = 1
}
}, completion: { finished in
if (finished) {
for element in self.playerBtnCollection {
element.isEnabled = true
}
completionHandler(true)
}
})
}
})
}
func animateQuestionsOut(_ completionHandler:@escaping (_ success:Bool) -> Void)
{
print (self.playerLabelCollection.count)
UIView.animate(withDuration: 0.5, delay: 0.5, options: .curveEaseOut, animations: {
for element:UILabel in self.playerLabelCollection {
element.layer.opacity = 0
element.alpha = 0.0
}
for element in self.playerBtnCollection {
element.layer.opacity = 0
element.layer.borderWidth = 0
element.layer.borderColor = UIColor.clear.cgColor
}
self.headlineLabel.layer.opacity = 0
self.progressView.layer.opacity = 0
self.updateRoundLabel()
}, completion: { finished in
if (finished) {
completionHandler(finished)
}
})
}
func updateScoreLabel() {
self.scoreLabel.text = "\(self.viewModel.formattedScore)"
}
func updateRoundLabel() {
print("Current round: \(self.viewModel.currentRound)")
self.roundLabel.text = "Round \(self.viewModel.currentRound) of \(self.viewModel.maxRounds)"
self.roundLabel.sizeToFit()
self.roundLabel.layoutIfNeeded()
}
func toggleQuizButtons(enabled:Bool = false) {
for btn in self.playerBtnCollection {
btn.isEnabled = enabled
}
}
}
// ---------------------------
//
// MARK: - NSTimer & Sounds
//
// ---------------------------
extension FDPlayGameViewController {
func startTimer() {
timer = Timer.scheduledTimer(timeInterval: 0.10, target: self, selector: #selector(self.updateProgressView), userInfo: nil, repeats: true)
tickTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.playTickingSound), userInfo: nil, repeats: true)
}
func updateProgressView() {
progressView.progress -= 0.1 / 5.0
if (progressView.progress <= 0) {
timer.invalidate()
tickTimer.invalidate()
outOfTime()
}
}
func outOfTime() {
self.stopTickingSound()
print("Time has ran out")
let player1: FDPlayer = self.viewModel.players[0]
let player2: FDPlayer = self.viewModel.players[1]
var correctTag:Int = 0
var incorrectTag:Int = 0
if player1.fppg > player2.fppg {
correctTag = 0
incorrectTag = 1
}
else if (player2.fppg > player1.fppg) {
correctTag = 1
incorrectTag = 0
}
self.viewModel.score -= self.viewModel.incorrect
self.updateScoreLabel()
self.playerBtnCollection[incorrectTag].shake()
let correctBtn:AnswerButton = self.playerBtnCollection[correctTag]
correctBtn.layer.borderWidth = 3
correctBtn.layer.borderColor = UIColor.green.cgColor
animateCorrectAnswer(correctTag, completionHandler: {(success:Bool) -> Void in
if (success) {
self.moveToNextQuestion()
}
})
}
// MARK: - Sounds
func loadSounds() {
do {
self.audioPlayer = try AVAudioPlayer.init(contentsOf: self.tickSound as URL)
audioPlayer.prepareToPlay()
} catch {
print("Error getting the audio file")
}
}
func playTickingSound() {
self.audioPlayer.play()
}
func stopTickingSound() {
tickTimer.invalidate()
self.audioPlayer.stop()
}
}
| gpl-3.0 | 16891b3efd1dcdd2ef114e9af682a8da | 28.611111 | 170 | 0.537491 | 4.919478 | false | false | false | false |
kevinvanderlugt/Exercism-Solutions | swift/exercism-test-runner/exercism-test-runner/Meetup.swift | 1 | 1972 | //
// MeetUp.swift
// exercism-test-runner
//
// Created by Kevin VanderLugt on 3/20/15.
// Copyright (c) 2015 Alpine Pipeline, LLC. All rights reserved.
//
import Foundation
struct Meetup {
var month: Int
var year: Int
let calendar = NSCalendar.currentCalendar()
let components = NSDateComponents()
private let invalidDate = NSDate.distantFuture() as! NSDate
init(year: Int, month: Int) {
self.year = year
self.month = month
}
func day(day: Int, which: String) -> NSDate {
components.weekday = day
var dateOptions = NSCalendarOptions.MatchNextTime
var weeks = 0, dayOffset = 0, monthOffset = 0
switch which {
case "1st": weeks = 0
case "2nd": weeks = 1
case "3rd": weeks = 2
case "4th": weeks = 3
case "teenth": dayOffset = 12
case "last":
dayOffset = 1
monthOffset = 1
dateOptions = dateOptions | NSCalendarOptions.SearchBackwards
default: return invalidDate
}
var returnDate = invalidDate
if let startingDate = startDate(dayOffset: dayOffset, monthOffset: monthOffset) {
var dateCount = 0
calendar.enumerateDatesStartingAfterDate(startingDate, matchingComponents: components, options: dateOptions)
{ (date: NSDate!, exactMatch: Bool, stop: UnsafeMutablePointer<ObjCBool>) in
if dateCount == weeks {
stop.memory = true
returnDate = date
}
dateCount++
}
}
return returnDate
}
func startDate(dayOffset: Int = 0, monthOffset: Int = 0) -> NSDate? {
return calendar.dateWithEra(1,
year: year,
month: month + monthOffset,
day: 0 + dayOffset,
hour: 0, minute: 0, second: 0, nanosecond: 0)
}
} | mit | fad63baa3646fe783a4a2dc1d18027db | 29.353846 | 120 | 0.559838 | 4.64 | false | false | false | false |
esttorhe/eidolon | KioskTests/TestHelpers.swift | 3 | 3368 | import Foundation
import Quick
import Nimble
@testable
import Kiosk
import Moya
private enum DefaultsKeys: String {
case TokenKey = "TokenKey"
case TokenExpiry = "TokenExpiry"
}
func clearDefaultsKeys(defaults: NSUserDefaults) {
defaults.removeObjectForKey(DefaultsKeys.TokenKey.rawValue)
defaults.removeObjectForKey(DefaultsKeys.TokenExpiry.rawValue)
}
func getDefaultsKeys(defaults: NSUserDefaults) -> (key: String?, expiry: NSDate?) {
let key = defaults.objectForKey(DefaultsKeys.TokenKey.rawValue) as! String?
let expiry = defaults.objectForKey(DefaultsKeys.TokenExpiry.rawValue) as! NSDate?
return (key: key, expiry: expiry)
}
func setDefaultsKeys(defaults: NSUserDefaults, key: String?, expiry: NSDate?) {
defaults.setObject(key, forKey: DefaultsKeys.TokenKey.rawValue)
defaults.setObject(expiry, forKey: DefaultsKeys.TokenExpiry.rawValue)
}
func setupProviderForSuite(provider: ArtsyProvider<ArtsyAPI>) {
beforeSuite {
Provider.sharedProvider = provider
}
afterSuite {
Provider.sharedProvider = Provider.DefaultProvider()
}
}
func yearFromDate(date: NSDate) -> Int {
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
return calendar.components(.Year, fromDate: date).year
}
@objc class TestClass: NSObject { }
// Necessary since UIImage(named:) doesn't work correctly in the test bundle
extension UIImage {
class func testImage(named name: String, ofType type: String) -> UIImage! {
let bundle = NSBundle(forClass: TestClass().dynamicType)
let path = bundle.pathForResource(name, ofType: type)
return UIImage(contentsOfFile: path!)
}
}
func testArtwork() -> Artwork {
return Artwork.fromJSON(["id": "red",
"title" : "Rose Red",
"date": "June 11th 2014",
"blurb": "Pretty good",
"artist": ["id" : "artistDee", "name": "Dee Emm"],
"images": [
["id" : "image_id",
"image_url" : "http://example.com/:version.jpg",
"image_versions" : ["large"],
"aspect_ratio" : 1.508,
"tile_base_url" : "http://example.com",
"tile_size" : 1]
]]) as! Artwork
}
func testSaleArtwork() -> SaleArtwork {
let saleArtwork = SaleArtwork(id: "12312313", artwork: testArtwork())
saleArtwork.auctionID = "AUCTION"
return saleArtwork
}
func testBidDetails() -> BidDetails {
return BidDetails(saleArtwork: testSaleArtwork(), paddleNumber: nil, bidderPIN: nil, bidAmountCents: nil)
}
class StubFulfillmentController: FulfillmentController {
lazy var bidDetails: BidDetails = { () -> BidDetails in
let bidDetails = BidDetails.stubbedBidDetails()
bidDetails.setImage = { (_, imageView) -> () in
imageView.image = loadingViewControllerTestImage
}
return bidDetails
}()
var auctionID: String! = ""
var xAccessToken: String?
var loggedInProvider: ReactiveCocoaMoyaProvider<ArtsyAPI>? = Provider.StubbingProvider()
var loggedInOrDefaultProvider: ReactiveCocoaMoyaProvider<ArtsyAPI> = Provider.StubbingProvider()
}
/// Nimble is currently having issues with nondeterministic async expectations.
/// This will have to do for now 😢
/// See: https://github.com/Quick/Nimble/issues/177
func kioskWaitUntil(action: (() -> Void) -> Void) {
waitUntil(timeout: 10, action: action)
}
| mit | 6f5baf507d254b158c0c4e48f62d0db3 | 31.990196 | 109 | 0.696582 | 4.270305 | false | true | false | false |
justeat/JustPeek | JustPeek/Classes/PeekReplacementHandler.swift | 1 | 4400 | //
// PeekReplacementHandler.swift
// JustPeek
//
// Copyright 2016 Just Eat Holdings Ltd.
//
import UIKit
@objcMembers internal class PeekReplacementHandler: PeekHandler {
private var peekContext: PeekContext?
private weak var delegate: PeekingDelegate?
private let longPressDurationForCommitting = 3.0
private var commitOperation: Operation?
private var peekStartLocation: CGPoint?
private var preventFromPopping = false
private var peekViewController: PeekViewController?
private lazy var presentationWindow: UIWindow! = {
let window = UIWindow()
window.backgroundColor = UIColor.clear
window.windowLevel = UIWindowLevelAlert
window.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dismissPreview)))
return window
}()
func register(viewController vc: UIViewController, forPeekingWithDelegate delegate: PeekingDelegate, sourceView: UIView) {
self.delegate = delegate
self.peekContext = PeekContext(sourceViewController: vc, sourceView: sourceView)
let selector = #selector(handleLongPress(fromRecognizer:))
let longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: selector)
sourceView.addGestureRecognizer(longPressGestureRecognizer)
}
internal func handleLongPress(fromRecognizer gestureRecognizer: UILongPressGestureRecognizer) {
switch gestureRecognizer.state {
case .began:
peekStartLocation = gestureRecognizer.location(in: gestureRecognizer.view)
peek(at: peekStartLocation!)
let commitOperation = BlockOperation(block: { [weak self] in
self?.commit()
})
self.commitOperation = commitOperation
let delayTime = DispatchTime.now() + Double(Int64(longPressDurationForCommitting * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime) {
if !commitOperation.isCancelled {
OperationQueue.main.addOperation(commitOperation)
}
}
case .changed:
let currentLocation = gestureRecognizer.location(in: gestureRecognizer.view)
if let startLocation = peekStartLocation , abs(currentLocation.y - startLocation.y) > 50 {
preventFromPopping = true
commitOperation?.cancel()
}
break
case .ended, .cancelled:
commitOperation?.cancel()
if !preventFromPopping {
// delay for UI Tests
let delayTime = DispatchTime.now() + Double(Int64(0.1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime) { [weak self] in
self?.pop()
}
}
default:
break
}
}
@objc(peekAtLocation:) internal func peek(at location: CGPoint) {
guard let peekContext = peekContext else { return }
peekContext.destinationViewController = delegate?.peekContext(peekContext, viewControllerForPeekingAt: location)
peekViewController = PeekViewController(peekContext: peekContext)
guard let peekViewController = peekViewController else { return }
presentationWindow.rootViewController = peekViewController
presentationWindow.isHidden = false
peekViewController.peek()
}
internal func pop(_ completion: (() -> Void)? = nil) {
preventFromPopping = false
let window = presentationWindow
peekViewController?.pop({ (_) in
window?.isHidden = true
completion?()
})
}
internal func commit() {
preventFromPopping = false
pop { [weak self] in
guard let strongSelf = self, let peekContext = strongSelf.peekContext else { return }
guard let destinationViewController = peekContext.destinationViewController else { return }
strongSelf.delegate?.peekContext(peekContext, commit: destinationViewController)
}
}
// This function purely exists to make objc happy when trying to call pop from the UIGestureRecognizer selector
internal func dismissPreview() {
pop()
}
}
| apache-2.0 | 2ece46c4234579995fe5cf9dc7b505b4 | 39.740741 | 140 | 0.650227 | 5.506884 | false | false | false | false |
bazelbuild/tulsi | src/TulsiGeneratorIntegrationTests/QueryTests.swift | 2 | 10428 | // Copyright 2016 The Tulsi 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 XCTest
@testable import BazelIntegrationTestCase
@testable import TulsiGenerator
// Tests for the Bazel query extractor.
class QueryTests_PackageRuleExtraction: BazelIntegrationTestCase {
var infoExtractor: BazelQueryInfoExtractor! = nil
override func setUp() {
super.setUp()
infoExtractor = BazelQueryInfoExtractor(bazelURL: bazelURL,
workspaceRootURL: workspaceRootURL!,
bazelUniversalFlags: bazelUniversalFlags,
localizedMessageLogger: localizedMessageLogger)
}
func testSimple() {
installBUILDFile("Simple", intoSubdirectory: "tulsi_test")
let infos = infoExtractor.extractTargetRulesFromPackages(["tulsi_test"])
let checker = InfoChecker(ruleInfos: infos)
checker.assertThat("//tulsi_test:Application")
.hasType("ios_application")
.hasNoLinkedTargetLabels()
.hasNoDependencies()
checker.assertThat("//tulsi_test:TargetApplication")
.hasType("ios_application")
.hasNoLinkedTargetLabels()
.hasNoDependencies()
checker.assertThat("//tulsi_test:ApplicationLibrary")
.hasType("objc_library")
.hasNoLinkedTargetLabels()
.hasNoDependencies()
checker.assertThat("//tulsi_test:Library")
.hasType("objc_library")
.hasNoLinkedTargetLabels()
.hasNoDependencies()
checker.assertThat("//tulsi_test:TestLibrary")
.hasType("objc_library")
.hasNoLinkedTargetLabels()
.hasNoDependencies()
checker.assertThat("//tulsi_test:XCTest")
.hasType("ios_unit_test")
.hasExactlyOneLinkedTargetLabel(BuildLabel("//tulsi_test:Application"))
.hasNoDependencies()
checker.assertThat("//tulsi_test:ccLibrary")
.hasType("cc_library")
.hasNoLinkedTargetLabels()
.hasNoDependencies()
checker.assertThat("//tulsi_test:ccBinary")
.hasType("cc_binary")
.hasNoLinkedTargetLabels()
.hasNoDependencies()
checker.assertThat("//tulsi_test:ccTest")
.hasType("cc_test")
.hasNoLinkedTargetLabels()
.hasNoDependencies()
}
func testComplexSingle() {
installBUILDFile("ComplexSingle", intoSubdirectory: "tulsi_complex_test")
let infos = infoExtractor.extractTargetRulesFromPackages(["tulsi_complex_test"])
let checker = InfoChecker(ruleInfos: infos)
checker.assertThat("//tulsi_complex_test:Application")
.hasType("ios_application")
.hasNoLinkedTargetLabels()
.hasNoDependencies()
checker.assertThat("//tulsi_complex_test:ApplicationResources")
.hasType("apple_resource_group")
.hasNoLinkedTargetLabels()
.hasNoDependencies()
checker.assertThat("//tulsi_complex_test:ApplicationLibrary")
.hasType("objc_library")
.hasNoLinkedTargetLabels()
.hasNoDependencies()
checker.assertThat("//tulsi_complex_test:ObjCBundle")
.hasType("apple_bundle_import")
.hasNoLinkedTargetLabels()
.hasNoDependencies()
checker.assertThat("//tulsi_complex_test:CoreDataResources")
.hasType("objc_library")
.hasNoLinkedTargetLabels()
.hasNoDependencies()
checker.assertThat("//tulsi_complex_test:Library")
.hasType("objc_library")
.hasNoLinkedTargetLabels()
.hasNoDependencies()
checker.assertThat("//tulsi_complex_test:SubLibrary")
.hasType("objc_library")
.hasNoLinkedTargetLabels()
.hasNoDependencies()
checker.assertThat("//tulsi_complex_test:SubLibraryWithDefines")
.hasType("objc_library")
.hasNoLinkedTargetLabels()
.hasNoDependencies()
checker.assertThat("//tulsi_complex_test:SubLibraryWithIdenticalDefines")
.hasType("objc_library")
.hasNoLinkedTargetLabels()
.hasNoDependencies()
checker.assertThat("//tulsi_complex_test:SubLibraryWithDifferentDefines")
.hasType("objc_library")
.hasNoLinkedTargetLabels()
.hasNoDependencies()
checker.assertThat("//tulsi_complex_test:ObjCFramework")
.hasType("apple_static_framework_import")
.hasNoLinkedTargetLabels()
.hasNoDependencies()
checker.assertThat("//tulsi_complex_test:TodayExtensionLibrary")
.hasType("objc_library")
.hasNoLinkedTargetLabels()
.hasNoDependencies()
checker.assertThat("//tulsi_complex_test:TodayExtension")
.hasType("ios_extension")
.hasNoLinkedTargetLabels()
.hasNoDependencies()
checker.assertThat("//tulsi_complex_test:XCTest")
.hasType("ios_unit_test")
.hasExactlyOneLinkedTargetLabel(BuildLabel("//tulsi_complex_test:Application"))
.hasNoDependencies()
}
}
// Tests for buildfiles extraction.
class QueryTests_BuildFilesExtraction: BazelIntegrationTestCase {
var infoExtractor: BazelQueryInfoExtractor! = nil
let testDir = "Buildfiles"
override func setUp() {
super.setUp()
infoExtractor = BazelQueryInfoExtractor(bazelURL: bazelURL,
workspaceRootURL: workspaceRootURL!,
bazelUniversalFlags: bazelUniversalFlags,
localizedMessageLogger: localizedMessageLogger)
installBUILDFile("ComplexSingle", intoSubdirectory: testDir)
}
func testExtractBuildfiles() {
let targets = [
BuildLabel("//\(testDir):Application"),
BuildLabel("//\(testDir):TodayExtension"),
]
let fileLabels = infoExtractor.extractBuildfiles(targets)
XCTAssert(infoExtractor.hasQueuedInfoMessages)
// Several file labels should've been retrieved, but these can be platform and Bazel version
// specific, so they're assumed to be correct if the primary BUILD file and the nop Skylark file
// are both located.
XCTAssert(fileLabels.contains(BuildLabel("//\(testDir):BUILD")))
XCTAssert(fileLabels.contains(BuildLabel("//\(testDir):ComplexSingle.bzl")))
}
}
private class InfoChecker {
let infoMap: [BuildLabel: (RuleInfo, Set<BuildLabel>)]
init(infos: [RuleInfo: Set<BuildLabel>]) {
var infoMap = [BuildLabel: (RuleInfo, Set<BuildLabel>)]()
for (info, dependencies) in infos {
infoMap[info.label] = (info, dependencies)
}
self.infoMap = infoMap
}
convenience init(ruleInfos: [RuleInfo]) {
var infoDict = [RuleInfo: Set<BuildLabel>]()
for info in ruleInfos {
infoDict[info] = Set<BuildLabel>()
}
self.init(infos: infoDict)
}
func assertThat(_ targetLabel: String, line: UInt = #line) -> Context {
guard let (ruleInfo, dependencies) = infoMap[BuildLabel(targetLabel)] else {
XCTFail("No rule with the label \(targetLabel) was found", line: line)
return Context(ruleInfo: nil, dependencies: nil, infoMap: infoMap)
}
return Context(ruleInfo: ruleInfo, dependencies: dependencies, infoMap: infoMap)
}
/// Context allowing checks against a single RuleInfo.
class Context {
let ruleInfo: RuleInfo?
let dependencies: Set<BuildLabel>?
let infoMap: [BuildLabel: (RuleInfo, Set<BuildLabel>)]
init(ruleInfo: RuleInfo?,
dependencies: Set<BuildLabel>?,
infoMap: [BuildLabel: (RuleInfo, Set<BuildLabel>)]) {
self.ruleInfo = ruleInfo
self.dependencies = dependencies
self.infoMap = infoMap
}
// Does nothing as "assertThat" already asserted the existence of the associated ruleInfo.
func exists() -> Context {
return self
}
/// Asserts that the contextual RuleInfo has the given type.
func hasType(_ type: String, line: UInt = #line) -> Context {
guard let ruleInfo = ruleInfo else { return self }
XCTAssertEqual(ruleInfo.type, type, line: line)
return self
}
/// Asserts that the contextual RuleInfo has the given set of linked target labels.
func hasLinkedTargetLabels(_ labels: Set<BuildLabel>, line: UInt = #line) -> Context {
guard let ruleInfo = ruleInfo else { return self }
XCTAssertEqual(ruleInfo.linkedTargetLabels, labels, line: line)
return self
}
/// Asserts that the contextual RuleInfo has the given linked target label and no others.
func hasExactlyOneLinkedTargetLabel(_ label: BuildLabel, line: UInt = #line) -> Context {
return hasLinkedTargetLabels(Set<BuildLabel>([label]), line: line)
}
/// Asserts that the contextual RuleInfo has no linked target labels.
func hasNoLinkedTargetLabels(_ line: UInt = #line) -> Context {
guard let ruleInfo = ruleInfo else { return self }
if !ruleInfo.linkedTargetLabels.isEmpty {
XCTFail("Expected no linked targets but found \(ruleInfo.linkedTargetLabels)", line: line)
}
return self
}
/// Asserts that the contextual RuleInfo has the given set of dependent labels.
func hasDependencies(_ dependencies: Set<BuildLabel>, line: UInt = #line) -> Context {
guard let ruleDeps = self.dependencies else { return self }
XCTAssertEqual(ruleDeps, dependencies, line: line)
return self
}
/// Asserts that the contextual RuleInfo has the given set of dependent labels.
@discardableResult
func hasDependencies(_ dependencies: [String], line: UInt = #line) -> Context {
let labels = dependencies.map() { BuildLabel($0) }
return hasDependencies(Set<BuildLabel>(labels), line: line)
}
/// Asserts that the contextual RuleInfo has no dependent labels.
@discardableResult
func hasNoDependencies(_ line: UInt = #line) -> Context {
if let ruleDeps = self.dependencies, !ruleDeps.isEmpty {
XCTFail("Expected no dependencies but found \(ruleDeps)", line: line)
}
return self
}
}
}
| apache-2.0 | 29d7cae668854f89c460861848eb731c | 34.469388 | 100 | 0.675201 | 4.630551 | false | true | false | false |
nathawes/swift | test/IRGen/dynamic_self_cast.swift | 9 | 5327 | // RUN: %target-swift-frontend -emit-ir -disable-objc-interop %s | %FileCheck %s
// Note: -disable-objc-interop is used to give consistent results on Darwin
// and Linux, avoiding differences like %swift.refcounted -vs- %objc_object,
// etc.
public class SelfCasts {
// CHECK-LABEL: define {{(dllexport )?}}{{(protected )?}}swiftcc %T17dynamic_self_cast9SelfCastsC* @"$s17dynamic_self_cast9SelfCastsC02toD0yACXDACFZ"(%T17dynamic_self_cast9SelfCastsC* %0, %swift.type* swiftself %1)
// CHECK: [[ARG:%.*]] = bitcast %T17dynamic_self_cast9SelfCastsC* %0 to i8*
// CHECK: [[METATYPE:%.*]] = bitcast %swift.type* %1 to i8*
// CHECK: call i8* @swift_dynamicCastClassUnconditional(i8* [[ARG]], i8* [[METATYPE]], i8* null, i32 0, i32 0)
// CHECK: ret
public static func toSelf(_ s: SelfCasts) -> Self {
return s as! Self
}
// CHECK-LABEL: define {{(dllexport )?}}{{(protected )?}}swiftcc %T17dynamic_self_cast9SelfCastsC* @"$s17dynamic_self_cast9SelfCastsC09genericToD0yACXDxlFZ"(%swift.opaque* noalias nocapture %0, %swift.type* %T, %swift.type* swiftself %1)
// CHECK: call i1 @swift_dynamicCast(%swift.opaque* {{%.*}}, %swift.opaque* {{%.*}}, %swift.type* %T, %swift.type* %1, {{.*}})
// CHECK: ret
public static func genericToSelf<T>(_ s: T) -> Self {
return s as! Self
}
// CHECK-LABEL: define {{(dllexport )?}}{{(protected )?}}swiftcc %T17dynamic_self_cast9SelfCastsC* @"$s17dynamic_self_cast9SelfCastsC014classGenericToD0yACXDxRlzClFZ"(%swift.refcounted* %0, %swift.type* %T, %swift.type* swiftself %1)
// CHECK: [[ARG:%.*]] = bitcast %swift.refcounted* %0 to i8*
// CHECK: [[METATYPE:%.*]] = bitcast %swift.type* %1 to i8*
// CHECK: call i8* @swift_dynamicCastClassUnconditional(i8* [[ARG]], i8* [[METATYPE]], i8* null, i32 0, i32 0)
// CHECK: ret
public static func classGenericToSelf<T : AnyObject>(_ s: T) -> Self {
return s as! Self
}
// CHECK-LABEL: define {{(dllexport )?}}{{(protected )?}}swiftcc void @"$s17dynamic_self_cast9SelfCastsC011genericFromD0xylFZ"(%swift.opaque* noalias nocapture sret %0, %swift.type* %T, %swift.type* swiftself %1)
// CHECK: call i1 @swift_dynamicCast(%swift.opaque* {{%.*}}, %swift.opaque* {{%.*}}, %swift.type* %1, %swift.type* %T, {{.*}})
// CHECK: ret
public static func genericFromSelf<T>() -> T {
let s = Self()
return s as! T
}
// CHECK-LABEL: define {{(dllexport )?}}{{(protected )?}}swiftcc %swift.refcounted* @"$s17dynamic_self_cast9SelfCastsC016classGenericFromD0xyRlzClFZ"(%swift.type* %T, %swift.type* swiftself %0)
// CHECK: call i1 @swift_dynamicCast(%swift.opaque* {{%.*}}, %swift.opaque* {{%.*}}, %swift.type* %0, %swift.type* %T, {{.*}})
// CHECK: ret
public static func classGenericFromSelf<T : AnyObject>() -> T {
let s = Self()
return s as! T
}
// CHECK-LABEL: define {{(dllexport )?}}{{(protected )?}}swiftcc {{i32|i64}} @"$s17dynamic_self_cast9SelfCastsC02toD11ConditionalyACXDSgACFZ"(%T17dynamic_self_cast9SelfCastsC* %0, %swift.type* swiftself %1)
// CHECK: [[ARG:%.*]] = bitcast %T17dynamic_self_cast9SelfCastsC* %0 to i8*
// CHECK: [[METATYPE:%.*]] = bitcast %swift.type* %1 to i8*
// CHECK: call i8* @swift_dynamicCastClass(i8* [[ARG]], i8* [[METATYPE]])
// CHECK: ret
public static func toSelfConditional(_ s: SelfCasts) -> Self? {
return s as? Self
}
// CHECK-LABEL: define {{(dllexport )?}}{{(protected )?}}swiftcc {{i32|i64}} @"$s17dynamic_self_cast9SelfCastsC09genericToD11ConditionalyACXDSgxlFZ"(%swift.opaque* noalias nocapture %0, %swift.type* %T, %swift.type* swiftself %1)
// CHECK: call i1 @swift_dynamicCast(%swift.opaque* {{%.*}}, %swift.opaque* {{%.*}}, %swift.type* %T, %swift.type* %1, {{.*}})
// CHECK: ret
public static func genericToSelfConditional<T>(_ s: T) -> Self? {
return s as? Self
}
// CHECK-LABEL: define {{(dllexport )?}}{{(protected )?}}swiftcc {{i32|i64}} @"$s17dynamic_self_cast9SelfCastsC014classGenericToD11ConditionalyACXDSgxRlzClFZ"(%swift.refcounted* %0, %swift.type* %T, %swift.type* swiftself %1)
// CHECK: [[ARG:%.*]] = bitcast %swift.refcounted* %0 to i8*
// CHECK: [[METATYPE:%.*]] = bitcast %swift.type* %1 to i8*
// CHECK: call i8* @swift_dynamicCastClass(i8* [[ARG]], i8* [[METATYPE]])
// CHECK: ret
public static func classGenericToSelfConditional<T : AnyObject>(_ s: T) -> Self? {
return s as? Self
}
// CHECK-LABEL: define {{(dllexport )?}}{{(protected )?}}swiftcc void @"$s17dynamic_self_cast9SelfCastsC011genericFromD11ConditionalxSgylFZ"(%TSq* noalias nocapture sret %0, %swift.type* %T, %swift.type* swiftself %1)
// CHECK: call i1 @swift_dynamicCast(%swift.opaque* {{%.*}}, %swift.opaque* {{%.*}}, %swift.type* %1, %swift.type* %T, {{.*}})
// CHECK: ret
public static func genericFromSelfConditional<T>() -> T? {
let s = Self()
return s as? T
}
// CHECK-LABEL: define {{(dllexport )?}}{{(protected )?}}swiftcc {{i32|i64}} @"$s17dynamic_self_cast9SelfCastsC016classGenericFromD11ConditionalxSgyRlzClFZ"(%swift.type* %T, %swift.type* swiftself %0)
// CHECK: call i1 @swift_dynamicCast(%swift.opaque* {{%.*}}, %swift.opaque* {{%.*}}, %swift.type* %0, %swift.type* %T, {{.*}})
// CHECK: ret
public static func classGenericFromSelfConditional<T : AnyObject>() -> T? {
let s = Self()
return s as? T
}
public required init() {}
}
| apache-2.0 | dfb925c9f65f9303232053d95299b936 | 57.538462 | 239 | 0.653651 | 3.266094 | false | false | false | false |
Carthage/ogdl-swift | OGDL/Parser.swift | 1 | 7478 | //
// Parser.swift
// OGDL
//
// Created by Justin Spahr-Summers on 2015-01-07.
// Copyright (c) 2015 Carthage. All rights reserved.
//
import Foundation
import Either
import Madness
import Prelude
/// Returns a parser which parses one character from the given set.
internal prefix func % (characterSet: NSCharacterSet) -> Parser<String>.Function {
return { string in
let scalars = string.unicodeScalars
if let scalar = first(scalars) {
if characterSet.longCharacterIsMember(scalar.value) {
return (String(scalar), String(dropFirst(scalars)))
}
}
return nil
}
}
/// Removes the characters in the given string from the character set.
internal func - (characterSet: NSCharacterSet, characters: String) -> NSCharacterSet {
let mutableSet = characterSet.mutableCopy() as NSMutableCharacterSet
mutableSet.removeCharactersInString(characters)
return mutableSet
}
/// Removes characters in the latter set from the former.
internal func - (characterSet: NSCharacterSet, subtrahend: NSCharacterSet) -> NSCharacterSet {
let mutableSet = characterSet.mutableCopy() as NSMutableCharacterSet
mutableSet.formIntersectionWithCharacterSet(subtrahend.invertedSet)
return mutableSet
}
/// Optional matching operator.
postfix operator |? {}
/// Matches zero or one occurrence of the given parser.
internal postfix func |? <T>(parser: Parser<T>.Function) -> Parser<T?>.Function {
return (parser * (0..<2)) --> first
}
private let char_control = NSCharacterSet.controlCharacterSet()
private let char_text = char_control.invertedSet - NSCharacterSet.newlineCharacterSet()
private let char_word = char_text - ",()" - NSCharacterSet.whitespaceCharacterSet()
private let char_space = NSCharacterSet.whitespaceCharacterSet()
private let char_break = NSCharacterSet.newlineCharacterSet()
// TODO: Use this somewhere.
private let char_end = char_control - NSCharacterSet.whitespaceAndNewlineCharacterSet()
private let wordStart: Parser<String>.Function = %(char_word - "#'\"")
private let wordChars: Parser<String>.Function = (%(char_word - "'\""))* --> { strings in join("", strings) }
private let word: Parser<String>.Function = wordStart ++ wordChars --> (+)
private let br: Parser<()>.Function = ignore(%char_break)
private let eof: Parser<()>.Function = { $0 == "" ? ((), "") : nil }
private let comment: Parser<()>.Function = ignore(%"#" ++ (%char_text)+ ++ (br | eof))
// TODO: Escape sequences.
private let singleQuotedChars: Parser<String>.Function = (%(char_text - "'"))* --> { strings in join("", strings) }
private let singleQuoted: Parser<String>.Function = ignore(%"'") ++ singleQuotedChars ++ ignore(%"'")
private let doubleQuotedChars: Parser<String>.Function = (%(char_text - "\""))* --> { strings in join("", strings) }
private let doubleQuoted: Parser<String>.Function = ignore(%"\"") ++ doubleQuotedChars ++ ignore(%"\"")
private let quoted: Parser<String>.Function = singleQuoted | doubleQuoted
private let requiredSpace: Parser<()>.Function = ignore((comment | %char_space)+)
private let optionalSpace: Parser<()>.Function = ignore((comment | %char_space)*)
private let separator: Parser<()>.Function = ignore(optionalSpace ++ %"," ++ optionalSpace)
private let value: Parser<String>.Function = word | quoted
/// A function taking an Int and returning a parser which parses at least that many
/// indentation characters.
func indentation(n: Int) -> Parser<Int>.Function {
return (%char_space * (n..<Int.max)) --> { $0.count }
}
// MARK: Generic combinators
// FIXME: move these into Madness.
/// Delays the evaluation of a parser so that it can be used in a recursive grammar without deadlocking Swift at runtime.
private func lazy<T>(parser: () -> Parser<T>.Function) -> Parser<T>.Function {
return { parser()($0) }
}
/// Returns a parser which produces an array of parse trees produced by `parser` interleaved with ignored parses of `separator`.
///
/// This is convenient for e.g. comma-separated lists.
private func interleave<T, U>(separator: Parser<U>.Function, parser: Parser<T>.Function) -> Parser<[T]>.Function {
return (parser ++ (ignore(separator) ++ parser)*) --> { [$0] + $1 }
}
private func foldr<S: SequenceType, Result>(sequence: S, initial: Result, combine: (S.Generator.Element, Result) -> Result) -> Result {
var generator = sequence.generate()
return foldr(&generator, initial, combine)
}
private func foldr<G: GeneratorType, Result>(inout generator: G, initial: Result, combine: (G.Element, Result) -> Result) -> Result {
return generator.next().map { combine($0, foldr(&generator, initial, combine)) } ?? initial
}
private func | <T, U> (left: Parser<T>.Function, right: String -> U) -> Parser<Either<T, U>>.Function {
return left | { (right($0), $0) }
}
private func | <T> (left: Parser<T>.Function, right: String -> T) -> Parser<T>.Function {
return left | { (right($0), $0) }
}
private func flatMap<T, U>(x: [T], f: T -> [U]) -> [U] {
return reduce(lazy(x).map(f), [], +)
}
// MARK: OGDL
private let children: Parser<[Node]>.Function = lazy { group | (element --> { elem in [ elem ] }) }
private let element = lazy { value ++ (optionalSpace ++ children)|? --> { value, children in Node(value: value, children: children ?? []) } }
// TODO: See Carthage/ogdl-swift#3.
private let block: Int -> Parser<()>.Function = { n in const(nil) }
/// Parses a single descendent element.
///
/// This is an element which may be an in-line descendent, and which may further have in-line descendents of its own.
private let descendent = value --> { Node(value: $0) }
/// Parses a sequence of hierarchically descending elements, e.g.:
///
/// x y z # => Node(x, [Node(y, Node(z))])
public let descendents: Parser<Node>.Function = interleave(requiredSpace, descendent) --> {
foldr(dropLast($0), last($0)!) { $0.nodeByAppendingChildren([ $1 ]) }
}
/// Parses a chain of descendents, optionally ending in a group.
///
/// x y (u, v) # => Node(x, [ Node(y, [ Node(u), Node(v) ]) ])
private let descendentChain: Parser<Node>.Function = (descendents ++ ((optionalSpace ++ group) | const([]))) --> uncurry(Node.nodeByAppendingChildren)
/// Parses a sequence of adjacent sibling elements, e.g.:
///
/// x, y z, w (u, v) # => [ Node(x), Node(y, Node(z)), Node(w, [ Node(u), Node(v) ]) ]
public let adjacent: Parser<[Node]>.Function = lazy { interleave(separator, descendentChain) }
/// Parses a parenthesized sequence of sibling elements, e.g.:
///
/// (x, y z, w) # => [ Node(x), Node(y, Node(z)), Node(w) ]
private let group = lazy { ignore(%"(") ++ optionalSpace ++ adjacent ++ optionalSpace ++ ignore(%")") }
private let subgraph: Int -> Parser<[Node]>.Function = { n in
(descendents ++ lines(n + 1) --> { [ $0.nodeByAppendingChildren($1) ] }) | adjacent
}
private let line: Int -> Parser<[Node]>.Function = fix { line in
{ n in
// TODO: block parsing: ignore(%char_space+ ++ block(n))|?) ++
// See Carthage/ogdl-swift#3.
indentation(n) >>- { n in
subgraph(n) ++ optionalSpace
}
}
}
private let followingLine: Int -> Parser<[Node]>.Function = { n in (ignore(comment | br)+ ++ line(n)) }
private let lines: Int -> Parser<[Node]>.Function = { n in
(line(n)|? ++ followingLine(n)*) --> { ($0 ?? []) + flatMap($1, id) }
}
/// Parses a textual OGDL graph into a list of nodes (and their descendants).
///
/// Example:
///
/// let nodes = parse(graph, "foo (bar, buzz baz)")
public let graph: Parser<[Node]>.Function = ignore(comment | br)* ++ (lines(0) | adjacent) ++ ignore(comment | br)*
| mit | c22ead8caee3fd899b5f60eae862c4ba | 40.544444 | 150 | 0.679861 | 3.624818 | false | false | false | false |
Yoloabdo/CS-193P | Calculator/Calculator/CalculatorSegeueController.swift | 1 | 1013 | //
// CalculatorSegeueController.swift
// Calculator
//
// Created by abdelrahman mohamed on 2/14/16.
// Copyright © 2016 Abdulrhman dev. All rights reserved.
//
import UIKit
class CalculatorSegeueController: CalculatorViewController {
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var destination = segue.destinationViewController
if let navcon = destination as? UINavigationController {
destination = navcon.visibleViewController!
}
if let hvc = destination as? DrawingViewController{
if let identfier = segue.identifier{
switch identfier{
case "drawRes":
hvc.title = brain.discription == "" ? "Graph" :
brain.discription.componentsSeparatedByString(", ").last
hvc.program = brain.program
default:
break
}
}
}
}
}
| mit | 46743bbdc0bc0a1b0501a994ca72a3bb | 30.625 | 81 | 0.576087 | 5.44086 | false | false | false | false |
AppsBoulevard/ABVideoRangeSlider | ABVideoRangeSlider/Classes/ABVideoHelper.swift | 1 | 889 | //
// ABVideoHelper.swift
// selfband
//
// Created by Oscar J. Irun on 27/11/16.
// Copyright © 2016 appsboulevard. All rights reserved.
//
import UIKit
import AVFoundation
class ABVideoHelper: NSObject {
static func thumbnailFromVideo(videoUrl: URL, time: CMTime) -> UIImage{
let asset: AVAsset = AVAsset(url: videoUrl) as AVAsset
let imgGenerator = AVAssetImageGenerator(asset: asset)
imgGenerator.appliesPreferredTrackTransform = true
do{
let cgImage = try imgGenerator.copyCGImage(at: time, actualTime: nil)
let uiImage = UIImage(cgImage: cgImage)
return uiImage
}catch{
}
return UIImage()
}
static func videoDuration(videoURL: URL) -> Float64{
let source = AVURLAsset(url: videoURL)
return CMTimeGetSeconds(source.duration)
}
}
| mit | ef8418ffadbcf075a0da1632dd4b4ab6 | 25.909091 | 81 | 0.638514 | 4.484848 | false | false | false | false |
koher/FailSwif | FailSwifTests/FailSwifTests.swift | 1 | 4499 | import XCTest
import FailSwif
class FailSwifTests: XCTestCase {
func testBasic() {
XCTAssert(toInt(nil).error == .Nil)
XCTAssert(toInt("Swift").error == .IllegalFormat("Swift"))
XCTAssert(toInt("42").value == 42)
}
func testMap() {
XCTAssert(toInt(nil).map { $0 * $0 } == .Failure(.Nil))
XCTAssert(toInt("Swift").map { $0 * $0 } == .Failure(.IllegalFormat("Swift")))
XCTAssert(toInt("42").map { $0 * $0 } == .Success(42 * 42))
}
func testFlatMap() {
XCTAssert(toInt(nil).flatMap { a in toInt(nil).flatMap { b in .Success(a + b) } } == .Failure(.Nil))
XCTAssert(toInt(nil).flatMap { a in toInt("A").flatMap { b in .Success(a + b) } } == .Failure(.Nil))
XCTAssert(toInt("2").flatMap { a in toInt("A").flatMap { b in .Success(a + b) } } == .Failure(.IllegalFormat("A")))
XCTAssert(toInt("2").flatMap { a in toInt("3").flatMap { b in .Success(a + b) } } == .Success(5))
}
func testEquals() {
XCTAssertTrue(toInt(nil) == toInt(nil))
XCTAssertFalse(toInt(nil) == toInt("Swift"))
XCTAssertFalse(toInt(nil) == toInt("42"))
XCTAssertFalse(toInt("Swift") == toInt(nil))
XCTAssertTrue(toInt("Swift") == toInt("Swift"))
XCTAssertFalse(toInt("Swift") == toInt("42"))
XCTAssertFalse(toInt("Swift") == toInt("Swift 2.0"))
XCTAssertFalse(toInt("42") == toInt(nil))
XCTAssertFalse(toInt("42") == toInt("Swift"))
XCTAssertTrue(toInt("42") == toInt("42"))
XCTAssertFalse(toInt("42") == toInt("0"))
}
func testCoalescing() {
XCTAssertEqual(toInt(nil) ?? 0, 0)
XCTAssertEqual(toInt("Swift") ?? 0, 0)
XCTAssertEqual(toInt("42") ?? 0, 42)
}
func testDescription() {
XCTAssertEqual(toInt(nil).description, "Failable(ParseError)")
XCTAssertEqual(toInt("Swift").description, "Failable(ParseError(Swift))")
XCTAssertEqual(toInt("42").description, "Failable(42)")
}
func testExample() {
struct UILabel {
var text: String?
}
let label = UILabel(text: "42")
let a: Failable<Int, ParseError> = toInt(label.text)
if let value = a.value {
print(value)
}
switch a {
case .Success(let value):
print(value)
case .Failure(.Nil):
print("The text is nil.")
case .Failure(.IllegalFormat(let string)):
print("Illegal format: \(string)")
}
let value: Int? = a.value
let error: ParseError? = a.error
let b = a.map { $0 * $0 }
let c = a.flatMap { a0 in b.flatMap { b0 in .Success(a0 + b0) } }
let d: Int = a ?? 0
let e = a.flatMap { .Success($0.successor()) }
func toIntThrowable(string: String?) throws -> Int {
guard let s = string else { throw ParseError.Nil }
guard let int = Int(s) else { throw ParseError.IllegalFormat(s) }
return int
}
func toInt2(string: String?) -> Failable<Int, ParseError> {
do {
return .Success(try toIntThrowable(string))
} catch let error as ParseError {
return .Failure(error)
} catch { // It cannot be ommited with the current version. The error says "the enclosing catch is not exhaustive".
fatalError("Never reaches here.")
}
}
print(a)
print(value)
print(error)
print(b)
print(c)
print(d)
print(e)
}
}
func toInt(string: String?) -> Failable<Int, ParseError> {
guard let s = string else { return .Failure(.Nil) }
guard let int = Int(s) else { return .Failure(.IllegalFormat(s)) }
return .Success(int)
}
enum ParseError: ErrorType, Equatable {
case Nil
case IllegalFormat(String)
}
extension ParseError: CustomStringConvertible {
var description: String {
switch self {
case .Nil:
return "ParseError"
case .IllegalFormat(let string):
return "ParseError(\(string))"
}
}
}
func ==(lhs: ParseError, rhs: ParseError) -> Bool {
switch (lhs, rhs) {
case (.Nil, .Nil):
return true
case (.IllegalFormat(let string1), .IllegalFormat(let string2)):
return string1 == string2
default:
return false
}
}
| mit | 4bfa9f36e70c43d5704a671f0b0742b0 | 31.601449 | 127 | 0.546788 | 4.101185 | false | true | false | false |
sebastiancrossa/smack | Smack/Services/MessageService.swift | 1 | 3385 | //
// MessageService.swift
// Smack
//
// Created by Sebastian Crossa on 8/2/17.
// Copyright © 2017 Sebastian Crossa. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
class MessageService {
static let instance = MessageService()
var channels = [Channel]()
var messages = [Message]()
var unreadChannels = [String]()
var selectedChannel: Channel?
func findAllChannel(completion: @escaping CompletionHandler) {
Alamofire.request(URL_GET_CHANNELS, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: BEARER_HEADER).responseJSON { (response) in
if response.result.error == nil {
guard let data = response.data else { return }
// The channels are returned inside an array
if let json = JSON(data: data).array {
for item in json {
let name = item["name"].stringValue
let description = item["description"].stringValue
let id = item["_id"].stringValue
let channel = Channel(channelTitle: name, channelDescription: description, id: id)
self.channels.append(channel)
}
NotificationCenter.default.post(name: NOTIF_CHANNELS_LOADED, object: nil)
completion(true)
}
} else {
debugPrint(response.result.error as Any)
completion(true)
}
}
}
func findAllMessagesForChannel(channelId: String, completion: @escaping CompletionHandler) {
Alamofire.request("\(URL_GET_MESSAGES)/\(channelId)", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: BEARER_HEADER).responseJSON { (response) in
if response.result.error == nil {
self.clearMessages()
guard let data = response.data else { return }
if let json = JSON(data: data).array {
for item in json {
let messageBody = item["messageBody"].stringValue
let channelId = item["channelId"].stringValue
let id = item["_id"].stringValue
let userName = item["userName"].stringValue
let userAvatar = item["userAvatar"].stringValue
let userAvatarColor = item["userAvatarColor"].stringValue
let timeStamp = item["timeStamp"].stringValue
let message = Message(message: messageBody, userName: userName, channelId: channelId, userAvatar: userAvatar, userAvatarColor: userAvatarColor, id: id, timeStamp: timeStamp)
self.messages.append(message)
}
print(self.messages)
completion(true)
}
} else {
debugPrint(response.result.error as Any)
completion(false)
}
}
}
func clearMessages() {
messages.removeAll()
}
func clearChannels() {
channels.removeAll()
}
}
| apache-2.0 | 41a78211841a9f47c96cde85c796b9c0 | 37.454545 | 197 | 0.527482 | 5.649416 | false | false | false | false |
thefuntasty/LocationManager | Example/LocationManager/ViewController.swift | 1 | 2714 | //
// ViewController.swift
// LocationManager
//
// Created by Jakub Knejzlik on 02/24/2016.
// Copyright (c) 2016 Jakub Knejzlik. All rights reserved.
//
import UIKit
import LocationManager
import CoreLocation
class ViewController: UIViewController {
var observer: LocationObserverLabel?
@IBOutlet var locationRequestLabel: UILabel!
@IBOutlet var locationLabel: UILabel!
@IBOutlet weak var distanceFilterLabel: UILabel!
@IBOutlet weak var distanceFilterSlider: UISlider!
@IBOutlet weak var minimumIntervalLabel: UILabel!
@IBOutlet weak var minimumIntervalSlider: UISlider!
@IBOutlet weak var maximumIntervalLabel: UILabel!
@IBOutlet weak var maximumIntervalSlider: UISlider!
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
refreshLocation(locationLabel)
didUpdateInterface(self)
}
@IBAction func refreshLocation(_ sender: AnyObject) {
locationRequestLabel.text = "...\n"
LocationManager.getCurrentLocation().done { location in
let userLat = String(format: "%f", location.coordinate.latitude)
let userLong = String(format: "%f", location.coordinate.longitude)
self.locationRequestLabel.text = "lat: \(userLat)\nlng: \(userLong)"
}.catch { _ in
self.locationRequestLabel.text = "cannot fetch location"
}
}
@IBAction func didUpdateInterface(_ sender: AnyObject) {
distanceFilterLabel.text = "Distance (\(Int(distanceFilterSlider.value))m)"
minimumIntervalLabel.text = "Minimum interval (\(Int(minimumIntervalSlider.value))s)"
maximumIntervalLabel.text = """
Minimum interval (\(Int(maximumIntervalSlider.value))s) –
forces call even without new location
"""
updateValuesAndInitializeObserver()
}
@objc func updateValuesAndInitializeObserver() {
if let currentObserver = self.observer {
LocationManager.remove(locationObserver: currentObserver)
self.observer = nil
}
let observer = LocationObserverLabel(label: locationLabel)
self.observer = observer
let minimumTimeInterval: Double? = minimumIntervalSlider.value == 0 ? nil : Double(minimumIntervalSlider.value)
let maximumTimeInterval: Double? = maximumIntervalSlider.value == 0 ? nil : Double(maximumIntervalSlider.value)
LocationManager.add(locationObserver: observer,
distanceFilter: Double(distanceFilterSlider.value),
minimumTimeInterval: minimumTimeInterval,
maximumTimeInterval: maximumTimeInterval)
}
}
| mit | 42bac51050241de62255ee2d6b5f16b8 | 34.220779 | 119 | 0.679941 | 4.957952 | false | false | false | false |
sarfraz-akhtar01/SPCalendar | SPCalendar/Classes/CVCalendarDayViewControlCoordinator.swift | 1 | 8834 | //
// CVCalendarDayViewControlCoordinator.swift
// CVCalendar
//
// Created by E. Mozharovsky on 12/27/14.
// Copyright (c) 2014 GameApp. All rights reserved.
//
import UIKit
public final class CVCalendarDayViewControlCoordinator {
// MARK: - Non public properties
fileprivate var selectionSet = Set<DayView>()
fileprivate unowned let calendarView: CalendarView
// MARK: - Public properties
public var selectedStartDayView: DayView?
public var selectedEndDayView: DayView?
public weak var selectedDayView: CVCalendarDayView?
public var animator: CVCalendarViewAnimator! {
return calendarView.animator
}
// MARK: - initialization
public init(calendarView: CalendarView) {
self.calendarView = calendarView
}
}
// MARK: - Animator side callback
extension CVCalendarDayViewControlCoordinator {
public func selectionPerformedOnDayView(_ dayView: DayView) {
// TODO:
}
public func deselectionPerformedOnDayView(_ dayView: DayView) {
if dayView != selectedDayView && calendarView.shouldSelectRange == false {
selectionSet.remove(dayView)
dayView.setDeselectedWithClearing(true)
}
}
public func dequeueDayView(_ dayView: DayView) {
selectionSet.remove(dayView)
}
public func flush() {
selectedDayView = nil
selectedEndDayView = nil
selectedStartDayView = nil
selectionSet.removeAll()
}
}
// MARK: - Animator reference
private extension CVCalendarDayViewControlCoordinator {
func presentSelectionOnDayView(_ dayView: DayView) {
animator.animateSelectionOnDayView(dayView)
//animator?.animateSelection(dayView, withControlCoordinator: self)
}
func presentDeselectionOnDayView(_ dayView: DayView) {
animator.animateDeselectionOnDayView(dayView)
//animator?.animateDeselection(dayView, withControlCoordinator: self)
}
}
// MARK: - Coordinator's control actions
extension CVCalendarDayViewControlCoordinator {
public func performDayViewSingleSelection(_ dayView: DayView) {
selectionSet.insert(dayView)
if selectionSet.count > 1 {
// let count = selectionSet.count-1
for dayViewInQueue in selectionSet {
if dayView != dayViewInQueue {
if dayView.calendarView != nil {
presentDeselectionOnDayView(dayViewInQueue)
}
}
}
}
if let _ = animator {
if selectedDayView != dayView {
selectedDayView = dayView
presentSelectionOnDayView(dayView)
}
}
}
public func performDayViewRangeSelection(_ dayView: DayView) {
if selectionSet.count == 2 {
clearSelection(in: dayView.monthView)
flush()
select(dayView: dayView)
return
}
let calendar = self.calendarView.delegate?.calendar?() ?? Calendar.current
if let previouslySelectedDayView = selectionSet.first,
let previouslySelectedDate = selectionSet.first?.date.convertedDate(calendar: calendar),
let currentlySelectedDate = dayView.date.convertedDate(calendar: calendar),
selectionSet.count == 1 {
//prevent selection of same day twice for range
if previouslySelectedDayView === dayView {
return
}
if previouslySelectedDate < currentlySelectedDate {
selectedStartDayView = previouslySelectedDayView
selectedEndDayView = dayView
self.calendarView.delegate?.didSelectRange?(from: previouslySelectedDayView, to: dayView)
} else {
selectedStartDayView = dayView
selectedEndDayView = previouslySelectedDayView
self.calendarView.delegate?.didSelectRange?(from: dayView, to: previouslySelectedDayView)
}
selectionSet.insert(dayView)
highlightSelectedDays(in: dayView.monthView)
return
}
select(dayView: dayView)
}
public func highlightSelectedDays(in monthView: MonthView) {
clearSelection(in: monthView)
let calendar = self.calendarView.delegate?.calendar?() ?? Calendar.current
let startDate = selectedStartDayView?.date.convertedDate(calendar: calendar)
let endDate = selectedEndDayView?.date.convertedDate(calendar: calendar)
monthView.mapDayViews { dayView in
guard let currDate = dayView.date.convertedDate(calendar: calendar) else {
return
}
if let startDate = startDate,
currDate.compare(startDate) == .orderedSame {
presentSelectionOnDayView(dayView)
return
}
if let startDate = startDate,
let endDate = endDate,
currDate.compare(startDate) == .orderedDescending && currDate.compare(endDate) == .orderedAscending {
presentSelectionOnDayView(dayView)
return
}
if let endDate = endDate,
currDate.compare(endDate) == .orderedSame {
presentSelectionOnDayView(dayView)
return
}
}
}
public func disableDays(in monthView: MonthView) {
var maxSelectableDate: Date? = nil
let calendar = self.calendarView.delegate?.calendar?() ?? Calendar.current
if let startDate = selectedStartDayView?.date.convertedDate(calendar: calendar) {
maxSelectableDate = calendarView.manager.date(after: calendarView.maxSelectableRange, from: startDate)
}
let startDate = selectedStartDayView?.date.convertedDate(calendar: calendar)
disableDays(inMonth: monthView, beforeDate: startDate, afterDate: maxSelectableDate)
}
}
// MARK: - private selection and disabling methods
private extension CVCalendarDayViewControlCoordinator {
func select(dayView: DayView) {
selectedStartDayView = dayView
selectionSet.insert(dayView)
presentSelectionOnDayView(dayView)
}
func disableDays(inMonth monthView:MonthView, beforeDate: Date?, afterDate: Date?) {
let calendar = self.calendarView.delegate?.calendar?() ?? Calendar.current
monthView.mapDayViews { dayView in
guard let currDate = dayView.date.convertedDate(calendar: calendar) else {
return
}
if let earliestDate = calendarView.earliestSelectableDate,
currDate.compare(earliestDate) == .orderedAscending {
disableUserInteraction(for: dayView)
return
}
if let beforeDate = beforeDate,
currDate.compare(beforeDate) == .orderedAscending {
disableUserInteraction(for: dayView)
return
}
if let afterDate = afterDate,
currDate.compare(afterDate) == .orderedDescending || currDate.compare(afterDate) == .orderedSame {
disableUserInteraction(for: dayView)
return
}
if let latestDate = calendarView.latestSelectableDate,
currDate.compare(latestDate) == .orderedDescending {
disableUserInteraction(for: dayView)
return
}
}
}
func disableUserInteraction(for dayView: DayView) {
dayView.isUserInteractionEnabled = false
presentDeselectionOnDayView(dayView)
}
func clearSelection(in monthView: MonthView) {
let calendar = self.calendarView.delegate?.calendar?() ?? Calendar.current
monthView.mapDayViews { dayView in
guard let currDate = dayView.date.convertedDate(calendar: calendar) else {
return
}
var shouldEnable = true
if let earliestDate = calendarView.earliestSelectableDate,
currDate.compare(earliestDate) == .orderedAscending {
shouldEnable = false
}
if let latestDate = calendarView.latestSelectableDate,
currDate.compare(latestDate) == .orderedDescending {
shouldEnable = false
}
if shouldEnable {
dayView.isUserInteractionEnabled = true
}
presentDeselectionOnDayView(dayView)
}
}
}
| mit | dbccf1146a83e2c14b499c5e9a08c7e7 | 33.373541 | 117 | 0.605388 | 5.721503 | false | false | false | false |
chrisjmendez/swift-exercises | Authentication/Parse/D - Data back and Forth/ParseDelta/DetailViewController.swift | 1 | 1577 | //
// DetailViewController.swift
// ParseDelta
//
// Created by tommy trojan on 6/25/15.
// Copyright (c) 2015 Chris Mendez. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
@IBOutlet weak var name: UITextField!
@IBOutlet weak var nameLocal: UITextField!
@IBOutlet weak var capital: UITextField!
@IBOutlet weak var currencyCode: UITextField!
@IBOutlet weak var saveButton: UIBarButtonItem!
//The Parse Object sent from TableView
var currentObj:PFObject?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if let object = currentObj {
name.text = object["nameEnglish"] as! String
nameLocal.text = object["nameLocal"] as! String
capital.text = object["capital"] as! String
currencyCode.text = object["currencyCode"] as! String
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func save(sender: AnyObject) {
if let object = currentObj {
object["nameEnglish"] = name.text
object["nameLocal"] = nameLocal.text
object["capital"] = capital.text
object["currencyCode"] = currencyCode.text
object.saveEventually(nil)
}
//Return to Table View
self.navigationController?.popViewControllerAnimated(true)
}
}
| mit | 50549e16f290137c2786f8e8e4cc95e7 | 28.754717 | 66 | 0.62397 | 4.897516 | false | false | false | false |
Mav3r1ck/Orbit7 | Orbit 7/GameScene.swift | 1 | 7820 | //
// GameScene.swift
// Orbit 7
//
// Created by Aaron Ackerman on 1/17/15.
// Copyright (c) 2015 Mav3r1ck. All rights reserved.
//
import SpriteKit
import AVFoundation
class GameScene: SKScene {
var audioPlayer = AVAudioPlayer()
var audioPlayerTwo = AVAudioPlayer()
var playerScore = 0
var playerlife = 3
let playerScorelabel = SKLabelNode()
var gameLevelLable = SKLabelNode()
//Player Life Images
let playerLifeImage1 = SKSpriteNode(imageNamed: "playerlife.png")
let playerLifeImage2 = SKSpriteNode(imageNamed: "playerlife.png")
let playerLifeImage3 = SKSpriteNode(imageNamed: "playerlife.png")
override func didMoveToView(view: SKView) {
var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Spiraling",ofType: "wav")!)
var error:NSError?
audioPlayerTwo = AVAudioPlayer(contentsOfURL: alertSound, error: &error)
audioPlayerTwo.prepareToPlay()
audioPlayerTwo.play()
audioPlayerTwo.numberOfLoops = -1
// Set background Color
backgroundColor = SKColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1)
// Player Score
playerScorelabel.fontName = "DIN Condensed"
playerScorelabel.fontSize = 28
playerScorelabel.fontColor = SKColor.whiteColor()
playerScorelabel.position = CGPoint(x: size.width/10.0, y: size.height/1.09)
playerScorelabel.text = "Score: \(playerScore)"
addChild(playerScorelabel)
// Level Label
gameLevelLable.fontName = "DIN Condensed"
gameLevelLable.fontSize = 28
gameLevelLable.fontColor = SKColor.whiteColor()
gameLevelLable.position = CGPoint(x: size.width/2, y: size.height/1.09)
gameLevelLable.text = gamelvlLable
addChild(gameLevelLable)
// Player Life Image locations
playerLifeImage1.position = CGPoint(x: size.width/1.10, y: size.height/1.08)
addChild(playerLifeImage1)
playerLifeImage2.position = CGPoint(x: size.width/1.075, y: size.height/1.08)
addChild(playerLifeImage2)
playerLifeImage3.position = CGPoint(x: size.width/1.05, y: size.height/1.08)
addChild(playerLifeImage3)
//alert!
showPauseAlert()
//Background Stars * * *
let stars = SKEmitterNode(fileNamed: "Stars")
stars.position = CGPointMake(400, 200)
addChild(stars)
//Func Add Squares
runAction(SKAction.repeatActionForever(SKAction.sequence([SKAction.runBlock(addNodeToScene),SKAction.waitForDuration(0.9)])
))
}
@objc private func addNodeToScene() {
let radius: CGFloat = 50
let node = Shape.randomShape().createSpriteNode()
let randomY = radius + CGFloat(arc4random_uniform(UInt32(frame.height - radius * 2)))
let initialPosition = CGPoint(x: frame.width + radius, y: randomY)
node.position = initialPosition
addChild(node)
let objectspeed = NSTimeInterval(arc4random_uniform(gameSpeed!))
let endPosition = CGPoint(x: -radius, y: initialPosition.y)
let action = SKAction.moveTo(endPosition, duration: objectspeed)
node.runAction(action) {
node.removeFromParent()
}
if playerlife < 1 {
let loseAction = SKAction.runBlock() {
let reveal = SKTransition.fadeWithDuration(0.1)
let gameOverScene = GameOverScene(size: self.size, won: false)
self.view?.presentScene(gameOverScene, transition: reveal)
self.audioPlayerTwo.stop()
}
node.runAction(SKAction.sequence([loseAction]))
}
}
// Adding Touches
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
let location = (touches.first as? UITouch)?.locationInNode(self)
let node = self.nodeAtPoint(location!)
// Particles
func explosion() {
// Effects
let sparkEmmiter = SKEmitterNode(fileNamed: "ParticleFire.sks")
sparkEmmiter.name = "Fire"
sparkEmmiter.position = location!
sparkEmmiter.targetNode = self
sparkEmmiter.particleLifetime = 1
self.addChild(sparkEmmiter)
// Sounds
var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("zapzap",ofType: "wav")!)
var error:NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error)
audioPlayer.prepareToPlay()
audioPlayer.play()
if (playerScore > gameObjective) {
let reveal = SKTransition.fadeWithDuration(0.5)
let gameOverScene = GameOverScene(size: self.size, won: true)
self.view?.presentScene(gameOverScene, transition: reveal)
audioPlayerTwo.stop()
} else if (playerScore <= -50) {
let reveal = SKTransition.fadeWithDuration(0.5)
let gameOverScene = GameOverScene(size: self.size, won: false)
self.view?.presentScene(gameOverScene, transition: reveal)
audioPlayerTwo.stop()
}
}
func playerScoreUpdate() {
playerScorelabel.text = "Score: \(playerScore)"
node.removeFromParent()
}
if let name = node.name {
var addedScore = 0
switch name {
// Circles
case Shape.RedCircle.name: addedScore = Shape.RedCircle.score
case Shape.BlueCircle.name: addedScore = Shape.BlueCircle.score
case Shape.YellowCircle.name: addedScore = Shape.YellowCircle.score
case Shape.GreenCircle.name: addedScore = Shape.GreenCircle.score
case Shape.PurpleCircle.name: addedScore = Shape.PurpleCircle.score
case Shape.BlackCircle.name: addedScore = Shape.BlackCircle.score
case Shape.Satellite.name: addedScore = Shape.Satellite.score
default: addedScore = 0
}
playerScore = playerScore + addedScore
playerScoreUpdate()
explosion()
} else {
playerlife--
if playerlife == 2 {
playerLifeImage3.hidden = true
} else if playerlife == 1 {
playerLifeImage3.hidden = true
playerLifeImage2.hidden = true
} else if playerlife == 0 {
playerLifeImage3.hidden = true
playerLifeImage2.hidden = true
playerLifeImage1.hidden = true
} else {
playerLifeImage3.hidden = false
playerLifeImage2.hidden = false
playerLifeImage1.hidden = false
}
}
}
func showPauseAlert() {
var alert = UIAlertController(title: "\(gamelvlLable)", message: "Destroy the Asteroids! & Avoid the Satellites!", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Continue", style: UIAlertActionStyle.Default) { _ in
})
self.view?.window?.rootViewController?.presentViewController(alert, animated: true, completion: nil)
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
let dropDown = SKAction.scaleTo(1.0, duration: 0.2)
}
}
| mit | 7c0626e0de989b8f9c862a3b9ff5df63 | 35.203704 | 168 | 0.590921 | 4.777031 | false | false | false | false |
MadArkitekt/Swift_Tutorials_And_Demos | SwiftUI/BullsEye/BullsEye/ViewController.swift | 1 | 2697 | /// Copyright (c) 2019 Razeware LLC
///
/// 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.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// 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 SwiftUI
class ViewController: UIViewController {
@IBOutlet weak var slider: UISlider!
@IBOutlet weak var targetLabel: UILabel!
var currentValue = 50
var targetValue = Int.random(in: 1...100)
override func viewDidLoad() {
super.viewDidLoad()
targetLabel.text = String(targetValue)
}
@IBAction func showAlert() {
let difference = abs(targetValue - currentValue)
let points = 100 - difference
let alert = UIAlertController(title: "Your Score",
message: String(points), preferredStyle: .alert)
let action = UIAlertAction(title: "OK",
style: .default, handler: nil)
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
@IBAction func sliderMoved(_ slider: UISlider) {
currentValue = lroundf(slider.value)
}
@IBSegueAction func openRGBullsEye(_ coder: NSCoder) -> UIViewController? {
UIHostingController(coder: coder, rootView: ContentView(rGuess: 0.5, gGuess: 0.5, bGuess: 0.5))
}
}
| gpl-2.0 | e74ae0c5b50a4f570325c9a3fc9298db | 38.661765 | 99 | 0.727846 | 4.594549 | false | false | false | false |
ladanv/EmailNotifier | EmailNotifier/EmailService.swift | 1 | 3028 | //
// EmailService.swift
// EmailNotifier
//
// Created by Vitaliy.Ladan on 07.12.14.
// Copyright (c) 2014 Vitaliy.Ladan. All rights reserved.
//
class EmailService {
private var session = MCOIMAPSession()
private let folder = "INBOX"
class var instance: EmailService {
struct Static {
static let instance: EmailService = EmailService()
}
return Static.instance
}
func initWithSettingService() -> NSError? {
session = MCOIMAPSession()
session.connectionType = MCOConnectionType.TLS
if let port = (SettingService.port as? String)?.toInt() {
session.port = UInt32(port)
} else {
session.port = 993
}
if let host = SettingService.host {
session.hostname = host
} else {
session.hostname = "imap.gmail.com"
}
if let email = SettingService.email {
session.username = email
}
let failable = SettingService.getPassword()
if failable.failed {
println("Error in EmailService:InitWithSettingService -> \(failable.error)")
return failable.error
} else {
session.password = failable.value
}
return nil
}
func fetchUnread(callback: (error: NSError?, messages: [AnyObject]?) -> Void) {
let searchOperation = session.searchExpressionOperationWithFolder(self.folder, expression: MCOIMAPSearchExpression.searchUnread())
searchOperation.start { (err: NSError!, indexSet: MCOIndexSet!) -> Void in
if err != nil || indexSet.count() == 0 {
callback(error: err, messages: nil)
return
}
let fetchOperation = self.session.fetchMessagesOperationWithFolder(self.folder, requestKind: MCOIMAPMessagesRequestKind.Headers, uids: indexSet)
fetchOperation.start { (err: NSError!, msgs: [AnyObject]!, vanished: MCOIndexSet!) -> Void in
callback(error: err, messages: msgs)
}
}
}
func markAsRead(idx: UInt64, callback: (error: NSError?) -> Void) {
let saveFlagOperation = session.storeFlagsOperationWithFolder(self.folder, uids: MCOIndexSet(index: idx), kind: MCOIMAPStoreFlagsRequestKind.Add, flags: MCOMessageFlag.Seen)
saveFlagOperation.start { (err: NSError!) -> Void in
callback(error: err)
}
}
func markAsDeleted(idx: UInt64, callback: (error: NSError?) -> Void) {
let saveFlagOperation = session.storeFlagsOperationWithFolder(self.folder, uids: MCOIndexSet(index: idx), kind: MCOIMAPStoreFlagsRequestKind.Add, flags: MCOMessageFlag.Deleted)
saveFlagOperation.start { (err: NSError!) -> Void in
callback(error: err)
}
}
func testConnection() -> Bool {
return true
}
} | mit | 2220460cb7d9ee008638d8d5415a4999 | 31.923913 | 184 | 0.588177 | 4.546547 | false | false | false | false |
cfdrake/lobsters-reader | Source/Services/Helpers/URLRequest+PaginatedRequest.swift | 1 | 830 | //
// URLRequest+PaginatedRequest.swift
// LobstersReader
//
// Created by Colin Drake on 6/25/17.
// Copyright © 2017 Colin Drake. All rights reserved.
//
import Foundation
extension URL {
/// Returns the given URL with pagination query parameters added.
func withPagination(page: UInt) -> URL {
let hasBaseUrl = (baseURL != nil)
guard var components = URLComponents(url: self, resolvingAgainstBaseURL: hasBaseUrl) else {
fatalError("Could not unpack URL into components")
}
let pageString = String(describing: page)
components.queryItems = [
URLQueryItem(name: "page", value: pageString)
]
guard let newUrl = components.url else {
fatalError("Could not form new paginated URL")
}
return newUrl
}
}
| mit | 653104f82ac1fb5bf75490f6cf35e835 | 26.633333 | 99 | 0.635706 | 4.530055 | false | false | false | false |
baiIey/events-and-states | Carousel/Carousel/SignInViewController.swift | 1 | 7109 | //
// SignInViewController.swift
// Carousel
//
// Created by Brian Bailey on 2/15/15.
// Copyright (c) 2015 i had that dream again. All rights reserved.
//
import UIKit
class SignInViewController: UIViewController, UIAlertViewDelegate {
@IBOutlet weak var signInTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var loginField: UIView!
@IBOutlet weak var loginContainer: UIView!
// Sign In Group
@IBOutlet weak var signInContainer: UIView!
@IBOutlet weak var signInImage: UIImageView!
@IBOutlet weak var signInButton: UIButton!
@IBOutlet weak var forgotPasswordButton: UIButton!
var signInContainerInitialPosition : CGFloat!
var loginContainerInitialPosition : CGFloat!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// Initialize by turning off button and declaring starting positions for containers
// signInButton.enabled = false
signInContainerInitialPosition = signInContainer.center.y
loginContainerInitialPosition = loginContainer.center.y
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func backArrow(sender: AnyObject) {
navigationController!.popToRootViewControllerAnimated(true)
}
@IBAction func didStartEditing(sender: AnyObject) {
// if (signInTextField.text.isEmpty || passwordTextField.text.isEmpty){
// signInButton.enabled = false
// } else {
// signInButton.enabled = true
// }
}
func alertViewEmail(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) {
// buttonIndex is 0 for Cancel
// buttonIndex ranges from 1-n for the other buttons.
}
func alertViewFailed(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) {
// buttonIndex is 0 for Cancel
// buttonIndex ranges from 1-n for the other buttons.
}
func alertViewLoggingIn(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) {
// buttonIndex is 0 for Cancel
// buttonIndex ranges from 1-n for the other buttons.
}
func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
@IBAction func signInDidPress(sender: AnyObject) {
if (signInTextField.text.isEmpty){
// if Sign In Field is empty, display Enter Email Address alert
var alertViewEmail = UIAlertView(title: "Email Required", message: "Please enter your email address", delegate: nil, cancelButtonTitle: "OK")
alertViewEmail.show()
} else {
// otherwise, do show Sign In alert and check
var alertViewLoading = UIAlertView(title: "Signing In", message: nil, delegate: nil, cancelButtonTitle: nil)
alertViewLoading.show()
delay(1, closure: { () -> () in
// dismiss loading screen
alertViewLoading.dismissWithClickedButtonIndex(0, animated: true)
// check if password is password
if (self.passwordTextField.text == "password") {
self.performSegueWithIdentifier("signInSegue", sender: self)
} else {
//wrong password alert
var alertViewFailed = UIAlertView(title: "Login Failed", message: "Incorrect email or password", delegate: nil, cancelButtonTitle: "OK")
alertViewFailed.show()
}
})
}
}
// animation properties for showing keyboard
func keyboardWillShow(notification: NSNotification!) {
var userInfo = notification.userInfo!
// Get the keyboard height and width from the notification
// Size varies depending on OS, language, orientation
var kbSize = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue().size
var durationValue = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
var animationDuration = durationValue.doubleValue
var curveValue = userInfo[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber
var animationCurve = curveValue.integerValue
UIView.animateWithDuration(animationDuration, delay: 0.0, options: UIViewAnimationOptions(UInt(animationCurve << 16)), animations: {
// moves containers up to new position
self.signInContainer.center.y = 250
self.loginContainer.center.y = 120
// Set view properties in here that you want to match with the animation of the keyboard
// If you need it, you can use the kbSize property above to get the keyboard width and height.
}, completion: nil)
}
// animation for hiding keyboard
func keyboardWillHide(notification: NSNotification!) {
var userInfo = notification.userInfo!
// Get the keyboard height and width from the notification
// Size varies depending on OS, language, orientation
var kbSize = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue().size
var durationValue = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
var animationDuration = durationValue.doubleValue
var curveValue = userInfo[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber
var animationCurve = curveValue.integerValue
UIView.animateWithDuration(animationDuration, delay: 0.0, options: UIViewAnimationOptions(UInt(animationCurve << 16)), animations: {
// moves containers back to origin
self.signInContainer.center.y = self.signInContainerInitialPosition
self.loginContainer.center.y = self.loginContainerInitialPosition
// Set view properties in here that you want to match with the animation of the keyboard
// If you need it, you can use the kbSize property above to get the keyboard width and height.
}, completion: nil)
}
/*
// 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.
// Pass the selected object to the new view controller.
}
*/
}
| mit | afe977fde22e85a2d5499f6db9151475 | 41.568862 | 156 | 0.659305 | 5.602049 | false | false | false | false |
wnanpi95/wnanpi95.github.io | _site/SDMTS_DataWrangler/SDMTS_DataWrangler/StopEdge.swift | 2 | 12433 | //
// StopEdge.swift
// SDMTS_DataWrangler
//
// Created by Will An on 8/9/17.
// Copyright © 2017 Will An. All rights reserved.
//
import Foundation
struct StopEdge: Hashable {
let stop_edge_id: String
let stop_0: String // Makes data set 3x larger, but allows
let stop_1: String // for faster and easier parsing downstream
init(stop_a: String, stop_b: String) {
self.stop_0 = min(stop_a, stop_b)
self.stop_1 = max(stop_a, stop_b)
self.stop_edge_id = stop_0+"_"+stop_1
}
var hashValue: Int {
return stop_edge_id.hashValue
}
static func == (lhs: StopEdge, rhs: StopEdge) -> Bool {
return lhs.stop_edge_id == rhs.stop_edge_id
}
}
func stopEdgeSet(resource: StaticDictionaryCollection) -> Set<StopEdge> {
var returnSet = Set<StopEdge>()
guard resource.trip_idTOstop_id_array != nil else {
print("stop_times.txt NOT read")
return returnSet
}
for (_, stop_id_array) in resource.trip_idTOstop_id_array! {
let count = stop_id_array.count - 1
for i in 0..<count {
let stop_a = stop_id_array[i]
let stop_b = stop_id_array[i+1]
let newStopEdge = StopEdge(stop_a: stop_a, stop_b: stop_b)
returnSet.insert(newStopEdge)
}
}
return returnSet
}
func writeStopEdges(stopEdgeSet: Set<StopEdge>, output: String) {
let file: FileHandle? = FileHandle(forWritingAtPath: output)
if file != nil {
let header = ("stop_edge_id,stop_0,stop_1\n" as NSString).data(using: String.Encoding.utf8.rawValue)
file?.write(header!)
for stopEdge in stopEdgeSet {
let line = stopEdge.stop_edge_id+","
+ stopEdge.stop_0+","
+ stopEdge.stop_1+"\n"
let newLine = (line as NSString).data(using: String.Encoding.utf8.rawValue)
file?.write(newLine!)
}
file?.closeFile()
} else {
print("Ooops! Something went wrong!")
}
}
struct ShapeStopEdge {
let start_idx: Int
let stop_idx: Int
let stop_edge_id: String
}
struct ShapeStop {
let idx: Int
let stop_id: String
}
func findCandidates(position: Position, shapeSet: [ShapeSeq]) -> [Int] {
let bbox: Float = 0.01
var candidateIndices: [Int] = []
let upperLat = position.latitude + bbox
let lowerLat = position.latitude - bbox
let upperLon = position.longitude + bbox
let lowerLon = position.longitude - bbox
for (index, shape) in shapeSet.enumerated() {
let lat = shape.latitude
let lon = shape.longitude
if lat >= lowerLat && lat <= upperLat {
if lon >= lowerLon && lon <= upperLon {
candidateIndices.append(index)
}
}
}
return candidateIndices
}
func findIndex(position: Position, candidates: [Int], shapeSet: [ShapeSeq]) -> Int {
var sepMin: Float = 9999.9
var nearestIndex: Int? = nil
for index in candidates {
let shape = shapeSet[index]
let sepLat = (position.latitude-(shape.latitude))*(position.latitude-(shape.latitude))
let sepLon = (position.longitude-(shape.longitude))*(position.longitude-(shape.longitude))
if sepLat+sepLon < sepMin {
sepMin = sepLat+sepLon
nearestIndex = index
}
}
return nearestIndex!
}
func shape_idTOshapeStopEdges(resource: StaticDictionaryCollection) -> [String: [ShapeStopEdge]] {
var returnDict: [String: [ShapeStopEdge]] = [:]
// Refactor these if you find time (automate print statements)
guard resource.shape_idTOshapeSeq_array != nil else {
print("shapes_unique.txt NOT read")
return returnDict
}
guard resource.stop_idTOstop_position != nil else {
print("stops.txt NOT read")
return returnDict
}
guard resource.trip_idTOstop_id_array != nil else {
print("stop_times.txt NOT read")
return returnDict
}
guard resource.trip_idTOshape_id != nil else {
print("trips.txt NOT read")
return returnDict
}
var shape_idTOshapeStop: [String: [ShapeStop]] = [:]
for (trip_id, stop_id_array) in resource.trip_idTOstop_id_array! {
guard trip_id != "124" else { continue } // skip "air" trip
let shape_id = resource.trip_idTOshape_id?[trip_id]
guard shape_id != "" else { continue } // skip "COR" trip
let shape_array = resource.shape_idTOshapeSeq_array?[shape_id!]
shape_idTOshapeStop[shape_id!] = []
returnDict[shape_id!] = []
for stop_id in stop_id_array {
let position = resource.stop_idTOstop_position?[stop_id]
let candidateIndices = findCandidates(position: position!,
shapeSet: shape_array!)
let index = findIndex(position: position!,
candidates: candidateIndices,
shapeSet: shape_array!)
let newShapeStop = ShapeStop(idx: index, stop_id: stop_id)
shape_idTOshapeStop[shape_id!]?.append(newShapeStop)
}
}
for (shape_id, shapeStop) in shape_idTOshapeStop {
let count = shapeStop.count - 1
for i in 0..<count {
let startIdx = shapeStop[i].idx
let stopIdx = shapeStop[i+1].idx
let stop_a = shapeStop[i].stop_id
let stop_b = shapeStop[i+1].stop_id
let newStopEdge = StopEdge(stop_a: stop_a, stop_b: stop_b)
let newShapeStopEdge = ShapeStopEdge(start_idx: startIdx,
stop_idx: stopIdx,
stop_edge_id: newStopEdge.stop_edge_id)
returnDict[shape_id]?.append(newShapeStopEdge)
}
}
return returnDict
}
func writeShape_StopEdge(shape_idTOShapeStopEdges: [String: [ShapeStopEdge]],
output: String) {
let file: FileHandle? = FileHandle(forWritingAtPath: output)
if file != nil {
let header = ("shape_id,start_idx,stop_idx,stop_edge_id\n" as NSString).data(using: String.Encoding.utf8.rawValue)
file?.write(header!)
for (shape_id, shapeStopEdges) in shape_idTOShapeStopEdges {
for shapeStopEdge in shapeStopEdges {
let line = shape_id+","
+ String(shapeStopEdge.start_idx)+","
+ String(shapeStopEdge.stop_idx)+","
+ shapeStopEdge.stop_edge_id+"\n"
let newLine = (line as NSString).data(using: String.Encoding.utf8.rawValue)
file?.write(newLine!)
}
}
file?.closeFile()
} else {
print("Ooops! Something went wrong!")
}
}
func stop_edge_idTOshape_pts(resource: StaticDictionaryCollection) -> [String: [Position]] {
var returnDict: [String: [Position]] = [:]
for (stop_edge_id, shapeIndices) in resource.stop_edge_idTOshape_indices! {
returnDict[stop_edge_id] = []
let shape_array = resource.shape_idTOshapes_array?[shapeIndices[0].shape_id]
for shapeIndex in shapeIndices {
let startIdx = shapeIndex.start_idx
var stopIdx = shapeIndex.stop_idx
// Hacky fix, consider reevaluating
if stopIdx < startIdx {
let increment = (shapeIndices.count - 1) / (shapeIndices.count - 1 - startIdx)
stopIdx = startIdx + increment
}
for i in startIdx...stopIdx {
let latitude = shape_array?[i].latitude
let longitude = shape_array?[i].longitude
let position = Position(latitude: latitude!,
longitude: longitude!)
if i >= startIdx + 2 {
let last = (returnDict[stop_edge_id]?.count)! - 1
var dropped = false
if abs(latitude! - (returnDict[stop_edge_id]?[last].latitude)!) > 0.001 {
if abs(latitude! - (returnDict[stop_edge_id]?[last-1].latitude)!) > 0.001 {
returnDict[stop_edge_id]?.removeLast()
dropped = true
}
}
if !dropped {
if abs(longitude! - (returnDict[stop_edge_id]?[last].longitude)!) > 0.001{
if abs(longitude! - (returnDict[stop_edge_id]?[last-1].longitude)!) > 0.001{
returnDict[stop_edge_id]?.removeLast()
}
}
}
}
returnDict[stop_edge_id]?.append(position)
}
}
}
return returnDict
}
let entryStartFirst = "\n\t\t{\n"
let entryStart = ",\n\t\t{\n"
let entryEnd = "\t\t}"
func writeStopEdge_shapePtsJSON(stop_edge_idTOshape_pts: [String: [Position]],
output: String) {
let file: FileHandle? = FileHandle(forWritingAtPath: output)
if file != nil {
file?.write(("{\n" as NSString).data(using: String.Encoding.utf8.rawValue)!)
for (stop_edge_id, shape_pt_array) in stop_edge_idTOshape_pts {
file?.write(("\t\""+stop_edge_id+"\": [" as NSString).data(using: String.Encoding.utf8.rawValue)!)
var first = true
for shape_pt in shape_pt_array {
if first {
first = false
file?.write((entryStartFirst as NSString).data(using: String.Encoding.utf8.rawValue)!)
} else {
file?.write((entryStart as NSString).data(using: String.Encoding.utf8.rawValue)!)
}
let entry = "\t\t\t\"shape_pt_lat\": "+String(shape_pt.latitude)
+ ",\n\t\t\t\"shape_pt_lon\": "+String(shape_pt.longitude)+"\n"
file?.write((entry as NSString).data(using: String.Encoding.utf8.rawValue)!)
file?.write((entryEnd as NSString).data(using: String.Encoding.utf8.rawValue)!)
}
first = true
file?.write(("\n\t],\n" as NSString).data(using: String.Encoding.utf8.rawValue)!)
}
file?.write(("}" as NSString).data(using: String.Encoding.utf8.rawValue)!)
file?.closeFile()
} else {
print("Ooops! Something went wrong!")
}
}
func writeStopEdge_shapePts(stop_edge_idTOshape_pts: [String: [Position]],
output: String) {
let file: FileHandle? = FileHandle(forWritingAtPath: output)
if file != nil {
let header = ("stop_edge_id,shape_pt_lat,shape_pt_lon\n" as NSString).data(using: String.Encoding.utf8.rawValue)
file?.write(header!)
for (stop_edge_id, shape_pt_array) in stop_edge_idTOshape_pts {
for shape_pt in shape_pt_array {
let line = stop_edge_id+","
+ String(shape_pt.latitude)+","
+ String(shape_pt.longitude)+"\n"
let newLine = (line as NSString).data(using: String.Encoding.utf8.rawValue)
file?.write(newLine!)
}
}
file?.closeFile()
} else {
print("Ooops! Something went wrong!")
}
}
| mit | 9a055f8cb909e12cb4e48a6114ad1ab0 | 29.696296 | 122 | 0.510859 | 4.298755 | false | false | false | false |
audiokit/AudioKit | Sources/AudioKit/MIDI/BluetoothMIDIButton.swift | 2 | 2543 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
#if os(iOS)
import CoreAudioKit
/// Bluetooth MIDI Central View Controller
class BTMIDICentralViewController: CABTMIDICentralViewController {
var uiViewController: UIViewController?
/// Called when subview area layed out
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done,
target: self,
action: #selector(doneAction))
}
/// Dismiss view cotnroller when done
@objc public func doneAction() {
uiViewController?.dismiss(animated: true, completion: nil)
}
}
/// A button that will pull up a Bluetooth MIDI menu
public class BluetoothMIDIButton: UIButton {
private var realSuperView: UIView?
/// Use this when your button's superview is not the entire screen, or when you prefer
/// the aesthetics of a centered popup window to one with an arrow pointing to your button
public func centerPopupIn(view: UIView) {
realSuperView = view
}
/// Pull up a popover controller when the button is released
public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
let bluetoothMIDIViewController = BTMIDICentralViewController()
let navController = UINavigationController(rootViewController: bluetoothMIDIViewController)
navController.modalPresentationStyle = .popover
let popC = navController.popoverPresentationController
let centerPopup = realSuperView != nil
let displayView = realSuperView ?? self.superview
popC?.permittedArrowDirections = centerPopup ? [] : .any
if let displayView = displayView {
popC?.sourceRect = centerPopup ? CGRect(x: displayView.bounds.midX,
y: displayView.bounds.midY,
width: 0,
height: 0) : self.frame
let controller = displayView.next as? UIViewController
controller?.present(navController, animated: true, completion: nil)
popC?.sourceView = controller?.view
bluetoothMIDIViewController.uiViewController = controller
}
}
}
#endif
| mit | 2148e8d8362578c5f6b58414ccaa4b74 | 39.365079 | 100 | 0.638616 | 5.576754 | false | false | false | false |
manavgabhawala/swift | test/SILGen/dso_handle.swift | 1 | 1102 | // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -Xllvm -sil-full-demangle -emit-silgen %s | %FileCheck %s
// CHECK: sil_global hidden_external [[DSO:@__dso_handle]] : $Builtin.RawPointer
// CHECK-LABEL: sil @main : $@convention(c)
// CHECK: bb0
// CHECK: [[DSOAddr:%[0-9]+]] = global_addr [[DSO]] : $*Builtin.RawPointer
// CHECK-NEXT: [[DSOPtr:%[0-9]+]] = address_to_pointer [[DSOAddr]] : $*Builtin.RawPointer to $Builtin.RawPointer
// CHECK-NEXT: [[DSOPtrStruct:[0-9]+]] = struct $UnsafeRawPointer ([[DSOPtr]] : $Builtin.RawPointer)
// CHECK-LABEL: sil hidden @_T010dso_handle14printDSOHandleS2V0A0_tFfA_
// CHECK: [[DSOAddr:%[0-9]+]] = global_addr [[DSO]] : $*Builtin.RawPointer
// CHECK-NEXT: [[DSOPtr:%[0-9]+]] = address_to_pointer [[DSOAddr]] : $*Builtin.RawPointer to $Builtin.RawPointer
// CHECK-NEXT: [[DSOPtrStruct:%[0-9]+]] = struct $UnsafeRawPointer ([[DSOPtr]] : $Builtin.RawPointer)
// CHECK-NEXT: return [[DSOPtrStruct]] : $UnsafeRawPointer
func printDSOHandle(dso: UnsafeRawPointer = #dsohandle) -> UnsafeRawPointer {
print(dso)
return dso
}
_ = printDSOHandle()
| apache-2.0 | 54067cd1841f4353bfad6341bf4b299d | 46.913043 | 119 | 0.680581 | 3.203488 | false | false | false | false |
jonbrown21/Seafood-Guide-iOS | Seafood Guide/Lingo/ViewControllers/LingoTableViewController.swift | 1 | 4618 | // Converted to Swift 5.1 by Swiftify v5.1.26565 - https://objectivec2swift.com/
//
// LingoTableViewController.swift
// Seafood Guide
//
// Created by Jon Brown on 9/1/14.
// Copyright (c) 2014 Jon Brown Designs. All rights reserved.
//
import UIKit
import CoreData
class LingoTableViewController: UITableViewController, UINavigationBarDelegate, UINavigationControllerDelegate {
var uppercaseFirstLetterOfName = ""
var predicateKey = ""
var window: UIWindow?
var fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult>?
lazy var managedObjectContext: NSManagedObjectContext? = {
return (UIApplication.shared.delegate as? AppDelegate)?.managedObjectContext
}()
var sectionIndexTitles: [AnyHashable] = []
init(lingoSize size: String?) {
super.init(style: .plain)
}
func setupFetchedResultsController() {
let entityName = "Lingo" // Put your entity name here
let request = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
request.sortDescriptors = [NSSortDescriptor.init(key: "titlenews", ascending: true)]
if let managedObjectContext = managedObjectContext {
fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: managedObjectContext, sectionNameKeyPath: "uppercaseFirstLetterOfName", cacheName: nil)
}
do {
try fetchedResultsController?.performFetch()
} catch {
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return fetchedResultsController?.sections?.count ?? 0
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
weak var sectionInfo = fetchedResultsController?.sections?[section]
return sectionInfo?.name
}
override func tableView(_ table: UITableView, numberOfRowsInSection section: Int) -> Int {
weak var sectionInfo = fetchedResultsController?.sections?[section]
return sectionInfo?.numberOfObjects ?? 0
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setupFetchedResultsController()
}
static let tableViewCellIdentifier = "lingocells"
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: LingoTableViewController.tableViewCellIdentifier)
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: LingoTableViewController.tableViewCellIdentifier)
}
cell?.accessoryType = .disclosureIndicator
let lingo = fetchedResultsController?.object(at: indexPath) as? Lingo
cell?.textLabel?.text = lingo?.titlenews
return cell!
}
override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return UILocalizedIndexedCollation.current().sectionIndexTitles
}
override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
return UILocalizedIndexedCollation.current().section(forSectionIndexTitle: index)
}
convenience override init(style: UITableView.Style) {
self.init(lingoSize: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.backBarButtonItem?.title = "Back"
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: - Table view sends data to detail view
override func tableView(_ aTableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let detailViewController = DetailLingoViewController.init(style: .plain)
var sumSections = 0
for i in 0..<indexPath.section {
let rowsInSection = tableView.numberOfRows(inSection: i)
sumSections += rowsInSection
}
let currentRow = sumSections + indexPath.row
let allLingo = fetchedResultsController?.fetchedObjects?[currentRow] as? Lingo
detailViewController.item = allLingo
navigationController?.pushViewController(detailViewController, animated: true)
navigationItem.backBarButtonItem = UIBarButtonItem(title: "Back", style: .plain, target: nil, action: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
navigationItem.hidesBackButton = false
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| mit | 838ae68ad44628b978b0eeb0bc19e5f7 | 32.708029 | 198 | 0.701386 | 5.563855 | false | false | false | false |
wbaumann/SmartReceiptsiOS | SmartReceipts/Persistence/Helpers/Database+Organizations.swift | 2 | 2414 | //
// Database+Organizations.swift
// SmartReceipts
//
// Created by Bogdan Evsenev on 04/09/2019.
// Copyright © 2019 Will Baumann. All rights reserved.
//
import Foundation
struct OrganizationSettingsModels {
let categories: [CategoryModel]
let paymentMethods: [PaymentMethodModel]
let pdfColumns: [ColumnModel]
let csvColumns: [ColumnModel]
}
extension Database {
func importSettings(models: OrganizationSettingsModels) {
let converter = OrganizationModelsConverter()
let csvUuids = (allCSVColumns() as! [ReceiptColumn]).map { $0.uuid }
let pdfUuids = (allPDFColumns() as! [ReceiptColumn]).map { $0.uuid }
let pmUuids = allPaymentMethods().map { $0.uuid }
let catUuids = listAllCategories().map { $0.uuid }
converter.convertColumns(models: models.csvColumns)
.filter { !csvUuids.contains($0.uuid) }
.forEach { addCSVColumn($0) }
converter.convertColumns(models: models.pdfColumns)
.filter { !pdfUuids.contains($0.uuid) }
.forEach { addPDFColumn($0) }
converter.convertPaymentMethods(models: models.paymentMethods)
.filter { !pmUuids.contains($0.uuid) }
.forEach { save($0) }
converter.convertCategories(models: models.categories)
.filter { !catUuids.contains($0.uuid) }
.forEach { save($0) }
}
func exportModels() -> OrganizationSettingsModels {
let converter = OrganizationModelsConverter()
let csvColumns = allCSVColumns() as! [ReceiptColumn]
let pdfColumns = (allPDFColumns() as! [ReceiptColumn])
let paymentMethods = allPaymentMethods() ?? []
let categories = listAllCategories() ?? []
return .init(
categories: converter.convertCategories(categories),
paymentMethods: converter.convertPaymentMethods(paymentMethods),
pdfColumns: converter.convertColumns(pdfColumns),
csvColumns: converter.convertColumns(csvColumns)
)
}
}
extension OrganizationAppSettings {
var models: OrganizationSettingsModels {
return OrganizationSettingsModels(
categories: categories,
paymentMethods: paymentMethods,
pdfColumns: pdfColumns,
csvColumns: csvColumns
)
}
}
| agpl-3.0 | f01fa493cd84cd534e68e58b80e3e265 | 32.513889 | 76 | 0.629507 | 4.604962 | false | false | false | false |
Zewo/Zewo | Sources/Media/JSON/JSONSerializer.swift | 2 | 5204 | #if os(Linux)
import Glibc
#else
import Darwin.C
#endif
import CYAJL
import Venice
public struct JSONSerializerError : Error, CustomStringConvertible {
public let description: String
}
final class JSONSerializer {
private var ordering: Bool
private var buffer: String = ""
private var bufferSize: Int = 0
private var handle: yajl_gen?
convenience init() {
self.init(ordering: false)
}
init(ordering: Bool) {
self.ordering = ordering
self.handle = yajl_gen_alloc(nil)
}
deinit {
yajl_gen_free(handle)
}
func serialize(_ json: JSON, bufferSize: Int = 4096, body: (UnsafeRawBufferPointer) throws -> Void) throws {
yajl_gen_reset(handle, nil)
self.bufferSize = bufferSize
try generate(json, body: body)
try write(body: body)
}
private func generate(_ json: JSON, body: (UnsafeRawBufferPointer) throws -> Void) throws {
switch json {
case .null:
try generateNull()
case .bool(let bool):
try generate(bool)
case .double(let double):
try generate(double)
case .int(let int):
try generate(int)
case .string(let string):
try generate(string)
case .array(let array):
try generate(array, body: body)
case .object(let object):
try generate(object, body: body)
}
try write(highwater: bufferSize, body: body)
}
private func generate(
_ dictionary: [String: JSON],
body: (UnsafeRawBufferPointer
) throws -> Void) throws {
var status = yajl_gen_status_ok
status = yajl_gen_map_open(handle)
try check(status: status)
if ordering {
for (key, value) in dictionary.sorted(by: { $0.0 < $1.0 }) {
try generate(key)
try generate(value, body: body)
}
} else {
for (key, value) in dictionary {
try generate(key)
try generate(value, body: body)
}
}
status = yajl_gen_map_close(handle)
try check(status: status)
}
private func generate(_ array: [JSON], body: (UnsafeRawBufferPointer) throws -> Void) throws {
var status = yajl_gen_status_ok
status = yajl_gen_array_open(handle)
try check(status: status)
for value in array {
try generate(value, body: body)
}
status = yajl_gen_array_close(handle)
try check(status: status)
}
private func generateNull() throws {
try check(status: yajl_gen_null(handle))
}
private func generate(_ string: String) throws {
let status: yajl_gen_status
if string.isEmpty {
status = yajl_gen_string(handle, nil, 0)
} else {
status = string.withCString { cStringPointer in
return cStringPointer.withMemoryRebound(to: UInt8.self, capacity: string.utf8.count) {
yajl_gen_string(self.handle, $0, string.utf8.count)
}
}
}
try check(status: status)
}
private func generate(_ bool: Bool) throws {
try check(status: yajl_gen_bool(handle, (bool) ? 1 : 0))
}
private func generate(_ double: Double) throws {
let string = double.description
let status = string.withCString { pointer in
return yajl_gen_number(self.handle, pointer, string.utf8.count)
}
try check(status: status)
}
private func generate(_ int: Int) throws {
try check(status: yajl_gen_integer(handle, Int64(int)))
}
private func check(status: yajl_gen_status) throws {
switch status {
case yajl_gen_keys_must_be_strings:
throw JSONSerializerError(description: "Keys must be strings.")
case yajl_max_depth_exceeded:
throw JSONSerializerError(description: "Max depth exceeded.")
case yajl_gen_in_error_state:
throw JSONSerializerError(description: "In error state.")
case yajl_gen_invalid_number:
throw JSONSerializerError(description: "Invalid number.")
case yajl_gen_no_buf:
throw JSONSerializerError(description: "No buffer.")
case yajl_gen_invalid_string:
throw JSONSerializerError(description: "Invalid string.")
case yajl_gen_status_ok:
break
case yajl_gen_generation_complete:
break
default:
throw JSONSerializerError(description: "Unknown.")
}
}
private func write(highwater: Int = 0, body: (UnsafeRawBufferPointer) throws -> Void) throws {
var buffer: UnsafePointer<UInt8>? = nil
var bufferLength: Int = 0
guard yajl_gen_get_buf(handle, &buffer, &bufferLength) == yajl_gen_status_ok else {
throw JSONSerializerError(description: "Could not get buffer.")
}
guard bufferLength >= highwater else {
return
}
try body(UnsafeRawBufferPointer(start: buffer, count: bufferLength))
yajl_gen_clear(handle)
}
}
| mit | e2f45e0c0d2acb22759fb05f615585c8 | 28.737143 | 112 | 0.587241 | 4.18328 | false | false | false | false |
gewill/Feeyue | Feeyue/Main/Weibo/CreateRepost/CreateRepostViewController.swift | 1 | 4875 | //
// CreateRepostViewController.swift
// Feeyue
//
// Created by Will on 2/23/16.
// Copyright © 2016 gewill.org. All rights reserved.
//
import UIKit
import RealmSwift
import Kingfisher
class CreateRepostViewController: GWViewController, UITableViewDataSource, UITableViewDelegate, ACEExpandableTableViewDelegate {
@IBOutlet var tableView: UITableView!
@IBOutlet var naviItem: UINavigationItem!
var realm = try! Realm()
var statusId: Int = 0
//一行字的高度
var cellHeight: [CGFloat] = [57, 0]
var repostText = ""
override func viewDidLoad() {
super.viewDidLoad()
self.setupUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// setupUI
func setupUI() {
self.automaticallyAdjustsScrollViewInsets = false
tableView.register(UINib(nibName: "StatusCell", bundle: nil), forCellReuseIdentifier: "StatusCell")
tableView.separatorStyle = .none
naviItem.title = "Repost"
naviItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(CreateRepostViewController.navigationItemCancelClick))
naviItem.rightBarButtonItem = UIBarButtonItem(title: "Send", style: .plain, target: self, action: #selector(CreateRepostViewController.navigationItemSendClick))
}
// MARK: - UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let repostCell = tableView.expandableTextCell(withId: "repost")
let retweetedStatusCell = tableView.dequeueReusableCell(withIdentifier: "StatusCell") as! StatusCell
retweetedStatusCell.backgroundColor = UIColor(red: 0.9606, green: 0.9605, blue: 0.9605, alpha: 1.0)
var newStatus = realm.object(ofType: Status.self, forPrimaryKey: self.statusId as AnyObject)!
if newStatus.retweetedStatus != nil {
repostCell?.text = newStatus.text
newStatus = newStatus.retweetedStatus!
} else {
repostCell?.text = ""
repostCell?.textView.placeholder = "Write repost here."
}
repostCell?.textView.becomeFirstResponder()
retweetedStatusCell.statusId = newStatus.statusId
if let avatarUrl = newStatus.user?.avatarHd {
retweetedStatusCell.avatarImageView.kf.setImage(with: URL(string: avatarUrl)!, placeholder: Placeholder)
}
retweetedStatusCell.userNameLabel.text = newStatus.user?.screenName
// 显示日期,并调换显示位置在 sourceLabel
if let date = newStatus.createdAt {
retweetedStatusCell.sourceLabel.text = date.fullFormateString
}
retweetedStatusCell.createdAtLabel.text = ""
retweetedStatusCell.statusTextLabel?.text = newStatus.text
if indexPath.section == 0 {
return repostCell!
} else {
return retweetedStatusCell
}
}
// MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0 {
return cellHeight[0]
} else {
return UITableView.automaticDimension
}
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 200
}
func tableView(_ tableView: UITableView!, updatedHeight height: CGFloat, at indexPath: IndexPath?) {
if indexPath != nil {
self.cellHeight[indexPath!.section] = height
}
}
func tableView(_ tableView: UITableView!, updatedText text: String!, at indexPath: IndexPath!) {
print(text)
self.repostText = text
}
// MARK: - response methods
@objc func navigationItemCancelClick() {
self.dismiss(animated: false, completion: nil)
}
@objc func navigationItemSendClick() {
var newStatus = realm.object(ofType: Status.self, forPrimaryKey: self.statusId as AnyObject)!
if newStatus.retweetedStatus != nil {
newStatus = newStatus.retweetedStatus!
}
WeiboService.repostStatus(statusId: newStatus.statusId, text: self.repostText, isComment: 0) { (stateCode, error) -> Void in
if stateCode == .success {
GWHUD.showSuccess(withStatus: "Success to repost.")
} else if stateCode == .error {
GWHUD.showError(withStatus: error)
}
}
self.dismiss(animated: true, completion: nil)
}
}
| mit | 78a1433e74d1acf29696092bd3a3bf81 | 31.675676 | 169 | 0.658809 | 4.995868 | false | false | false | false |
brentdax/swift | stdlib/public/core/StringGuts.swift | 1 | 36706 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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
//
//===----------------------------------------------------------------------===//
import SwiftShims
//
// Largely inspired by string-recore at
// https://github.com/apple/swift/pull/10747.
//
//
// StringGuts is always 16 bytes on both 32bit and 64bit platforms. This
// effectively makes the worse-case (from a spare bit perspective) ABIs be the
// 64bit ones, as all 32bit pointers effectively have a 32-bit address space
// while the 64bit ones have a 56-bit address space.
//
// Of the 64bit ABIs, x86_64 has the fewest spare bits, so that's the ABI we
// design for.
//
// FIXME: what about ppc64 and s390x?
//
@_fixed_layout
public // FIXME
struct _StringGuts {
public // FIXME for testing only
var _object: _StringObject
public // FIXME for testing only
var _otherBits: UInt // (Mostly) count or inline storage
@inlinable
@inline(__always)
public
init(object: _StringObject, otherBits: UInt) {
self._object = object
self._otherBits = otherBits
_invariantCheck()
}
public typealias _RawBitPattern = (_StringObject._RawBitPattern, UInt)
@inlinable
internal var rawBits: _RawBitPattern {
@inline(__always)
get {
return (_object.rawBits, _otherBits)
}
}
init(rawBits: _RawBitPattern) {
self.init(
object: _StringObject(noReallyHereAreTheRawBits: rawBits.0),
otherBits: rawBits.1)
}
}
extension _StringGuts {
@inlinable // FIXME(sil-serialize-all)
internal func _invariantCheck() {
#if INTERNAL_CHECKS_ENABLED
_object._invariantCheck()
if _object.isNative {
_sanityCheck(UInt(_object.nativeRawStorage.count) == self._otherBits)
} else if _object.isUnmanaged {
} else if _object.isCocoa {
if _object.isContiguous {
_sanityCheck(_isValidAddress(_otherBits))
} else {
_sanityCheck(_otherBits == 0)
}
} else if _object.isSmall {
_smallUTF8String._invariantCheck()
} else {
fatalError("Unimplemented string form")
}
#if arch(i386) || arch(arm)
_sanityCheck(MemoryLayout<String>.size == 12, """
the runtime is depending on this, update Reflection.mm and \
this if you change it
""")
#else
_sanityCheck(MemoryLayout<String>.size == 16, """
the runtime is depending on this, update Reflection.mm and \
this if you change it
""")
#endif
#endif // INTERNAL_CHECKS_ENABLED
}
@inlinable
@inline(__always)
internal mutating func _isUniqueNative() -> Bool {
guard _isNative else { return false }
// Note that the isUnique test must be in a separate statement;
// `isNative && _isUnique` always evaluates to false in debug builds,
// because SILGen keeps the self reference in `isNative` alive for the
// duration of the expression.
// Note that we have to perform this operation here, and not as a (even
// mutating) method on our _StringObject to avoid all chances of a semantic
// copy.
//
// FIXME: Super hacky. Is there a better way?
defer { _fixLifetime(self) }
var bitPattern = _object.referenceBits
return _isUnique_native(&bitPattern)
}
}
extension _StringGuts {
@inlinable
internal var isASCII: Bool {
@inline(__always) get { return _object.isContiguousASCII }
}
@inlinable
internal
var _isASCIIOrSmallASCII: Bool {
@inline(__always) get {
return isASCII || _isSmall && _smallUTF8String.isASCII
}
}
@inlinable
internal var _isNative: Bool {
return _object.isNative
}
@inlinable
internal var _isCocoa: Bool {
return _object.isCocoa
}
@inlinable
internal var _isUnmanaged: Bool {
return _object.isUnmanaged
}
@inlinable
internal var _isSmall: Bool {
return _object.isSmall
}
@inlinable
internal var _owner: AnyObject? {
return _object.owner
}
@inlinable
internal var isSingleByte: Bool {
// FIXME: Currently used to sometimes mean contiguous ASCII
return _object.isSingleByte
}
@inlinable
internal
var _isEmptySingleton: Bool {
return _object.isEmptySingleton
}
@inlinable
internal var byteWidth: Int {
return _object.byteWidth
}
@inlinable
internal
var _nativeCount: Int {
@inline(__always) get {
_sanityCheck(_object.isNative)
return Int(bitPattern: _otherBits)
}
@inline(__always) set {
_sanityCheck(_object.isNative)
_sanityCheck(newValue >= 0)
_otherBits = UInt(bitPattern: newValue)
}
}
// TODO(SSO): consider a small-checking variant
@inlinable
@inline(__always)
internal
init<CodeUnit>(_large storage: _SwiftStringStorage<CodeUnit>)
where CodeUnit : FixedWidthInteger & UnsignedInteger {
_sanityCheck(storage.count >= 0)
self.init(
object: _StringObject(storage),
otherBits: UInt(bitPattern: storage.count))
}
}
extension _StringGuts {
@inlinable
@inline(__always)
internal init() {
self.init(object: _StringObject(), otherBits: 0)
_invariantCheck()
}
}
#if _runtime(_ObjC)
extension _StringGuts {
//
// FIXME(TODO: JIRA): HACK HACK HACK: Work around for ARC :-(
//
@usableFromInline
@_effects(readonly)
internal static func getCocoaLength(_unsafeBitPattern: UInt) -> Int {
return _stdlib_binary_CFStringGetLength(
Builtin.reinterpretCast(_unsafeBitPattern))
}
@inlinable
var _cocoaCount: Int {
@inline(__always)
get {
_sanityCheck(_object.isCocoa)
defer { _fixLifetime(self) }
return _StringGuts.getCocoaLength(
_unsafeBitPattern: _object.referenceBits)
// _stdlib_binary_CFStringGetLength(_object.asCocoaObject)
}
}
@inlinable
var _cocoaRawStart: UnsafeRawPointer {
@inline(__always)
get {
_sanityCheck(_object.isContiguousCocoa)
_sanityCheck(_isValidAddress(_otherBits))
return UnsafeRawPointer(
bitPattern: _otherBits
)._unsafelyUnwrappedUnchecked
}
}
@inlinable
func _asContiguousCocoa<CodeUnit>(
of codeUnit: CodeUnit.Type = CodeUnit.self
) -> _UnmanagedString<CodeUnit>
where CodeUnit : FixedWidthInteger & UnsignedInteger {
_sanityCheck(_object.isContiguousCocoa)
_sanityCheck(CodeUnit.bitWidth == _object.bitWidth)
let start = _cocoaRawStart.assumingMemoryBound(to: CodeUnit.self)
return _UnmanagedString(start: start, count: _cocoaCount)
}
// TODO(SSO): consider a small-checking variant
@usableFromInline
internal
init(
_largeNonTaggedCocoaObject s: _CocoaString,
count: Int,
isSingleByte: Bool,
start: UnsafeRawPointer?
) {
_sanityCheck(!_isObjCTaggedPointer(s))
guard count > 0 else {
self.init()
return
}
self.init(
object: _StringObject(
cocoaObject: s,
isSingleByte: isSingleByte,
isContiguous: start != nil),
otherBits: UInt(bitPattern: start))
if start == nil {
_sanityCheck(_object.isOpaque)
} else {
_sanityCheck(_object.isContiguous)
}
}
}
#else // !_runtime(_ObjC)
extension _StringGuts {
// TODO(SSO): consider a small-checking variant
@inline(never)
@usableFromInline
internal
init<S: _OpaqueString>(_large opaqueString: S) {
self.init(
object: _StringObject(opaqueString: opaqueString),
otherBits: UInt(bitPattern: opaqueString.length))
}
}
#endif // _runtime(_ObjC)
extension _StringGuts {
@inlinable
internal var _unmanagedRawStart: UnsafeRawPointer {
@inline(__always) get {
_sanityCheck(_object.isUnmanaged)
return _object.asUnmanagedRawStart
}
}
@inlinable
internal var _unmanagedCount: Int {
@inline(__always) get {
_sanityCheck(_object.isUnmanaged)
return Int(bitPattern: _otherBits)
}
}
@inlinable
@inline(__always)
internal
func _asUnmanaged<CodeUnit>(
of codeUnit: CodeUnit.Type = CodeUnit.self
) -> _UnmanagedString<CodeUnit>
where CodeUnit : FixedWidthInteger & UnsignedInteger {
_sanityCheck(_object.isUnmanaged)
_sanityCheck(CodeUnit.bitWidth == _object.bitWidth)
let start = _unmanagedRawStart.assumingMemoryBound(to: CodeUnit.self)
let count = _unmanagedCount
_sanityCheck(count >= 0)
return _UnmanagedString(start: start, count: count)
}
// TODO(SSO): consider a small-checking variant
@inlinable
init<CodeUnit>(_large s: _UnmanagedString<CodeUnit>)
where CodeUnit : FixedWidthInteger & UnsignedInteger {
_sanityCheck(s.count >= 0)
self.init(
object: _StringObject(unmanaged: s.start),
otherBits: UInt(bitPattern: s.count))
_sanityCheck(_object.isUnmanaged)
_sanityCheck(_unmanagedRawStart == s.rawStart)
_sanityCheck(_unmanagedCount == s.count)
_invariantCheck()
}
}
// Small strings
extension _StringGuts {
@inlinable
internal var _smallUTF8Count: Int {
@inline(__always) get {
#if arch(i386) || arch(arm)
unsupportedOn32bit()
#else
return _object.smallUTF8Count
#endif
}
}
@inlinable
internal var _smallUTF8String: _SmallUTF8String {
@inline(__always) get {
#if arch(i386) || arch(arm)
unsupportedOn32bit()
#else
return _SmallUTF8String(
_rawBits: (low: _otherBits, high: _object.asSmallUTF8SecondWord))
#endif
}
}
@inlinable
@inline(__always)
internal init(_ small: _SmallUTF8String) {
#if arch(i386) || arch(arm)
unsupportedOn32bit()
#else
self.init(
object: _StringObject(_smallUTF8SecondWord: small._rawBits.high),
otherBits: small._rawBits.low)
#endif
}
}
extension _StringGuts {
@inlinable
internal
var _unmanagedASCIIView: _UnmanagedString<UInt8> {
@_effects(readonly)
get {
_sanityCheck(_object.isContiguousASCII)
if _object.isUnmanaged {
return _asUnmanaged()
} else if _object.isNative {
return _object.nativeStorage(of: UInt8.self).unmanagedView
} else {
#if _runtime(_ObjC)
_sanityCheck(_object.isContiguousCocoa)
return _asContiguousCocoa(of: UInt8.self)
#else
Builtin.unreachable()
#endif
}
}
}
@inlinable
internal
var _unmanagedUTF16View: _UnmanagedString<UTF16.CodeUnit> {
@_effects(readonly)
get {
_sanityCheck(_object.isContiguousUTF16)
if _object.isUnmanaged {
return _asUnmanaged()
} else if _object.isNative {
return _object.nativeStorage(of: UTF16.CodeUnit.self).unmanagedView
} else {
#if _runtime(_ObjC)
_sanityCheck(_object.isContiguousCocoa)
return _asContiguousCocoa(of: UTF16.CodeUnit.self)
#else
Builtin.unreachable()
#endif
}
}
}
}
extension _StringGuts {
@inlinable
internal
var _isOpaque: Bool {
@inline(__always)
get { return _object.isOpaque }
}
@inlinable
internal
var _isContiguous: Bool {
@inline(__always)
get { return _object.isContiguous }
}
}
#if _runtime(_ObjC)
extension _StringGuts {
@usableFromInline
var _underlyingCocoaString: _CocoaString? {
if _object.isNative {
return _object.nativeRawStorage
}
if _object.isCocoa {
return _object.asCocoaObject
}
return nil
}
}
#endif
extension _StringGuts {
/// Return the object identifier for the reference counted heap object
/// referred to by this string (if any). This is useful for testing allocation
/// behavior.
@usableFromInline
internal var _objectIdentifier: ObjectIdentifier? {
if _object.isNative {
return ObjectIdentifier(_object.nativeRawStorage)
}
#if _runtime(_ObjC)
if _object.isCocoa {
return ObjectIdentifier(_object.asCocoaObject)
}
#endif
return nil
}
}
extension _StringGuts {
// @opaque
internal func _asOpaque() -> _UnmanagedOpaqueString {
#if _runtime(_ObjC)
if _object.isSmall {
fatalError("Invariant violated: opaque small strings")
}
_sanityCheck(_object.isNoncontiguousCocoa)
return _UnmanagedOpaqueString(_object.asCocoaObject, count: _cocoaCount)
#else
_sanityCheck(_object.isOpaque)
return _UnmanagedOpaqueString(_object.asOpaqueObject, count: _opaqueCount)
#endif
}
@usableFromInline
internal var _opaqueCount: Int {
fatalError("TODO: non-cocoa opaque string support")
}
}
extension _StringGuts {
internal
func _dump() {
#if INTERNAL_CHECKS_ENABLED
func printHex<U: UnsignedInteger>(_ uint: U, newline: Bool = true) {
print(String(uint, radix: 16), terminator: newline ? "\n" : "")
}
func fromAny(_ x: AnyObject) -> UInt {
return Builtin.reinterpretCast(x)
}
func fromPtr(_ x: UnsafeMutableRawPointer) -> UInt {
return Builtin.reinterpretCast(x)
}
print("_StringGuts(", terminator: "")
defer { print(")") }
printHex(rawBits.0, newline: false)
print(" ", terminator: "")
printHex(rawBits.1, newline: false)
print(": ", terminator: "")
if _object.isNative {
let storage = _object.nativeRawStorage
print("native ", terminator: "")
printHex(Builtin.reinterpretCast(storage) as UInt, newline: false)
print(" start: ", terminator: "")
printHex(
Builtin.reinterpretCast(storage.rawStart) as UInt, newline: false)
print(" count: ", terminator: "")
print(storage.count, terminator: "")
print("/", terminator: "")
print(storage.capacity, terminator: "")
return
}
if _object.isSmall {
self._smallUTF8String._dump()
return
}
#if _runtime(_ObjC)
if _object.isCocoa {
print("cocoa ", terminator: "")
printHex(
Builtin.reinterpretCast(_object.asCocoaObject) as UInt, newline: false)
print(" start: ", terminator: "")
if _object.isContiguous {
printHex(
Builtin.reinterpretCast(_cocoaRawStart) as UInt, newline: false)
} else {
print("<opaque>", terminator: "")
}
print(" count: ", terminator: "")
print(_cocoaCount, terminator: "")
return
}
#else // no ObjC
if _object.isOpaque {
print("opaque ", terminator: "")
printHex(
Builtin.reinterpretCast(_object.asOpaqueObject) as UInt, newline: false)
print(" count: ", terminator: "")
print(_opaqueCount, terminator: "")
return
}
#endif // ObjC
if _object.isUnmanaged {
print("unmanaged ", terminator: "")
printHex(
Builtin.reinterpretCast(_unmanagedRawStart) as UInt, newline: false)
print(" count: ", terminator: "")
print(_unmanagedCount, terminator: "")
return
}
print("error", terminator: "")
if isASCII {
print(" <ascii>", terminator: "")
}
else {
print(" <utf16>", terminator: "")
}
#endif // INTERNAL_CHECKS_ENABLED
}
}
//
// String API helpers
//
extension _StringGuts {
// Return a contiguous _StringGuts with the same contents as this one.
// Use the existing guts if possible; otherwise copy the string into a
// new buffer.
@usableFromInline
internal
func _extractContiguous<CodeUnit>(
of codeUnit: CodeUnit.Type = CodeUnit.self
) -> _StringGuts
where CodeUnit : FixedWidthInteger & UnsignedInteger {
if _fastPath(
_object.isContiguous && CodeUnit.bitWidth == _object.bitWidth) {
return self
}
// TODO (TODO: JIRA): check if we're small, extract that.
let count = self.count
return _StringGuts(
_large: _copyToNativeStorage(of: CodeUnit.self, from: 0..<count))
}
@usableFromInline
internal
func _extractContiguousUTF16() -> _StringGuts {
return _extractContiguous(of: UTF16.CodeUnit.self)
}
@usableFromInline
internal
func _extractContiguousASCII() -> _StringGuts {
return _extractContiguous(of: UInt8.self)
}
// Return a native storage object with the same contents as this string.
// Use the existing buffer if possible; otherwise copy the string into a
// new buffer.
@usableFromInline
@_specialize(where CodeUnit == UInt8)
@_specialize(where CodeUnit == UInt16)
internal
func _extractNativeStorage<CodeUnit>(
of codeUnit: CodeUnit.Type = CodeUnit.self
) -> _SwiftStringStorage<CodeUnit>
where CodeUnit : FixedWidthInteger & UnsignedInteger {
if _fastPath(_object.isNative && CodeUnit.bitWidth == _object.bitWidth) {
return _object.nativeStorage()
}
let count = self.count
return _copyToNativeStorage(of: CodeUnit.self, from: 0..<count)
}
@_specialize(where CodeUnit == UInt8)
@_specialize(where CodeUnit == UInt16)
internal
func _copyToNativeStorage<CodeUnit>(
of codeUnit: CodeUnit.Type = CodeUnit.self,
from range: Range<Int>,
unusedCapacity: Int = 0
) -> _SwiftStringStorage<CodeUnit>
where CodeUnit : FixedWidthInteger & UnsignedInteger {
_sanityCheck(unusedCapacity >= 0)
let storage = _SwiftStringStorage<CodeUnit>.create(
capacity: range.count + unusedCapacity,
count: range.count)
self._copy(range: range, into: storage.usedBuffer)
return storage
}
@usableFromInline // @testable
func _extractSlice(_ range: Range<Int>) -> _StringGuts {
if range.isEmpty { return _StringGuts() }
if range == 0..<count { return self }
if self._isSmall {
return _StringGuts(self._smallUTF8String[range])
}
if self.isASCII {
defer { _fixLifetime(self) }
let ascii = self._unmanagedASCIIView[range]
if let small = _SmallUTF8String(ascii.buffer) {
return _StringGuts(small)
}
if _object.isUnmanaged {
return _StringGuts(_large: ascii)
}
return _StringGuts(
_large: _copyToNativeStorage(of: UInt8.self, from: range))
}
// TODO(SSO): small UTF-16 strings
if _object.isUnmanaged {
return _StringGuts(_large: _unmanagedUTF16View[range])
}
return _StringGuts(
_large: _copyToNativeStorage(of: UTF16.CodeUnit.self, from: range))
}
internal mutating func allocationParametersForMutableStorage<CodeUnit>(
of type: CodeUnit.Type,
unusedCapacity: Int
) -> (count: Int, capacity: Int)?
where CodeUnit : FixedWidthInteger & UnsignedInteger {
if _slowPath(!_object.isNative) {
return (self.count, count + unusedCapacity)
}
unowned(unsafe) let storage = _object.nativeRawStorage
defer { _fixLifetime(self) }
if _slowPath(storage.unusedCapacity < unusedCapacity) {
// Need more space; borrow Array's exponential growth curve.
return (
storage.count,
Swift.max(
_growArrayCapacity(storage.capacity),
count + unusedCapacity))
}
// We have enough space; check if it's unique and of the correct width.
if _fastPath(_object.bitWidth == CodeUnit.bitWidth) {
if _fastPath(_isUniqueNative()) {
return nil
}
}
// If not, allocate new storage, but keep existing capacity.
return (storage.count, storage.capacity)
}
// Convert ourselves (if needed) to a native string with the specified storage
// parameters and call `body` on the resulting native storage.
internal
mutating func withMutableStorage<CodeUnit, R>(
of type: CodeUnit.Type = CodeUnit.self,
unusedCapacity: Int,
_ body: (Unmanaged<_SwiftStringStorage<CodeUnit>>) -> R
) -> R
where CodeUnit : FixedWidthInteger & UnsignedInteger {
let paramsOpt = allocationParametersForMutableStorage(
of: CodeUnit.self,
unusedCapacity: unusedCapacity)
if _fastPath(paramsOpt == nil) {
unowned(unsafe) let storage = _object.nativeStorage(of: CodeUnit.self)
let result = body(Unmanaged.passUnretained(storage))
self._nativeCount = storage.count
_fixLifetime(self)
return result
}
let params = paramsOpt._unsafelyUnwrappedUnchecked
let unmanagedRef = Unmanaged.passRetained(
self._copyToNativeStorage(
of: CodeUnit.self,
from: 0..<params.count,
unusedCapacity: params.capacity - params.count))
let result = body(unmanagedRef)
self = _StringGuts(_large: unmanagedRef.takeRetainedValue())
_fixLifetime(self)
return result
}
@inline(__always)
internal
mutating func withMutableASCIIStorage<R>(
unusedCapacity: Int,
_ body: (Unmanaged<_ASCIIStringStorage>) -> R
) -> R {
return self.withMutableStorage(
of: UInt8.self, unusedCapacity: unusedCapacity, body)
}
@inline(__always)
internal
mutating func withMutableUTF16Storage<R>(
unusedCapacity: Int,
_ body: (Unmanaged<_UTF16StringStorage>) -> R
) -> R {
return self.withMutableStorage(
of: UTF16.CodeUnit.self, unusedCapacity: unusedCapacity, body)
}
}
//
// String API
//
extension _StringGuts {
@inlinable
internal var _hasStoredCount: Bool {
@inline(__always) get { return !_object.isSmallOrCocoa }
}
@inlinable
internal var startIndex: Int {
return 0
}
@inlinable
internal var endIndex: Int {
@inline(__always) get { return count }
}
@inlinable
internal var count: Int {
if _slowPath(!_hasStoredCount) {
return _nonStoredCount
}
// TODO(StringObject): Mask off the high bits
_sanityCheck(Int(self._otherBits) >= 0)
return Int(bitPattern: self._otherBits)
}
@usableFromInline
internal
var _nonStoredCount: Int {
@_effects(readonly)
get {
if _object.isSmall {
return _object.smallUTF8Count
}
#if _runtime(_ObjC)
_sanityCheck(_object.isCocoa)
return _cocoaCount
#else
_sanityCheck(_object.isOpaque)
return _opaqueCount
#endif
}
}
@inlinable
internal var capacity: Int {
if _fastPath(_object.isNative) {
return _object.nativeRawStorage.capacity
}
return 0
}
/// Get the UTF-16 code unit stored at the specified position in this string.
@inlinable // FIXME(sil-serialize-all)
func codeUnit(atCheckedOffset offset: Int) -> UTF16.CodeUnit {
if _slowPath(_isOpaque) {
return _opaqueCodeUnit(atCheckedOffset: offset)
} else if isASCII {
return _unmanagedASCIIView.codeUnit(atCheckedOffset: offset)
} else {
return _unmanagedUTF16View.codeUnit(atCheckedOffset: offset)
}
}
@usableFromInline // @opaque
func _opaqueCodeUnit(atCheckedOffset offset: Int) -> UTF16.CodeUnit {
_sanityCheck(_isOpaque)
// TODO: ascii fast path, and reconsider this whole API anyways
if self._isSmall {
return self._smallUTF8String.withUnmanagedASCII {
$0.codeUnit(atCheckedOffset: offset)
}
}
defer { _fixLifetime(self) }
return _asOpaque().codeUnit(atCheckedOffset: offset)
}
// Copy code units from a slice of this string into a buffer.
internal func _copy<CodeUnit>(
range: Range<Int>,
into dest: UnsafeMutableBufferPointer<CodeUnit>)
where CodeUnit : FixedWidthInteger & UnsignedInteger {
_sanityCheck(CodeUnit.bitWidth == 8 || CodeUnit.bitWidth == 16)
_sanityCheck(dest.count >= range.count)
if _slowPath(_isOpaque) {
_opaqueCopy(range: range, into: dest)
return
}
defer { _fixLifetime(self) }
if isASCII {
_unmanagedASCIIView[range]._copy(into: dest)
} else {
_unmanagedUTF16View[range]._copy(into: dest)
}
}
internal func _opaqueCopy<CodeUnit>(
range: Range<Int>,
into dest: UnsafeMutableBufferPointer<CodeUnit>)
where CodeUnit : FixedWidthInteger & UnsignedInteger {
_sanityCheck(_isOpaque)
if _fastPath(self._isSmall) {
var slice = self._smallUTF8String[range]
slice._copy(into: dest)
return
}
defer { _fixLifetime(self) }
_asOpaque()[range]._copy(into: dest)
}
@usableFromInline
mutating func reserveUnusedCapacity(
_ unusedCapacity: Int,
ascii: Bool = false
) {
if _fastPath(_isUniqueNative()) {
if _fastPath(
ascii == (_object.bitWidth == 8) &&
_object.nativeRawStorage.unusedCapacity >= unusedCapacity) {
return
}
}
// TODO (TODO: JIRA): check if we're small and still within capacity
if ascii {
let storage = _copyToNativeStorage(
of: UInt8.self,
from: 0..<self.count,
unusedCapacity: unusedCapacity)
self = _StringGuts(_large: storage)
} else {
let storage = _copyToNativeStorage(
of: UTF16.CodeUnit.self,
from: 0..<self.count,
unusedCapacity: unusedCapacity)
self = _StringGuts(_large: storage)
}
_invariantCheck()
}
@usableFromInline // @testable
mutating func reserveCapacity(_ capacity: Int) {
if _fastPath(_isUniqueNative()) {
if _fastPath(_object.nativeRawStorage.capacity >= capacity) {
return
}
}
// Small strings can accomodate small capacities
if capacity <= _SmallUTF8String.capacity {
return
}
let selfCount = self.count
if isASCII {
let storage = _copyToNativeStorage(
of: UInt8.self,
from: 0..<selfCount,
unusedCapacity: Swift.max(capacity - count, 0))
self = _StringGuts(_large: storage)
} else {
let storage = _copyToNativeStorage(
of: UTF16.CodeUnit.self,
from: 0..<selfCount,
unusedCapacity: Swift.max(capacity - count, 0))
self = _StringGuts(_large: storage)
}
_invariantCheck()
}
internal
mutating func append(_ other: _UnmanagedASCIIString) {
guard other.count > 0 else { return }
if self._isSmall {
if let result = self._smallUTF8String._appending(other.buffer) {
self = _StringGuts(result)
return
}
}
if _object.isSingleByte {
withMutableASCIIStorage(unusedCapacity: other.count) { storage in
storage._value._appendInPlace(other)
}
} else {
withMutableUTF16Storage(unusedCapacity: other.count) { storage in
storage._value._appendInPlace(other)
}
}
}
internal
mutating func append(_ other: _UnmanagedUTF16String) {
guard other.count > 0 else { return }
withMutableUTF16Storage(unusedCapacity: other.count) { storage in
storage._value._appendInPlace(other)
}
}
internal
mutating func append(_ other: _UnmanagedOpaqueString) {
guard other.count > 0 else { return }
withMutableUTF16Storage(unusedCapacity: other.count) { storage in
storage._value._appendInPlace(other)
}
}
internal
mutating func append<S: StringProtocol>(_ other: S) {
self.append(other._wholeString._guts, range: other._encodedOffsetRange)
}
@usableFromInline // @testable
internal
mutating func append(_ other: _StringGuts) {
// FIXME(TODO: JIRA): shouldn't _isEmptySingleton be sufficient?
if _isEmptySingleton || self.count == 0 && !_object.isNative {
// We must be careful not to discard any capacity that
// may have been reserved for the append -- this is why
// we check for the empty string singleton rather than
// a zero `count` above.
self = other
return
}
if _slowPath(other._isOpaque) {
_opaqueAppend(opaqueOther: other)
return
}
defer { _fixLifetime(other) }
if other.isASCII {
self.append(other._unmanagedASCIIView)
} else {
self.append(other._unmanagedUTF16View)
}
}
mutating func _opaqueAppend(opaqueOther other: _StringGuts) {
if other._isSmall {
// TODO: Fix the visitation pattern for append here. For now, we funnel
// through _UnmanagedASCIIString.
other._smallUTF8String.withUnmanagedASCII {
self.append($0)
}
return
}
_sanityCheck(other._isOpaque)
defer { _fixLifetime(other) }
self.append(other._asOpaque())
}
@usableFromInline
internal
mutating func append(_ other: _StringGuts, range: Range<Int>) {
_sanityCheck(range.lowerBound >= 0 && range.upperBound <= other.count)
guard range.count > 0 else { return }
if _isEmptySingleton && range.count == other.count {
self = other
return
}
if _slowPath(other._isOpaque) {
_opaqueAppend(opaqueOther: other, range: range)
return
}
defer { _fixLifetime(other) }
if other.isASCII {
self.append(other._unmanagedASCIIView[range])
} else {
self.append(other._unmanagedUTF16View[range])
}
}
mutating func _opaqueAppend(opaqueOther other: _StringGuts, range: Range<Int>) {
if other._isSmall {
other._smallUTF8String.withUnmanagedASCII {
self.append($0[range])
}
return
}
_sanityCheck(other._isOpaque)
defer { _fixLifetime(other) }
self.append(other._asOpaque()[range])
}
//
// FIXME (TODO JIRA): Appending a character onto the end of a string should
// really have a less generic implementation, then we can drop @specialize.
//
@usableFromInline
@_specialize(where C == Character._SmallUTF16)
mutating func append<C : RandomAccessCollection>(contentsOf other: C)
where C.Element == UInt16 {
if self._isSmall {
if let result = self._smallUTF8String._appending(other) {
self = _StringGuts(result)
return
}
}
if _object.isSingleByte && !other.contains(where: { $0 > 0x7f }) {
withMutableASCIIStorage(
unusedCapacity: numericCast(other.count)) { storage in
storage._value._appendInPlaceUTF16(contentsOf: other)
}
return
}
withMutableUTF16Storage(
unusedCapacity: numericCast(other.count)) { storage in
storage._value._appendInPlaceUTF16(contentsOf: other)
}
}
}
extension _StringGuts {
@usableFromInline
mutating func _replaceSubrange<C, CodeUnit>(
_ bounds: Range<Int>,
with newElements: C,
of codeUnit: CodeUnit.Type
) where C : Collection, C.Element == UTF16.CodeUnit,
CodeUnit : FixedWidthInteger & UnsignedInteger {
_precondition(bounds.lowerBound >= 0,
"replaceSubrange: subrange start precedes String start")
let newCount: Int = numericCast(newElements.count)
let deltaCount = newCount - bounds.count
let paramsOpt = allocationParametersForMutableStorage(
of: CodeUnit.self,
unusedCapacity: Swift.max(0, deltaCount))
if _fastPath(paramsOpt == nil) {
// We have unique native storage of the correct code unit,
// with enough capacity to do the replacement inline.
unowned(unsafe) let storage = _object.nativeStorage(of: CodeUnit.self)
_sanityCheck(storage.unusedCapacity >= deltaCount)
let tailCount = storage.count - bounds.upperBound
_precondition(tailCount >= 0,
"replaceSubrange: subrange extends past String end")
let dst = storage.start + bounds.lowerBound
if deltaCount != 0 && tailCount > 0 {
// Move tail to make space for new data
(dst + newCount).moveInitialize(
from: dst + bounds.count,
count: tailCount)
}
// Copy new elements in place
var it = newElements.makeIterator()
for p in dst ..< (dst + newCount) {
p.pointee = CodeUnit(it.next()!)
}
_precondition(it.next() == nil, "Collection misreported its count")
storage.count += deltaCount
_nativeCount += deltaCount
_invariantCheck()
_fixLifetime(self)
return
}
// Allocate new storage.
let params = paramsOpt._unsafelyUnwrappedUnchecked
_precondition(bounds.upperBound <= params.count,
"replaceSubrange: subrange extends past String end")
let storage = _SwiftStringStorage<CodeUnit>.create(
capacity: params.capacity,
count: params.count + deltaCount)
var dst = storage.start
// Copy prefix up to replaced range
let prefixRange: Range<Int> = 0..<bounds.lowerBound
_copy(
range: prefixRange,
into: UnsafeMutableBufferPointer(start: dst, count: prefixRange.count))
dst += prefixRange.count
// Copy new data
var it = newElements.makeIterator()
for p in dst ..< (dst + newCount) {
p.pointee = CodeUnit(it.next()!)
}
_precondition(it.next() == nil, "Collection misreported its count")
dst += newCount
// Copy suffix from end of replaced range
let suffixRange: Range<Int> = bounds.upperBound..<params.count
_copy(
range: suffixRange,
into: UnsafeMutableBufferPointer(start: dst, count: suffixRange.count))
_sanityCheck(dst + suffixRange.count == storage.end)
self = _StringGuts(_large: storage)
_invariantCheck()
}
@usableFromInline
mutating func replaceSubrange<C>(
_ bounds: Range<Int>,
with newElements: C
) where C : Collection, C.Element == UTF16.CodeUnit {
if isASCII && !newElements.contains(where: {$0 > 0x7f}) {
self._replaceSubrange(bounds, with: newElements, of: UInt8.self)
} else {
self._replaceSubrange(bounds, with: newElements, of: UTF16.CodeUnit.self)
}
}
}
extension _StringGuts {
// TODO: Drop or unify with String._fromCodeUnits
internal
static func fromCodeUnits<Encoding : _UnicodeEncoding>(
_ input: UnsafeBufferPointer<Encoding.CodeUnit>,
encoding: Encoding.Type,
repairIllFormedSequences: Bool,
minimumCapacity: Int = 0
) -> (_StringGuts?, hadError: Bool) {
// Determine how many UTF-16 code units we'll need
guard let (utf16Count, isASCII) = UTF16.transcodedLength(
of: input.makeIterator(),
decodedAs: Encoding.self,
repairingIllFormedSequences: repairIllFormedSequences) else {
return (nil, true)
}
if isASCII {
if let small = _SmallUTF8String(
_fromCodeUnits: input,
utf16Length: utf16Count,
isASCII: true,
Encoding.self
) {
return (_StringGuts(small), false)
}
let storage = _SwiftStringStorage<UTF8.CodeUnit>.create(
capacity: Swift.max(minimumCapacity, utf16Count),
count: utf16Count)
let hadError = storage._initialize(
fromCodeUnits: input,
encoding: Encoding.self)
return (_StringGuts(_large: storage), hadError)
}
let storage = _SwiftStringStorage<UTF16.CodeUnit>.create(
capacity: Swift.max(minimumCapacity, utf16Count),
count: utf16Count)
let hadError = storage._initialize(
fromCodeUnits: input,
encoding: Encoding.self)
return (_StringGuts(_large: storage), hadError)
}
}
extension _SwiftStringStorage {
/// Initialize a piece of freshly allocated storage instance from a sequence
/// of code units, which is assumed to contain exactly as many code units as
/// fits in the current storage count.
///
/// Returns true iff `input` was found to contain invalid code units in the
/// specified encoding. If any invalid sequences are found, they are replaced
/// with REPLACEMENT CHARACTER (U+FFFD).
internal
func _initialize<Encoding: _UnicodeEncoding>(
fromCodeUnits input: UnsafeBufferPointer<Encoding.CodeUnit>,
encoding: Encoding.Type
) -> Bool {
var p = self.start
let hadError = transcode(
input.makeIterator(),
from: Encoding.self,
to: UTF16.self,
stoppingOnError: false) { cu in
_sanityCheck(p < end)
p.pointee = CodeUnit(cu)
p += 1
}
_sanityCheck(p == end)
return hadError
}
}
extension _StringGuts {
// FIXME: Remove. Still used by swift-corelibs-foundation
@available(*, deprecated)
public var startASCII: UnsafeMutablePointer<UTF8.CodeUnit> {
return UnsafeMutablePointer(mutating: _unmanagedASCIIView.start)
}
// FIXME: Remove. Still used by swift-corelibs-foundation
@available(*, deprecated)
public var startUTF16: UnsafeMutablePointer<UTF16.CodeUnit> {
return UnsafeMutablePointer(mutating: _unmanagedUTF16View.start)
}
}
extension _StringGuts {
@available(*, deprecated)
public // SPI(Foundation)
var _isContiguousASCII: Bool {
return _object.isContiguousASCII
}
@available(*, deprecated)
public // SPI(Foundation)
var _isContiguousUTF16: Bool {
return _object.isContiguousUTF16
}
@available(*, deprecated)
public // SPI(Foundation)
func _withUnsafeUTF8CodeUnitsIfAvailable<Result>(
_ f: (UnsafeBufferPointer<UInt8>) throws -> Result
) rethrows -> Result? {
guard _object.isContiguousASCII else { return nil }
return try f(_unmanagedASCIIView.buffer)
}
@available(*, deprecated)
public // SPI(Foundation)
func _withUnsafeUTF16CodeUnitsIfAvailable<Result>(
_ f: (UnsafeBufferPointer<UInt16>) throws -> Result
) rethrows -> Result? {
guard _object.isContiguousUTF16 else { return nil }
return try f(_unmanagedUTF16View.buffer)
}
}
| apache-2.0 | 734ece3e681a85a359bed3263d78a28f | 27.278891 | 82 | 0.659729 | 4.19785 | false | false | false | false |
kzaher/RxSwift | Tests/RxSwiftTests/Observable+TakeTests.swift | 2 | 17209 | //
// Observable+TakeTests.swift
// Tests
//
// Created by Krunoslav Zaher on 4/29/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
import XCTest
import RxSwift
import RxTest
class ObservableTakeTest : RxTest {
}
extension ObservableTakeTest {
func testTake_Complete_After() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
.next(70, 6),
.next(150, 4),
.next(210, 9),
.next(230, 13),
.next(270, 7),
.next(280, 1),
.next(300, -1),
.next(310, 3),
.next(340, 8),
.next(370, 11),
.next(410, 15),
.next(415, 16),
.next(460, 72),
.next(510, 76),
.next(560, 32),
.next(570, -100),
.next(580, -3),
.next(590, 5),
.next(630, 10),
.completed(690)
])
let res = scheduler.start {
xs.take(20)
}
XCTAssertEqual(res.events, [
.next(210, 9),
.next(230, 13),
.next(270, 7),
.next(280, 1),
.next(300, -1),
.next(310, 3),
.next(340, 8),
.next(370, 11),
.next(410, 15),
.next(415, 16),
.next(460, 72),
.next(510, 76),
.next(560, 32),
.next(570, -100),
.next(580, -3),
.next(590, 5),
.next(630, 10),
.completed(690)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 690)
])
}
func testTake_Complete_Same() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
.next(70, 6),
.next(150, 4),
.next(210, 9),
.next(230, 13),
.next(270, 7),
.next(280, 1),
.next(300, -1),
.next(310, 3),
.next(340, 8),
.next(370, 11),
.next(410, 15),
.next(415, 16),
.next(460, 72),
.next(510, 76),
.next(560, 32),
.next(570, -100),
.next(580, -3),
.next(590, 5),
.next(630, 10),
.completed(690)
])
let res = scheduler.start {
xs.take(17)
}
XCTAssertEqual(res.events, [
.next(210, 9),
.next(230, 13),
.next(270, 7),
.next(280, 1),
.next(300, -1),
.next(310, 3),
.next(340, 8),
.next(370, 11),
.next(410, 15),
.next(415, 16),
.next(460, 72),
.next(510, 76),
.next(560, 32),
.next(570, -100),
.next(580, -3),
.next(590, 5),
.next(630, 10),
.completed(630)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 630)
])
}
func testTake_Complete_Before() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
.next(70, 6),
.next(150, 4),
.next(210, 9),
.next(230, 13),
.next(270, 7),
.next(280, 1),
.next(300, -1),
.next(310, 3),
.next(340, 8),
.next(370, 11),
.next(410, 15),
.next(415, 16),
.next(460, 72),
.next(510, 76),
.next(560, 32),
.next(570, -100),
.next(580, -3),
.next(590, 5),
.next(630, 10),
.completed(690)
])
let res = scheduler.start {
xs.take(10)
}
XCTAssertEqual(res.events, [
.next(210, 9),
.next(230, 13),
.next(270, 7),
.next(280, 1),
.next(300, -1),
.next(310, 3),
.next(340, 8),
.next(370, 11),
.next(410, 15),
.next(415, 16),
.completed(415)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 415)
])
}
func testTake_Error_After() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
.next(70, 6),
.next(150, 4),
.next(210, 9),
.next(230, 13),
.next(270, 7),
.next(280, 1),
.next(300, -1),
.next(310, 3),
.next(340, 8),
.next(370, 11),
.next(410, 15),
.next(415, 16),
.next(460, 72),
.next(510, 76),
.next(560, 32),
.next(570, -100),
.next(580, -3),
.next(590, 5),
.next(630, 10),
.error(690, testError)
])
let res = scheduler.start {
xs.take(20)
}
XCTAssertEqual(res.events, [
.next(210, 9),
.next(230, 13),
.next(270, 7),
.next(280, 1),
.next(300, -1),
.next(310, 3),
.next(340, 8),
.next(370, 11),
.next(410, 15),
.next(415, 16),
.next(460, 72),
.next(510, 76),
.next(560, 32),
.next(570, -100),
.next(580, -3),
.next(590, 5),
.next(630, 10),
.error(690, testError)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 690)
])
}
func testTake_Error_Same() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
.next(70, 6),
.next(150, 4),
.next(210, 9),
.next(230, 13),
.next(270, 7),
.next(280, 1),
.next(300, -1),
.next(310, 3),
.next(340, 8),
.next(370, 11),
.next(410, 15),
.next(415, 16),
.next(460, 72),
.next(510, 76),
.next(560, 32),
.next(570, -100),
.next(580, -3),
.next(590, 5),
.next(630, 10),
.error(690, testError)
])
let res = scheduler.start {
xs.take(17)
}
XCTAssertEqual(res.events, [
.next(210, 9),
.next(230, 13),
.next(270, 7),
.next(280, 1),
.next(300, -1),
.next(310, 3),
.next(340, 8),
.next(370, 11),
.next(410, 15),
.next(415, 16),
.next(460, 72),
.next(510, 76),
.next(560, 32),
.next(570, -100),
.next(580, -3),
.next(590, 5),
.next(630, 10),
.completed(630)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 630)
])
}
func testTake_Error_Before() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
.next(70, 6),
.next(150, 4),
.next(210, 9),
.next(230, 13),
.next(270, 7),
.next(280, 1),
.next(300, -1),
.next(310, 3),
.next(340, 8),
.next(370, 11),
.next(410, 15),
.next(415, 16),
.next(460, 72),
.next(510, 76),
.next(560, 32),
.next(570, -100),
.next(580, -3),
.next(590, 5),
.next(630, 10),
.error(690, testError)
])
let res = scheduler.start {
xs.take(3)
}
XCTAssertEqual(res.events, [
.next(210, 9),
.next(230, 13),
.next(270, 7),
.completed(270)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 270)
])
}
func testTake_Dispose_Before() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
.next(70, 6),
.next(150, 4),
.next(210, 9),
.next(230, 13),
.next(270, 7),
.next(280, 1),
.next(300, -1),
.next(310, 3),
.next(340, 8),
.next(370, 11),
.next(410, 15),
.next(415, 16),
.next(460, 72),
.next(510, 76),
.next(560, 32),
.next(570, -100),
.next(580, -3),
.next(590, 5),
.next(630, 10),
.error(690, testError)
])
let res = scheduler.start(disposed: 250) {
xs.take(3)
}
XCTAssertEqual(res.events, [
.next(210, 9),
.next(230, 13),
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 250)
])
}
func testTake_Dispose_After() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
.next(70, 6),
.next(150, 4),
.next(210, 9),
.next(230, 13),
.next(270, 7),
.next(280, 1),
.next(300, -1),
.next(310, 3),
.next(340, 8),
.next(370, 11),
.next(410, 15),
.next(415, 16),
.next(460, 72),
.next(510, 76),
.next(560, 32),
.next(570, -100),
.next(580, -3),
.next(590, 5),
.next(630, 10),
.error(690, testError)
])
let res = scheduler.start(disposed: 400) {
xs.take(3)
}
XCTAssertEqual(res.events, [
.next(210, 9),
.next(230, 13),
.next(270, 7),
.completed(270)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 270)
])
}
func testTake_0_DefaultScheduler() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
.next(70, 6),
.next(150, 4),
.next(210, 9),
.next(230, 13)
])
let res = scheduler.start {
xs.take(0)
}
XCTAssertEqual(res.events, [
.completed(200)
])
XCTAssertEqual(xs.subscriptions, [
])
}
func testTake_Take1() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
.next(70, 6),
.next(150, 4),
.next(210, 9),
.next(230, 13),
.next(270, 7),
.next(280, 1),
.next(300, -1),
.next(310, 3),
.next(340, 8),
.next(370, 11),
.completed(400)
])
let res = scheduler.start {
xs.take(3)
}
XCTAssertEqual(res.events, [
.next(210, 9),
.next(230, 13),
.next(270, 7),
.completed(270)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 270)
])
}
func testTake_DecrementCountsFirst() {
let k = BehaviorSubject(value: false)
_ = k.take(1).subscribe(onNext: { n in
k.on(.next(!n))
})
}
#if TRACE_RESOURCES
func testTakeReleasesResourcesOnComplete() {
_ = Observable<Int>.of(1, 2).take(1).subscribe()
}
func testTakeReleasesResourcesOnError() {
_ = Observable<Int>.error(testError).take(1).subscribe()
}
#endif
}
extension ObservableTakeTest {
func testTake_TakeZero() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
.next(210, 1),
.next(220, 2),
.completed(230)
])
let res = scheduler.start {
xs.take(for: .seconds(0), scheduler: scheduler)
}
XCTAssertEqual(res.events, [
.completed(201)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 201)
])
}
func testTake_Some() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
.next(210, 1),
.next(220, 2),
.next(230, 3),
.completed(240)
])
let res = scheduler.start {
xs.take(for: .seconds(25), scheduler: scheduler)
}
XCTAssertEqual(res.events, [
.next(210, 1),
.next(220, 2),
.completed(225)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 225)
])
}
func testTake_TakeLate() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
.next(210, 1),
.next(220, 2),
.completed(230),
])
let res = scheduler.start {
xs.take(for: .seconds(50), scheduler: scheduler)
}
XCTAssertEqual(res.events, [
.next(210, 1),
.next(220, 2),
.completed(230)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 230)
])
}
func testTake_TakeError() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
.next(0, 0),
.error(210, testError)
])
let res = scheduler.start {
xs.take(for: .seconds(50), scheduler: scheduler)
}
XCTAssertEqual(res.events, [
.error(210, testError),
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 210)
])
}
func testTake_TakeNever() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
.next(0, 0),
])
let res = scheduler.start {
xs.take(for: .seconds(50), scheduler: scheduler)
}
XCTAssertEqual(res.events, [
.completed(250)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 250)
])
}
func testTake_TakeTwice1() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
.next(210, 1),
.next(220, 2),
.next(230, 3),
.next(240, 4),
.next(250, 5),
.next(260, 6),
.completed(270)
])
let res = scheduler.start {
xs.take(for: .seconds(55), scheduler: scheduler).take(for: .seconds(35), scheduler: scheduler)
}
XCTAssertEqual(res.events, [
.next(210, 1),
.next(220, 2),
.next(230, 3),
.completed(235)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 235)
])
}
func testTake_TakeDefault() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
.next(210, 1),
.next(220, 2),
.next(230, 3),
.next(240, 4),
.next(250, 5),
.next(260, 6),
.completed(270)
])
let res = scheduler.start {
xs.take(for: .seconds(35), scheduler: scheduler)
}
XCTAssertEqual(res.events, [
.next(210, 1),
.next(220, 2),
.next(230, 3),
.completed(235)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 235)
])
}
#if TRACE_RESOURCES
func testTakeTimeReleasesResourcesOnComplete() {
let scheduler = TestScheduler(initialClock: 0)
_ = Observable<Int>.just(1).take(for: .seconds(35), scheduler: scheduler).subscribe()
scheduler.start()
}
func testTakeTimeReleasesResourcesOnError() {
let scheduler = TestScheduler(initialClock: 0)
_ = Observable<Int>.error(testError).take(for: .seconds(35), scheduler: scheduler).subscribe()
scheduler.start()
}
#endif
}
| mit | 440257b3e719c49389fc2d2b7fa6eba1 | 24.493333 | 106 | 0.413761 | 4.113794 | false | true | false | false |
marklin2012/iOS_Animation | Section3/Chapter8/O2UIViewAnimation_completed/O2UIViewAnimation/ViewController.swift | 1 | 8193 | //
// ViewController.swift
// O2UIViewAnimation
//
// Created by O2.LinYi on 16/3/10.
// Copyright © 2016年 jd.com. All rights reserved.
//
import UIKit
// a delay function
func delay(seconds seconds: Double, completion: () -> ()) {
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * seconds))
dispatch_after(popTime, dispatch_get_main_queue()) { () -> Void in
completion()
}
}
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var loginBtn: UIButton!
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var usernameField: UITextField!
@IBOutlet weak var headingLabel: UILabel!
@IBOutlet weak var cloud1: UIImageView!
@IBOutlet weak var cloud2: UIImageView!
@IBOutlet weak var cloud3: UIImageView!
@IBOutlet weak var cloud4: UIImageView!
// MARK: - further UI
let spinner = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge)
let status = UIImageView(image: UIImage(named: "banner"))
let label = UILabel()
let messages = ["Connectiong ...", "Authorizing ...", "Sending credentials ...", "Failed"]
var statusPosition = CGPoint.zero
// MARK: - Lift cycle
override func viewDidLoad() {
super.viewDidLoad()
// set up the UI
loginBtn.layer.cornerRadius = 8.0
loginBtn.layer.masksToBounds = true
spinner.frame = CGRect(x: -20, y: 6, width: 20, height: 20)
spinner.startAnimating()
spinner.alpha = 0
loginBtn.addSubview(spinner)
status.hidden = true
status.center = loginBtn.center
view.addSubview(status)
label.frame = CGRect(x: 0, y: 0, width: status.frame.size.width, height: status.frame.size.height)
label.font = UIFont(name: "HelveticaNeue", size: 18)
label.textColor = UIColor(red: 0.89, green: 0.38, blue: 0, alpha: 1)
label.textAlignment = .Center
status.addSubview(label)
statusPosition = status.center
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
usernameField.layer.position.x -= view.bounds.width
passwordField.layer.position.x -= view.bounds.width
delay(seconds: 5.0, completion: {
print("where are the fields?")
})
// add layer animations
let flyRight = CABasicAnimation(keyPath: "position.x")
flyRight.fromValue = -view.bounds.size.width/2
flyRight.toValue = view.bounds.size.width/2
flyRight.duration = 0.5
flyRight.fillMode = kCAFillModeBoth
// flyRight.removedOnCompletion = false
headingLabel.layer.addAnimation(flyRight, forKey: nil)
flyRight.beginTime = CACurrentMediaTime() + 0.3
usernameField.layer.addAnimation(flyRight, forKey: nil)
flyRight.beginTime = CACurrentMediaTime() + 0.4
passwordField.layer.addAnimation(flyRight, forKey: nil)
usernameField.layer.position.x = view.bounds.size.width/2
passwordField.layer.position.x = view.bounds.size.width/2
cloud1.alpha = 0.0
cloud2.alpha = 0.0
cloud3.alpha = 0.0
cloud4.alpha = 0.0
loginBtn.center.y += 30
loginBtn.alpha = 0
// present animation
UIView.animateWithDuration(0.5, delay: 0.5, options: [], animations: { () -> Void in
self.cloud1.alpha = 1
}, completion: nil)
UIView.animateWithDuration(0.5, delay: 0.7, options: [], animations: { () -> Void in
self.cloud2.alpha = 1
}, completion: nil)
UIView.animateWithDuration(0.5, delay: 0.9, options: [], animations: { () -> Void in
self.cloud3.alpha = 1
}, completion: nil)
UIView.animateWithDuration(0.5, delay: 1.1, options: [], animations: { () -> Void in
self.cloud4.alpha = 1
}, completion: nil)
UIView.animateWithDuration(0.5, delay: 0.5, usingSpringWithDamping: 0.5, initialSpringVelocity: 1, options: [], animations: { () -> Void in
self.loginBtn.center.y -= 30
self.loginBtn.alpha = 1.0
}, completion: nil)
// make the cloud animation
animateCloud(cloud1)
animateCloud(cloud2)
animateCloud(cloud3)
animateCloud(cloud4)
}
// MARK: - further methods
@IBAction func login() {
view.endEditing(true)
// add animation
UIView.animateWithDuration(1.5, delay: 0, usingSpringWithDamping: 0.2, initialSpringVelocity: 0, options: [], animations: { () -> Void in
self.loginBtn.bounds.size.width += 80
}, completion: { _ in
self.showMessage(index: 0)
})
UIView.animateWithDuration(0.33, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [], animations: { () -> Void in
self.loginBtn.center.y += 60
self.loginBtn.backgroundColor = UIColor(red: 0.85, green: 0.83, blue: 0.45, alpha: 1)
self.spinner.center = CGPoint(x: 40, y: self.loginBtn.frame.size.height/2)
self.spinner.alpha = 1
}, completion: nil)
}
func showMessage(index index: Int) {
label.text = messages[index]
UIView.transitionWithView(status, duration: 0.33, options: [.CurveEaseOut, .TransitionFlipFromBottom], animations: { () -> Void in
self.status.hidden = false
}, completion: { _ in
// transition completion
delay(seconds: 2) { () -> () in
if index < self.messages.count-1 {
self.removeMessage(index: index)
} else {
// reset form
self.resetForm()
}
}
})
}
func removeMessage(index index: Int) {
UIView.animateWithDuration(0.33, delay: 0, options: [], animations: { () -> Void in
self.status.center.x += self.view.frame.size.width
}, completion: { _ in
self.status.hidden = true
self.status.center = self.statusPosition
self.showMessage(index: index+1)
})
}
func resetForm() {
UIView.transitionWithView(status, duration: 0.2, options: [.TransitionFlipFromTop], animations: { () -> Void in
self.status.hidden = true
self.status.center = self.statusPosition
}, completion: nil)
UIView.animateWithDuration(0.2, delay: 0, options: [], animations: { () -> Void in
self.spinner.center = CGPoint(x: -20, y: 16)
self.spinner.alpha = 0
self.loginBtn.backgroundColor = UIColor(red: 0.63, green: 0.84, blue: 0.35, alpha: 1)
self.loginBtn.bounds.size.width -= 90
self.loginBtn.center.y -= 60
}, completion: nil)
}
func animateCloud(cloud: UIImageView) {
let cloudSpeed = 60.0 / view.frame.size.width
let duration = (view.frame.size.width - cloud.frame.origin.x) * cloudSpeed
UIView.animateWithDuration(NSTimeInterval(duration), delay: 0, options: [.CurveLinear], animations: { () -> Void in
cloud.frame.origin.x = self.view.frame.size.width
}, completion: { _ in
cloud.frame.origin.x = -cloud.frame.size.width
self.animateCloud(cloud)
})
}
// MARK: - UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
let nextField = (textField === usernameField) ? passwordField : usernameField
nextField.becomeFirstResponder()
return true
}
}
| mit | 223f57b622c8178dfdbb74ac2762d208 | 34.150215 | 147 | 0.573382 | 4.497529 | false | false | false | false |
oisdk/SwiftSequence | Sources/LazyPrefix.swift | 1 | 1145 | // MARK: LazyPrefix
import Foundation
/// :nodoc:
public struct LazyPrefixSeq<S : SequenceType> : LazySequenceType {
private let seq: S
private let take: Int
/// :nodoc:
public func generate() -> LazyPrefixGen<S.Generator> {
return LazyPrefixGen(g: seq.generate(), take: take)
}
}
/// :nodoc:
public struct LazyPrefixGen<G : GeneratorType> : GeneratorType {
private var g: G
private let take: Int
private var found: Int
init(g: G, take: Int) {
self.g = g
self.take = take
self.found = 0
}
/// :nodoc:
mutating public func next() -> G.Element? {
guard found < take else {
return nil
}
guard let next = g.next() else {
return nil
}
found += 1
return next
}
}
public extension LazySequenceType {
/// Returns a lazy sequence of self with the first n elements (useful if chained with filter)
/// ```swift
/// [1, 2, 3, 4, 5, 6, 7, 8].lazy.filter { $0 > 2 }.lazyPrefix(2)
///
/// 3, 4
/// ```
@warn_unused_result
func lazyPrefix(take: Int) -> LazyPrefixSeq<Self> {
return LazyPrefixSeq(seq: self, take: take)
}
}
| mit | a316613c72e11df82ebc6950ae20d47e | 17.770492 | 95 | 0.6 | 3.544892 | false | false | false | false |
banxi1988/BXiOSUtils | Pod/Classes/UIBezierPathExtensions.swift | 5 | 1341 | //
// UIBezierPathExtensions.swift
// Pods
//
// Created by Haizhen Lee on 15/12/28.
//
//
import UIKit
public extension UIBezierPath{
public convenience init(starInRect rect:CGRect){
self.init()
// 从上面的中间开始绘制
let startPoint = CGPoint(x: rect.midX, y: rect.minY)
let point1 = CGPoint(x: rect.minX + rect.width * 0.6763, y: rect.minY + rect.height * 0.2573)
let point2 = CGPoint(x: rect.minX + rect.width * 0.9755, y: rect.minY + rect.height * 0.3455)
let point3 = CGPoint(x: rect.minX + rect.width * 0.7853, y: rect.minY + rect.height * 0.5927)
let point4 = CGPoint(x: rect.minX + rect.width * 0.7939, y: rect.minY + rect.height * 0.9045)
let point5 = CGPoint(x: rect.minX + rect.width * 0.50, y: rect.minY + rect.height * 0.80)
let point6 = CGPoint(x: rect.minX + rect.width * 0.2061, y: rect.minY + rect.height * 0.9045)
let point7 = CGPoint(x: rect.minX + rect.width * 0.2147, y: rect.minY + rect.height * 0.5927)
let point8 = CGPoint(x: rect.minX + rect.width * 0.0245, y: rect.minY + rect.height * 0.3455)
let point9 = CGPoint(x: rect.minX + rect.width * 0.3237, y: rect.minY + rect.height * 0.2573)
move(to: startPoint)
for point in [point1,point2,point3,point4,point5,point6,point7,point8,point9] {
addLine(to: point)
}
close()
}
}
| mit | 711930e9827d2d4527eba3b61136f0a1 | 40.28125 | 97 | 0.647237 | 2.804671 | false | false | false | false |
gregomni/swift | stdlib/public/Distributed/LocalTestingDistributedActorSystem.swift | 2 | 9922 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2022 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
//
//===----------------------------------------------------------------------===//
import Swift
#if canImport(Darwin)
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif os(Windows)
import WinSDK
#endif
/// A `DistributedActorSystem` designed for local only testing.
///
/// It will crash on any attempt of remote communication, but can be useful
/// for learning about `distributed actor` isolation, as well as early
/// prototyping stages of development where a real system is not necessary yet.
@available(SwiftStdlib 5.7, *)
public final class LocalTestingDistributedActorSystem: DistributedActorSystem, @unchecked Sendable {
public typealias ActorID = LocalTestingActorAddress
public typealias ResultHandler = LocalTestingInvocationResultHandler
public typealias InvocationEncoder = LocalTestingInvocationEncoder
public typealias InvocationDecoder = LocalTestingInvocationDecoder
public typealias SerializationRequirement = Codable
private var activeActors: [ActorID: any DistributedActor] = [:]
private let activeActorsLock = _Lock()
private var idProvider: ActorIDProvider = ActorIDProvider()
private var assignedIDs: Set<ActorID> = []
private let assignedIDsLock = _Lock()
public init() {}
public func resolve<Act>(id: ActorID, as actorType: Act.Type)
throws -> Act? where Act: DistributedActor {
guard let anyActor = self.activeActorsLock.withLock({ self.activeActors[id] }) else {
throw LocalTestingDistributedActorSystemError(message: "Unable to locate id '\(id)' locally")
}
guard let actor = anyActor as? Act else {
throw LocalTestingDistributedActorSystemError(message: "Failed to resolve id '\(id)' as \(Act.Type.self)")
}
return actor
}
public func assignID<Act>(_ actorType: Act.Type) -> ActorID
where Act: DistributedActor {
let id = self.idProvider.next()
self.assignedIDsLock.withLock {
self.assignedIDs.insert(id)
}
return id
}
public func actorReady<Act>(_ actor: Act)
where Act: DistributedActor,
Act.ID == ActorID {
guard self.assignedIDsLock.withLock({ self.assignedIDs.contains(actor.id) }) else {
fatalError("Attempted to mark an unknown actor '\(actor.id)' ready")
}
self.activeActorsLock.withLock {
self.activeActors[actor.id] = actor
}
}
public func resignID(_ id: ActorID) {
self.activeActorsLock.withLock {
self.activeActors.removeValue(forKey: id)
}
}
public func makeInvocationEncoder() -> InvocationEncoder {
.init()
}
public func remoteCall<Act, Err, Res>(
on actor: Act,
target: RemoteCallTarget,
invocation: inout InvocationEncoder,
throwing errorType: Err.Type,
returning returnType: Res.Type
) async throws -> Res
where Act: DistributedActor,
Act.ID == ActorID,
Err: Error,
Res: SerializationRequirement {
fatalError("Attempted to make remote call to \(target) on actor \(actor) using a local-only actor system")
}
public func remoteCallVoid<Act, Err>(
on actor: Act,
target: RemoteCallTarget,
invocation: inout InvocationEncoder,
throwing errorType: Err.Type
) async throws
where Act: DistributedActor,
Act.ID == ActorID,
Err: Error {
fatalError("Attempted to make remote call to \(target) on actor \(actor) using a local-only actor system")
}
private struct ActorIDProvider {
private var counter: Int = 0
private let counterLock = _Lock()
init() {}
mutating func next() -> LocalTestingActorAddress {
let id: Int = self.counterLock.withLock {
self.counter += 1
return self.counter
}
return LocalTestingActorAddress(parse: "\(id)")
}
}
}
@available(SwiftStdlib 5.7, *)
public struct LocalTestingActorAddress: Hashable, Sendable, Codable {
public let address: String
public init(parse address: String) {
self.address = address
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
self.address = try container.decode(String.self)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.address)
}
}
@available(SwiftStdlib 5.7, *)
public struct LocalTestingInvocationEncoder: DistributedTargetInvocationEncoder {
public typealias SerializationRequirement = Codable
public mutating func recordGenericSubstitution<T>(_ type: T.Type) throws {
fatalError("Attempted to call encoder method in a local-only actor system")
}
public mutating func recordArgument<Value: SerializationRequirement>(_ argument: RemoteCallArgument<Value>) throws {
fatalError("Attempted to call encoder method in a local-only actor system")
}
public mutating func recordErrorType<E: Error>(_ type: E.Type) throws {
fatalError("Attempted to call encoder method in a local-only actor system")
}
public mutating func recordReturnType<R: SerializationRequirement>(_ type: R.Type) throws {
fatalError("Attempted to call encoder method in a local-only actor system")
}
public mutating func doneRecording() throws {
fatalError("Attempted to call encoder method in a local-only actor system")
}
}
@available(SwiftStdlib 5.7, *)
public class LocalTestingInvocationDecoder : DistributedTargetInvocationDecoder {
public typealias SerializationRequirement = Codable
public func decodeGenericSubstitutions() throws -> [Any.Type] {
fatalError("Attempted to call decoder method in a local-only actor system")
}
public func decodeNextArgument<Argument: SerializationRequirement>() throws -> Argument {
fatalError("Attempted to call decoder method in a local-only actor system")
}
public func decodeErrorType() throws -> Any.Type? {
fatalError("Attempted to call decoder method in a local-only actor system")
}
public func decodeReturnType() throws -> Any.Type? {
fatalError("Attempted to call decoder method in a local-only actor system")
}
}
@available(SwiftStdlib 5.7, *)
public struct LocalTestingInvocationResultHandler: DistributedTargetInvocationResultHandler {
public typealias SerializationRequirement = Codable
public func onReturn<Success: SerializationRequirement>(value: Success) async throws {
fatalError("Attempted to call decoder method in a local-only actor system")
}
public func onReturnVoid() async throws {
fatalError("Attempted to call decoder method in a local-only actor system")
}
public func onThrow<Err: Error>(error: Err) async throws {
fatalError("Attempted to call decoder method in a local-only actor system")
}
}
// === errors ----------------------------------------------------------------
@available(SwiftStdlib 5.7, *)
public struct LocalTestingDistributedActorSystemError: DistributedActorSystemError {
public let message: String
public init(message: String) {
self.message = message
}
}
// === lock ----------------------------------------------------------------
@available(SwiftStdlib 5.7, *)
fileprivate class _Lock {
#if os(iOS) || os(macOS) || os(tvOS) || os(watchOS)
private let underlying: UnsafeMutablePointer<os_unfair_lock>
#elseif os(Windows)
private let underlying: UnsafeMutablePointer<SRWLOCK>
#elseif os(WASI)
// pthread is currently not available on WASI
#elseif os(Cygwin) || os(FreeBSD) || os(OpenBSD)
private let underlying: UnsafeMutablePointer<pthread_mutex_t?>
#else
private let underlying: UnsafeMutablePointer<pthread_mutex_t>
#endif
deinit {
#if os(iOS) || os(macOS) || os(tvOS) || os(watchOS)
// `os_unfair_lock`s do not need to be explicitly destroyed
#elseif os(Windows)
// `SRWLOCK`s do not need to be explicitly destroyed
#elseif os(WASI)
// WASI environment has only a single thread
#else
guard pthread_mutex_destroy(self.underlying) == 0 else {
fatalError("pthread_mutex_destroy failed")
}
#endif
#if !os(WASI)
self.underlying.deinitialize(count: 1)
self.underlying.deallocate()
#endif
}
init() {
#if os(iOS) || os(macOS) || os(tvOS) || os(watchOS)
self.underlying = UnsafeMutablePointer.allocate(capacity: 1)
#elseif os(Windows)
self.underlying = UnsafeMutablePointer.allocate(capacity: 1)
InitializeSRWLock(self.underlying)
#elseif os(WASI)
// WASI environment has only a single thread
#else
self.underlying = UnsafeMutablePointer.allocate(capacity: 1)
guard pthread_mutex_init(self.underlying, nil) == 0 else {
fatalError("pthread_mutex_init failed")
}
#endif
}
@discardableResult
func withLock<T>(_ body: () -> T) -> T {
#if os(iOS) || os(macOS) || os(tvOS) || os(watchOS)
os_unfair_lock_lock(self.underlying)
#elseif os(Windows)
AcquireSRWLockExclusive(self.underlying)
#elseif os(WASI)
// WASI environment has only a single thread
#else
guard pthread_mutex_lock(self.underlying) == 0 else {
fatalError("pthread_mutex_lock failed")
}
#endif
defer {
#if os(iOS) || os(macOS) || os(tvOS) || os(watchOS)
os_unfair_lock_unlock(self.underlying)
#elseif os(Windows)
ReleaseSRWLockExclusive(self.underlying)
#elseif os(WASI)
// WASI environment has only a single thread
#else
guard pthread_mutex_unlock(self.underlying) == 0 else {
fatalError("pthread_mutex_unlock failed")
}
#endif
}
return body()
}
}
| apache-2.0 | ce0054bdd9d97336d50c6d9000ab2c9c | 31.963455 | 118 | 0.688672 | 4.357488 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/Helpers/syncengine/ImageResource.swift | 1 | 8112 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import FLAnimatedImage
import WireDataModel
import WireLinkPreview
import UIKit
import WireSyncEngine
extension ZMConversationMessage {
var linkAttachmentImage: ImageResource? {
guard let attachment = self.linkAttachments?.first, let textMessage = self.textMessageData else {
return nil
}
return LinkAttachmentImageResourceAdaptor(attachment: attachment, textMessageData: textMessage, urlSession: URLSession.shared)
}
}
extension ZMTextMessageData {
var linkPreviewImage: ImageResource {
return LinkPreviewImageResourceAdaptor(textMessageData: self)
}
}
extension ZMFileMessageData {
var thumbnailImage: PreviewableImageResource {
return FileMessageImageResourceAdaptor(fileMesssageData: self)
}
}
extension ZMImageMessageData {
var image: PreviewableImageResource {
return ImageMessageImageResourceAdaptor(imageMessageData: self)
}
}
struct LinkPreviewImageResourceAdaptor: ImageResource {
let textMessageData: ZMTextMessageData
var cacheIdentifier: String? {
return textMessageData.linkPreviewImageCacheKey?.appending("-link")
}
var isAnimatedGIF: Bool {
return false
}
func requestImageDownload() {
textMessageData.requestLinkPreviewImageDownload()
}
func fetchImageData(queue: DispatchQueue, completionHandler: @escaping (Data?) -> Void) {
textMessageData.fetchLinkPreviewImageData(with: queue, completionHandler: completionHandler)
}
}
struct LinkAttachmentImageResourceAdaptor: ImageResource {
let attachment: LinkAttachment
let textMessageData: ZMTextMessageData
let urlSession: URLSessionProtocol
var cacheIdentifier: String? {
return textMessageData.linkPreviewImageCacheKey?.appending("-linkattachment")
}
var isAnimatedGIF: Bool {
return false
}
init(attachment: LinkAttachment, textMessageData: ZMTextMessageData, urlSession: URLSessionProtocol) {
self.attachment = attachment
self.textMessageData = textMessageData
self.urlSession = urlSession
}
func requestImageDownload() {
// no-op
}
func fetchImageData(queue: DispatchQueue, completionHandler: @escaping (Data?) -> Void) {
let complete: (Data?) -> Void = { data in
queue.async {
completionHandler(data)
}
}
// Download the thumbnail
guard let thumbnailURL = attachment.thumbnails.first else {
return complete(nil)
}
let getRequest = URLRequest(url: thumbnailURL)
// Download the image
let task = urlSession.dataTask(with: getRequest) { data, _, _ in
complete(data)
}
task.resume()
}
}
struct FileMessageImageResourceAdaptor: PreviewableImageResource {
let fileMesssageData: ZMFileMessageData
var cacheIdentifier: String? {
return fileMesssageData.imagePreviewDataIdentifier?.appending("-file")
}
var contentMode: UIView.ContentMode {
return .scaleAspectFill
}
var contentSize: CGSize {
return CGSize(width: 250, height: 140)
}
var isAnimatedGIF: Bool {
return false
}
func requestImageDownload() {
fileMesssageData.requestImagePreviewDownload()
}
func fetchImageData(queue: DispatchQueue, completionHandler: @escaping (Data?) -> Void) {
fileMesssageData.fetchImagePreviewData(queue: queue, completionHandler: completionHandler)
}
}
struct ImageMessageImageResourceAdaptor: PreviewableImageResource {
let imageMessageData: ZMImageMessageData
var cacheIdentifier: String? {
return imageMessageData.imageDataIdentifier?.appending("-image")
}
var isAnimatedGIF: Bool {
return imageMessageData.isAnimatedGIF
}
var contentMode: UIView.ContentMode {
return .scaleAspectFit
}
var contentSize: CGSize {
return imageMessageData.originalSize
}
func requestImageDownload() {
imageMessageData.requestFileDownload()
}
func fetchImageData(queue: DispatchQueue, completionHandler: @escaping (Data?) -> Void) {
imageMessageData.fetchImageData(with: queue, completionHandler: completionHandler)
}
}
protocol ImageResource {
var cacheIdentifier: String? { get }
var isAnimatedGIF: Bool { get }
func requestImageDownload()
func fetchImageData(queue: DispatchQueue, completionHandler: @escaping (_ imageData: Data?) -> Void)
}
protocol PreviewableImageResource: ImageResource {
var contentMode: UIView.ContentMode { get }
var contentSize: CGSize { get }
}
enum ImageSizeLimit {
case none
case deviceOptimized
case maxDimension(CGFloat)
case maxDimensionForShortSide(CGFloat)
}
extension ImageSizeLimit {
var cacheKeyExtension: String {
switch self {
case .none:
return "default"
case .deviceOptimized:
return "device"
case .maxDimension(let size):
return "max_\(String(Int(size)))"
case .maxDimensionForShortSide(let size):
return "maxshort_\(String(Int(size)))"
}
}
}
extension ImageResource {
/// Fetch image data and calls the completion handler when it is available on the main queue.
func fetchImage(cache: ImageCache<AnyObject> = MediaAssetCache.defaultImageCache,
sizeLimit: ImageSizeLimit = .deviceOptimized,
completion: @escaping (_ image: MediaAsset?, _ cacheHit: Bool) -> Void) {
guard let cacheIdentifier = self.cacheIdentifier else {
return completion(nil, false)
}
let isAnimatedGIF = self.isAnimatedGIF
var sizeLimit = sizeLimit
if isAnimatedGIF {
// animated GIFs can't be resized
sizeLimit = .none
}
let cacheKey = "\(cacheIdentifier)_\(sizeLimit.cacheKeyExtension)" as NSString
if let image = cache.cache.object(forKey: cacheKey) as? MediaAsset {
return completion(image, true)
}
ZMUserSession.shared()?.enqueue {
self.requestImageDownload()
}
cache.dispatchGroup.enter()
fetchImageData(queue: cache.processingQueue) { (imageData) in
var image: MediaAsset?
defer {
DispatchQueue.main.async {
completion(image, false)
cache.dispatchGroup.leave()
}
}
guard let imageData = imageData else { return }
if isAnimatedGIF {
image = FLAnimatedImage(animatedGIFData: imageData)
} else {
switch sizeLimit {
case .none:
image = UIImage(data: imageData)?.decoded
case .deviceOptimized:
image = UIImage.deviceOptimizedImage(from: imageData)
case .maxDimension(let limit):
image = UIImage(from: imageData, withMaxSize: limit)
case .maxDimensionForShortSide(let limit):
image = UIImage(from: imageData, withShorterSideLength: limit)
}
}
if let image = image {
cache.cache.setObject(image, forKey: cacheKey)
}
}
}
}
| gpl-3.0 | 1b73e4da0e34902939007786d8c4eee0 | 26.591837 | 134 | 0.657298 | 5.076345 | false | false | false | false |
jasnig/DouYuTVMutate | DouYuTVMutate/DouYuTV/Main/Lib/GifAnimator.swift | 1 | 10880 | //
// GifAnimator.swift
// DouYuTVMutate
//
// Created by ZeroJ on 16/7/24.
// Copyright © 2016年 ZeroJ. All rights reserved.
//
import UIKit
class GifAnimator: UIView {
/// 为不同的state设置不同的图片
/// 闭包需要返回一个元组: 图片数组和gif动画每一帧的执行时间
/// 一般需要设置loading状态的图片(必须), 作为加载的gif
/// 和pullToRefresh状态的图片数组(可选择设置), 作为拖拽时的加载动画
typealias SetImagesForStateClosure = (refreshState: RefreshViewState) -> (images:[UIImage], duration:Double)?
/// 为header或者footer的不同的state设置显示的文字
typealias SetDescriptionClosure = (refreshState: RefreshViewState, refreshType: RefreshViewType) -> String
/// 设置显示上次刷新时间的显示格式
typealias SetLastTimeClosure = (date: NSDate) -> String
// MARK: - private property
/// 显示上次刷新时间 可以外界隐藏和自定义字体颜色等
private(set) lazy var lastTimeLabel: UILabel = {
let lastTimeLabel = UILabel()
lastTimeLabel.textColor = UIColor.lightGrayColor()
lastTimeLabel.backgroundColor = UIColor.clearColor()
lastTimeLabel.textAlignment = .Center
lastTimeLabel.font = UIFont.systemFontOfSize(14.0)
return lastTimeLabel
}()
/// 显示描述状态的文字 可以外界隐藏和自定义字体颜色等
private(set) lazy var descriptionLabel: UILabel = {
let descriptionLabel = UILabel()
descriptionLabel.textColor = UIColor.lightGrayColor()
descriptionLabel.backgroundColor = UIColor.clearColor()
descriptionLabel.textAlignment = .Center
descriptionLabel.font = UIFont.systemFontOfSize(14.0)
return descriptionLabel
}()
/// gif图片 -> 外界不支持自定义
private lazy var gifImageView: UIImageView = {
let gifImageView = UIImageView()
gifImageView.clipsToBounds = true
return gifImageView
}()
/// 缓存图片
private var imagesDic = [RefreshViewState: (images:[UIImage], duration: Double)]()
private var setupDesctiptionClosure: SetDescriptionClosure?
private var setupLastTimeClosure: SetLastTimeClosure?
/// 耗时操作
private lazy var formatter: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.dateStyle = .ShortStyle
return formatter
}()
/// 耗时操作
private lazy var calendar: NSCalendar = NSCalendar.currentCalendar()
private var setupImagesClosure: SetImagesForStateClosure?
// MARK: - public property
/// 是否刷新完成后自动隐藏 默认为false
/// 这个属性是协议定义的, 当写在class里面可以供外界修改, 如果写在extension里面只能是可读的
var isAutomaticlyHidden: Bool = false
/// 这个key如果不指定或者为nil,将使用默认的key那么所有的未指定key的header和footer公用一个刷新时间
var lastRefreshTimeKey: String? = nil
/// 图片和字体的间距
var imageMagin = CGFloat(15.0)
// MARK: - public helper
/// 为不同的state设置不同的图片
/// 闭包需要返回一个元组: 图片数组和gif动画每一帧的执行时间
/// 一般需要设置loading状态的图片(必须), 作为加载的gif
/// 和pullToRefresh状态的图片数组(可选择设置), 作为拖拽时的加载动画
func setupImagesForRefreshstate(closure: SetImagesForStateClosure?) {
guard let imageClosure = closure else { return }
imagesDic[.normal] = imageClosure(refreshState: .normal)
imagesDic[.pullToRefresh] = imageClosure(refreshState: .pullToRefresh)
imagesDic[.releaseToFresh] = imageClosure(refreshState: .releaseToFresh)
imagesDic[.loading] = imageClosure(refreshState: .loading)
for (_, result) in imagesDic {
if result.images.count != 0 {
gifImageView.image = result.images.first
break
}
}
}
///
class func gifAnimator() -> GifAnimator {
let gif = GifAnimator(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 50.0))
gif.lastRefreshTimeKey = NSProcessInfo().globallyUniqueString
return gif
}
// MARK: - life cycle
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(gifImageView)
addSubview(lastTimeLabel)
addSubview(descriptionLabel)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
gifImageView.frame = bounds
/// setting height and width
descriptionLabel.sizeToFit()
lastTimeLabel.sizeToFit()
gifImageView.frame.origin.x = 15.0
/// 由图片设置刷新控件的高度
if gifImageView.image?.size.height > bounds.height {
bounds.size.height = gifImageView.image!.size.height
}
if descriptionLabel.hidden && lastTimeLabel.hidden {
gifImageView.contentMode = .Center
}
else {
/// y
if lastTimeLabel.hidden {// 居中
descriptionLabel.center.y = center.y
}
else {
descriptionLabel.frame.origin.y = bounds.height/2 - descriptionLabel.bounds.height
}
/// imageView
gifImageView.contentMode = .Right
gifImageView.frame.size.width = min(descriptionLabel.frame.minX, lastTimeLabel.frame.minX) - imageMagin - 15.0
}
/// y
lastTimeLabel.frame.origin.y = bounds.height - lastTimeLabel.bounds.height
/// x
descriptionLabel.center.x = center.x
lastTimeLabel.center.x = center.x
}
}
// MARK: - RefreshViewDelegate
extension GifAnimator: RefreshViewDelegate {
/// optional 两个可选的实现方法
/// 允许在控件添加到scrollView之前的准备
func refreshViewDidPrepare(refreshView: RefreshView, refreshType: RefreshViewType) {
if refreshType == .header {
descriptionLabel.text = "继续下拉刷新"
}
else {
descriptionLabel.text = "继续上拉刷新"
}
setupLastTime()
}
func refreshDidBegin(refreshView: RefreshView, refreshViewType: RefreshViewType) {
gifImageView.startAnimating()
}
/// 刷新结束状态, 这个时候应该关闭自定义的(动画)刷新
func refreshDidEnd(refreshView: RefreshView, refreshViewType: RefreshViewType) {
gifImageView.stopAnimating()
}
/// 刷新状态变为新的状态, 这个时候可以自定义设置各个状态对应的属性
func refreshDidChangeState(refreshView: RefreshView, fromState: RefreshViewState, toState: RefreshViewState, refreshViewType: RefreshViewType) {
setupDescriptionForState(toState, type: refreshViewType)
switch toState {
case .loading:
if gifImageView.isAnimating() {
gifImageView.stopAnimating()
}
guard let result = imagesDic[.loading] , let image = result.images.first else { return }
if result.images.count == 1 {
gifImageView.image = image
}
else {
gifImageView.animationImages = result.images
gifImageView.animationDuration = result.duration
}
case .normal:
/// 设置时间
setupLastTime()
default: break
}
}
/// 拖拽的进度, 可用于自定义实现拖拽过程中的动画
func refreshDidChangeProgress(refreshView: RefreshView, progress: CGFloat, refreshViewType: RefreshViewType) {
if gifImageView.isAnimating() {
gifImageView.stopAnimating()
}
guard let result = imagesDic[.pullToRefresh] where result.images.count != 0 else { return }
if result.images.count == 1 {
gifImageView.image = result.images.first
}
var index = Int(CGFloat(result.images.count) * progress)
index = min(index, result.images.count - 1)
gifImageView.image = result.images[index]
}
}
// MARK: - private helper
extension GifAnimator {
private func setupLastTime() {
if lastTimeLabel.hidden { return }
else {
guard let lastDate = lastRefreshTime else {
lastTimeLabel.text = "首次刷新"
return
}
if let closure = setupLastTimeClosure {
lastTimeLabel.text = closure(date:lastDate)
setNeedsLayout()
}
else {
let lastComponent = calendar.components([.Day, .Year], fromDate: lastDate)
let currentComponent = calendar.components([.Day, .Year], fromDate: NSDate())
var todayString = ""
if lastComponent.day == currentComponent.day {
formatter.dateFormat = "HH:mm"
todayString = "今天 "
}
else if lastComponent.year == currentComponent.year {
formatter.dateFormat = "MM-dd HH:mm"
}
else {
formatter.dateFormat = "yyyy-MM-dd HH:mm"
}
let timeString = formatter.stringFromDate(lastDate)
lastTimeLabel.text = "上次刷新时间:" + todayString + timeString
setNeedsLayout()
}
}
}
private func setupDescriptionForState(state: RefreshViewState, type: RefreshViewType) {
if descriptionLabel.hidden { return }
else {
if let closure = setupDesctiptionClosure {
descriptionLabel.text = closure(refreshState: state, refreshType: type)
setNeedsLayout()
}
else {
switch state {
case .normal:
descriptionLabel.text = "正常状态"
case .loading:
descriptionLabel.text = "加载数据中..."
case .pullToRefresh:
if type == .header {
descriptionLabel.text = "继续下拉刷新"
} else {
descriptionLabel.text = "继续上拉刷新"
}
case .releaseToFresh:
descriptionLabel.text = "松开手刷新"
}
setNeedsLayout()
}
}
}
}
| mit | 4749083b8fc852843fceedc230f90314 | 33.621053 | 148 | 0.595926 | 4.87741 | false | false | false | false |
modcloth-labs/XBot | XBot/Device.swift | 1 | 1000 | //
// Device.swift
// XBot
//
// Created by Geoffrey Nix on 9/30/14.
// Copyright (c) 2014 ModCloth. All rights reserved.
//
import Foundation
public class Device {
public var id:String
public var name:String
public var osVersion:String
public var type:String
public init(deviceDictionary:NSDictionary){
id = deviceDictionary["_id"]! as String
name = deviceDictionary["name"]! as String
osVersion = deviceDictionary["osVersion"]! as String
type = deviceDictionary["deviceType"]! as String
}
public func description() -> String {
return "\(type) \(name) (\(id)) \(osVersion)"
}
}
func devicesFromDevicesJson(json:Dictionary<String, AnyObject>) -> [Device] {
var devices:[Device] = []
if let results = json["results"] as AnyObject? as? [Dictionary<String, AnyObject>]{
for dict in results {
devices.append(Device(deviceDictionary: dict))
}
}
return devices
} | mit | 1aa1eaeb8324d8672f153cec840beba9 | 24.025 | 87 | 0.629 | 4.201681 | false | false | false | false |
KaneCheshire/Communicator | Sources/Helpers/CommunicatorSessionDelegate.swift | 1 | 5364 | //
// CommunicatorSessionDelegate.swift
// Communicator-iOS
//
// Created by Kane Cheshire on 20/11/2019.
//
import WatchConnectivity
/// Serves as the WCSessionDelegate to obfuscate the delegate methods.
final class SessionDelegate: NSObject, WCSessionDelegate {
let communicator: Communicator
var blobTransferCompletionHandlers: [WCSessionFileTransfer : Blob.Completion] = [:]
var guaranteedMessageTransferCompletionHandlers: [WCSessionUserInfoTransfer : GuaranteedMessage.Completion] = [:]
var complicationInfoTransferCompletionHandlers: [WCSessionUserInfoTransfer : ComplicationInfo.Completion] = [:]
init(communicator: Communicator) {
self.communicator = communicator
super.init()
}
// MARK: - WCSessionDelegate -
// MARK: Session status
func sessionReachabilityDidChange(_ session: WCSession) {
Reachability.notifyObservers(communicator.currentReachability)
}
#if os(iOS)
func sessionDidDeactivate(_ session: WCSession) {
Reachability.notifyObservers(communicator.currentReachability)
session.activate()
}
func sessionDidBecomeInactive(_ session: WCSession) {
Reachability.notifyObservers(communicator.currentReachability)
}
func sessionWatchStateDidChange(_ session: WCSession) {
WatchState.notifyObservers(communicator.currentWatchState)
Reachability.notifyObservers(communicator.currentReachability)
}
#endif
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
let state = Communicator.State(session: session.activationState)
Communicator.State.notifyObservers(state)
Reachability.notifyObservers(communicator.currentReachability)
if activationState == .notActivated {
session.activate()
}
}
// MARK: Receiving messages
func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
guard let message = ImmediateMessage(content: message) else { return }
ImmediateMessage.notifyObservers(message)
}
func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
guard let message = InteractiveImmediateMessage(content: message, reply: { reply in
replyHandler(reply.jsonRepresentation())
}) else { return }
InteractiveImmediateMessage.notifyObservers(message)
}
// MARK: Receiving and sending userInfo/complication data
func session(_ session: WCSession, didReceiveUserInfo userInfo: [String : Any] = [:]) {
if let message = GuaranteedMessage(content: userInfo) {
GuaranteedMessage.notifyObservers(message)
}
#if os(watchOS)
if let complicationInfo = ComplicationInfo(jsonDictionary: userInfo) {
ComplicationInfo.notifyObservers(complicationInfo)
}
#endif
endBackgroundTaskIfRequired()
}
func session(_ session: WCSession, didFinish userInfoTransfer: WCSessionUserInfoTransfer, error: Error?) {
if let handler = guaranteedMessageTransferCompletionHandlers[userInfoTransfer] {
if let error = error {
handler(.failure(error))
} else {
handler(.success(()))
}
}
#if os(iOS)
if let handler = complicationInfoTransferCompletionHandlers[userInfoTransfer] {
if let error = error {
handler(.failure(error))
} else {
let numberOfUpdatesRemaining = communicator.currentWatchState.numberOfComplicationUpdatesAvailableToday
handler(.success(numberOfUpdatesRemaining))
}
}
#endif
}
// MARK: Receiving contexts
func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) {
let context = Context(content: applicationContext)
Context.notifyObservers(context)
endBackgroundTaskIfRequired()
}
// MARK: Receiving and sending files
func session(_ session: WCSession, didReceive file: WCSessionFile) {
guard let data = try? Data(contentsOf: file.fileURL) else { return }
guard let content = NSKeyedUnarchiver.unarchiveObject(with: data) as? [String : Any] else { return }
guard let blob = Blob(content: content, metadata: file.metadata) else { return }
Blob.notifyObservers(blob)
endBackgroundTaskIfRequired()
}
func session(_ session: WCSession, didFinish fileTransfer: WCSessionFileTransfer, error: Error?) {
guard let handler = blobTransferCompletionHandlers[fileTransfer] else { return }
if let error = error {
handler(.failure(error))
} else {
handler(.success(()))
}
}
private func endBackgroundTaskIfRequired() {
#if os(watchOS)
guard !communicator.hasPendingDataToBeReceived else { return }
if #available(watchOSApplicationExtension 4.0, *) {
communicator.task?.setTaskCompletedWithSnapshot(true)
} else {
communicator.task?.setTaskCompleted()
}
#endif
}
}
| mit | 8ccba335315547428a1d009119f1f743 | 36.51049 | 133 | 0.665175 | 5.42366 | false | false | false | false |
huangboju/Moots | UICollectionViewLayout/SpreadsheetView-master/Framework/Tests/SelectionTests.swift | 2 | 17792 | //
// SelectionTests.swift
// SpreadsheetView
//
// Created by Kishikawa Katsumi on 4/30/17.
// Copyright © 2017 Kishikawa Katsumi. All rights reserved.
//
import XCTest
@testable import SpreadsheetView
class SelectionTests: XCTestCase {
override func setUp() {
super.setUp()
continueAfterFailure = false
}
override func tearDown() {
super.tearDown()
}
func testSelectItem() {
let parameters = Parameters(frozenColumns: 1, frozenRows: 1)
let viewController = defaultViewController(parameters: parameters)
showViewController(viewController: viewController)
waitRunLoop()
guard let _ = viewController.view else {
XCTFail("fails to create root view controller")
return
}
let spreadsheetView = viewController.spreadsheetView
var indexPath: IndexPath
indexPath = IndexPath(row: 0, column: 0)
spreadsheetView.selectItem(at: indexPath, animated: false, scrollPosition: [.left, .top])
waitRunLoop()
XCTAssertNotNil(spreadsheetView.cellForItem(at: indexPath))
XCTAssertEqual(spreadsheetView.indexPathForSelectedItem, indexPath)
XCTAssertEqual(spreadsheetView.indexPathsForSelectedItems.count, 1)
indexPath = IndexPath(row: 0, column: parameters.numberOfColumns - 1)
spreadsheetView.selectItem(at: indexPath, animated: false, scrollPosition: [.left, .top])
waitRunLoop()
XCTAssertNotNil(spreadsheetView.cellForItem(at: indexPath))
XCTAssertEqual(spreadsheetView.indexPathForSelectedItem, indexPath)
XCTAssertEqual(spreadsheetView.indexPathsForSelectedItems.count, 1)
indexPath = IndexPath(row: parameters.numberOfRows - 1, column: 0)
spreadsheetView.selectItem(at: indexPath, animated: false, scrollPosition: [.left, .top])
waitRunLoop()
XCTAssertNotNil(spreadsheetView.cellForItem(at: indexPath))
XCTAssertEqual(spreadsheetView.indexPathForSelectedItem, indexPath)
XCTAssertEqual(spreadsheetView.indexPathsForSelectedItems.count, 1)
indexPath = IndexPath(row: parameters.numberOfRows - 1, column: parameters.numberOfColumns - 1)
spreadsheetView.selectItem(at: indexPath, animated: false, scrollPosition: [.left, .top])
waitRunLoop()
XCTAssertNotNil(spreadsheetView.cellForItem(at: indexPath))
XCTAssertEqual(spreadsheetView.indexPathForSelectedItem, indexPath)
XCTAssertEqual(spreadsheetView.indexPathsForSelectedItems.count, 1)
}
func testAllowsSelection() {
let parameters = Parameters()
let viewController = defaultViewController(parameters: parameters)
showViewController(viewController: viewController)
waitRunLoop()
guard let _ = viewController.view else {
XCTFail("fails to create root view controller")
return
}
let spreadsheetView = viewController.spreadsheetView
spreadsheetView.allowsSelection = false
spreadsheetView.selectItem(at: IndexPath(row: 0, column: 0), animated: false, scrollPosition: [.left, .top])
waitRunLoop()
XCTAssertNil(spreadsheetView.indexPathForSelectedItem)
XCTAssertEqual(spreadsheetView.indexPathsForSelectedItems.count, 0)
spreadsheetView.selectItem(at: IndexPath(row: 0, column: parameters.numberOfColumns - 1), animated: false, scrollPosition: [.left, .top])
waitRunLoop()
XCTAssertNil(spreadsheetView.indexPathForSelectedItem)
XCTAssertEqual(spreadsheetView.indexPathsForSelectedItems.count, 0)
spreadsheetView.selectItem(at: IndexPath(row: parameters.numberOfRows - 1, column: 0), animated: false, scrollPosition: [.left, .top])
waitRunLoop()
XCTAssertNil(spreadsheetView.indexPathForSelectedItem)
XCTAssertEqual(spreadsheetView.indexPathsForSelectedItems.count, 0)
spreadsheetView.selectItem(at: IndexPath(row: parameters.numberOfRows - 1, column: parameters.numberOfColumns - 1), animated: false, scrollPosition: [.left, .top])
waitRunLoop()
XCTAssertNil(spreadsheetView.indexPathForSelectedItem)
XCTAssertEqual(spreadsheetView.indexPathsForSelectedItems.count, 0)
}
func testAllowsMultipleSelection() {
let parameters = Parameters(frozenColumns: 2, frozenRows: 2)
let viewController = defaultViewController(parameters: parameters)
showViewController(viewController: viewController)
waitRunLoop()
guard let _ = viewController.view else {
XCTFail("fails to create root view controller")
return
}
let spreadsheetView = viewController.spreadsheetView
spreadsheetView.allowsMultipleSelection = true
var selectedIndexPaths = [IndexPath]()
var indexPath = IndexPath(row: 0, column: 0)
selectedIndexPaths.append(indexPath)
spreadsheetView.selectItem(at: indexPath, animated: false, scrollPosition: [.left, .top])
waitRunLoop()
XCTAssertEqual(spreadsheetView.indexPathForSelectedItem, indexPath)
XCTAssertEqual(spreadsheetView.indexPathsForSelectedItems.count, 1)
XCTAssertEqual(spreadsheetView.indexPathsForSelectedItems.first, indexPath)
XCTAssertEqual(spreadsheetView.indexPathsForSelectedItems.last, indexPath)
indexPath = IndexPath(row: 0, column: parameters.numberOfColumns - 1)
selectedIndexPaths.append(indexPath)
spreadsheetView.selectItem(at: indexPath, animated: false, scrollPosition: [.left, .top])
waitRunLoop()
XCTAssertEqual(spreadsheetView.indexPathForSelectedItem, selectedIndexPaths.sorted().first)
XCTAssertEqual(spreadsheetView.indexPathsForSelectedItems.count, selectedIndexPaths.count)
XCTAssertEqual(spreadsheetView.indexPathsForSelectedItems.first, selectedIndexPaths.sorted().first)
XCTAssertEqual(spreadsheetView.indexPathsForSelectedItems.last, selectedIndexPaths.sorted().last)
indexPath = IndexPath(row: parameters.numberOfRows - 1, column: 0)
selectedIndexPaths.append(indexPath)
spreadsheetView.selectItem(at: indexPath, animated: false, scrollPosition: [.left, .top])
waitRunLoop()
XCTAssertEqual(spreadsheetView.indexPathForSelectedItem, selectedIndexPaths.sorted().first)
XCTAssertEqual(spreadsheetView.indexPathsForSelectedItems.count, selectedIndexPaths.count)
XCTAssertEqual(spreadsheetView.indexPathsForSelectedItems.first, selectedIndexPaths.sorted().first)
XCTAssertEqual(spreadsheetView.indexPathsForSelectedItems.last, selectedIndexPaths.sorted().last)
indexPath = IndexPath(row: parameters.numberOfRows - 1, column: parameters.numberOfColumns - 1)
selectedIndexPaths.append(indexPath)
spreadsheetView.selectItem(at: indexPath, animated: false, scrollPosition: [.left, .top])
waitRunLoop()
XCTAssertEqual(spreadsheetView.indexPathForSelectedItem, selectedIndexPaths.sorted().first)
XCTAssertEqual(spreadsheetView.indexPathsForSelectedItems.count, selectedIndexPaths.count)
XCTAssertEqual(spreadsheetView.indexPathsForSelectedItems.first, selectedIndexPaths.sorted().first)
XCTAssertEqual(spreadsheetView.indexPathsForSelectedItems.last, selectedIndexPaths.sorted().last)
spreadsheetView.deselectItem(at: selectedIndexPaths[1], animated: false)
selectedIndexPaths.remove(at: 1)
XCTAssertEqual(spreadsheetView.indexPathForSelectedItem, selectedIndexPaths.sorted().first)
XCTAssertEqual(spreadsheetView.indexPathsForSelectedItems.count, selectedIndexPaths.count)
XCTAssertEqual(spreadsheetView.indexPathsForSelectedItems.first, selectedIndexPaths.sorted().first)
XCTAssertEqual(spreadsheetView.indexPathsForSelectedItems.last, selectedIndexPaths.sorted().last)
spreadsheetView.deselectItem(at: selectedIndexPaths[0], animated: false)
selectedIndexPaths.remove(at: 0)
XCTAssertEqual(spreadsheetView.indexPathForSelectedItem, selectedIndexPaths.sorted().first)
XCTAssertEqual(spreadsheetView.indexPathsForSelectedItems.count, selectedIndexPaths.count)
XCTAssertEqual(spreadsheetView.indexPathsForSelectedItems.first, selectedIndexPaths.sorted().first)
XCTAssertEqual(spreadsheetView.indexPathsForSelectedItems.last, selectedIndexPaths.sorted().last)
// deselect all items
spreadsheetView.selectItem(at: nil, animated: false, scrollPosition: [])
selectedIndexPaths.removeAll()
XCTAssertNil(spreadsheetView.indexPathForSelectedItem)
XCTAssertEqual(spreadsheetView.indexPathsForSelectedItems.count, 0)
}
func testTouches() {
let parameters = Parameters()
let viewController = defaultViewController(parameters: parameters)
showViewController(viewController: viewController)
waitRunLoop()
guard let _ = viewController.view else {
XCTFail("fails to create root view controller")
return
}
let spreadsheetView = viewController.spreadsheetView
verifyBoundaries(spreadsheetView: spreadsheetView,
columns: (0, parameters.numberOfColumns),
rows: (0, parameters.numberOfRows),
parameters: parameters)
}
func testTouchesFrozenColumns() {
let parameters = Parameters(frozenColumns: 1)
let viewController = defaultViewController(parameters: parameters)
showViewController(viewController: viewController)
waitRunLoop()
guard let _ = viewController.view else {
XCTFail("fails to create root view controller")
return
}
let spreadsheetView = viewController.spreadsheetView
verifyBoundaries(spreadsheetView: spreadsheetView,
columns: (0, parameters.numberOfColumns),
rows: (0, parameters.numberOfRows),
parameters: parameters)
}
func testTouchesFrozenRows() {
let parameters = Parameters(frozenRows: 2)
let viewController = defaultViewController(parameters: parameters)
showViewController(viewController: viewController)
waitRunLoop()
guard let _ = viewController.view else {
XCTFail("fails to create root view controller")
return
}
let spreadsheetView = viewController.spreadsheetView
verifyBoundaries(spreadsheetView: spreadsheetView,
columns: (0, parameters.numberOfColumns),
rows: (0, parameters.numberOfRows),
parameters: parameters)
}
func testTouchesFrozenColumnsAndRows() {
let parameters = Parameters(frozenColumns: 1, frozenRows: 3)
let viewController = defaultViewController(parameters: parameters)
showViewController(viewController: viewController)
waitRunLoop()
guard let _ = viewController.view else {
XCTFail("fails to create root view controller")
return
}
let spreadsheetView = viewController.spreadsheetView
verifyBoundaries(spreadsheetView: spreadsheetView,
columns: (0, parameters.numberOfColumns),
rows: (0, parameters.numberOfRows),
parameters: parameters)
}
func verifyBoundaries(spreadsheetView: SpreadsheetView,
columns: (from: Int, to: Int),
rows: (from: Int, to: Int),
parameters: Parameters) {
print("parameters: \(parameters)")
var width: CGFloat = 0
var height: CGFloat = 0
var offsetWidth: CGFloat = 0
var offsetHeight: CGFloat = 0
var leftEdgeColumn = 0
for column in columns.from..<columns.to {
let frozenWidth = calculateWidth(range: 0..<parameters.frozenColumns, parameters: parameters) - (parameters.frozenColumns > 0 ? parameters.intercellSpacing.width : 0)
if column > parameters.frozenColumns && width + parameters.columns[column] + parameters.intercellSpacing.width >= spreadsheetView.frame.width - frozenWidth {
offsetWidth = calculateWidth(range: parameters.frozenColumns..<column, parameters: parameters) - parameters.intercellSpacing.width
if parameters.columnWidth - offsetWidth - frozenWidth < spreadsheetView.frame.width - frozenWidth {
offsetWidth -= spreadsheetView.frame.width - (parameters.columnWidth - offsetWidth)
}
width = 0
leftEdgeColumn = column
spreadsheetView.scrollToItem(at: IndexPath(row: 0, column: column), at: [.left, .top], animated: false)
waitRunLoop(secs: 0.0001)
}
width += parameters.columns[column] + parameters.intercellSpacing.width
height = 0
offsetHeight = 0
for row in rows.from..<rows.to {
let frozenHeight = calculateHeight(range: 0..<parameters.frozenRows, parameters: parameters) - (parameters.frozenRows > 0 ? parameters.intercellSpacing.height : 0)
if row > parameters.frozenRows && height + parameters.rows[row] + parameters.intercellSpacing.height >= spreadsheetView.frame.height - frozenHeight {
offsetHeight = calculateHeight(range: parameters.frozenRows..<(row), parameters: parameters) - parameters.intercellSpacing.height
if parameters.rowHeight - offsetHeight - frozenHeight < spreadsheetView.frame.height - frozenHeight {
offsetHeight -= spreadsheetView.frame.height - (parameters.rowHeight - offsetHeight)
}
height = 0
spreadsheetView.scrollToItem(at: IndexPath(row: row, column: leftEdgeColumn), at: [.left, .top], animated: false)
waitRunLoop(secs: 0.0001)
}
height += parameters.rows[row] + parameters.intercellSpacing.height
let indexPath = IndexPath(row: row, column: column)
let rect = spreadsheetView.rectForItem(at: indexPath)
func verifyTouches(at location: CGPoint, on spreadsheetView: SpreadsheetView, shouldSucceed: Bool) {
let touch = Touch(location: location)
spreadsheetView.touchesBegan(Set<UITouch>([touch]), nil)
waitRunLoop(secs: 0.0001)
spreadsheetView.touchesEnded(Set<UITouch>([touch]), nil)
waitRunLoop(secs: 0.0001)
if shouldSucceed {
XCTAssertEqual(spreadsheetView.indexPathForSelectedItem, indexPath)
XCTAssertEqual(spreadsheetView.indexPathsForSelectedItems.count, 1)
} else {
XCTAssertNil(spreadsheetView.indexPathForSelectedItem)
XCTAssertEqual(spreadsheetView.indexPathsForSelectedItems.count, 0)
}
}
let minX = rect.origin.x - offsetWidth
let minY = rect.origin.y - offsetHeight
let maxX = minX + rect.width
let maxY = minY + rect.height
let midX = minX + rect.width / 2
let midY = minY + rect.height / 2
func clearSelection() {
spreadsheetView.selectItem(at: nil, animated: false, scrollPosition: [])
waitRunLoop(secs: 0.0001)
}
verifyTouches(at: CGPoint(x: minX, y: minY), on: spreadsheetView, shouldSucceed: true)
clearSelection()
verifyTouches(at: CGPoint(x: minX, y: maxY), on: spreadsheetView, shouldSucceed: true)
clearSelection()
verifyTouches(at: CGPoint(x: maxX, y: minY), on: spreadsheetView, shouldSucceed: true)
clearSelection()
verifyTouches(at: CGPoint(x: maxX, y: maxY), on: spreadsheetView, shouldSucceed: true)
clearSelection()
verifyTouches(at: CGPoint(x: midX, y: midY), on: spreadsheetView, shouldSucceed: true)
clearSelection()
verifyTouches(at: CGPoint(x: minX - 0.01, y: minY), on: spreadsheetView, shouldSucceed: false)
clearSelection()
verifyTouches(at: CGPoint(x: minX, y: minY - 0.01), on: spreadsheetView, shouldSucceed: false)
clearSelection()
verifyTouches(at: CGPoint(x: minX - 0.01, y: maxY), on: spreadsheetView, shouldSucceed: false)
clearSelection()
verifyTouches(at: CGPoint(x: minX, y: maxY + 0.01), on: spreadsheetView, shouldSucceed: false)
clearSelection()
verifyTouches(at: CGPoint(x: maxX + 0.01, y: minY), on: spreadsheetView, shouldSucceed: false)
clearSelection()
verifyTouches(at: CGPoint(x: maxX, y: minY - 0.01), on: spreadsheetView, shouldSucceed: false)
clearSelection()
verifyTouches(at: CGPoint(x: maxX + 0.01, y: maxY), on: spreadsheetView, shouldSucceed: false)
clearSelection()
verifyTouches(at: CGPoint(x: maxX, y: maxY + 0.01), on: spreadsheetView, shouldSucceed: false)
clearSelection()
}
spreadsheetView.scrollToItem(at: IndexPath(row: 0, column: leftEdgeColumn), at: [.left, .top], animated: false)
waitRunLoop()
}
}
}
| mit | fad7d5fbcbb6995920991d8d12424f85 | 44.385204 | 179 | 0.663819 | 5.401032 | false | false | false | false |
huangboju/Moots | Examples/SwiftUI/CreatingAmacOSApp/Complete/Landmarks/MacLandmarks/Filter.swift | 1 | 1379 | /*
See LICENSE folder for this sample’s licensing information.
Abstract:
A filter for controlling which landmarks to display in the list.
*/
import SwiftUI
struct Filter: View {
@EnvironmentObject private var userData: UserData
@Binding var filter: FilterType
var body: some View {
HStack {
Picker(selection: $filter, label: EmptyView()) {
ForEach(FilterType.allCases) { choice in
Text(choice.name).tag(choice)
}
}
Spacer()
Toggle(isOn: $userData.showFavoritesOnly) {
Text("Favorites only")
}
}
}
}
struct Filter_Previews: PreviewProvider {
static var previews: some View {
Filter(filter: .constant(.all))
.environmentObject(UserData())
}
}
struct FilterType: CaseIterable, Hashable, Identifiable {
var name: String
var category: Landmark.Category?
init(_ category: Landmark.Category) {
self.name = category.rawValue
self.category = category
}
init(name: String) {
self.name = name
self.category = nil
}
static var all = FilterType(name: "All")
static var allCases: [FilterType] {
return [.all] + Landmark.Category.allCases.map(FilterType.init)
}
var id: FilterType {
return self
}
}
| mit | 7010ef5601b7c6ad40a8232d88570a13 | 21.57377 | 71 | 0.594771 | 4.605351 | false | false | false | false |
huangboju/Moots | Examples/波浪/WaterWave/WaterWave/ViewController.swift | 1 | 2189 | //
// ViewController.swift
// WaterWave
//
// Created by 伯驹 黄 on 16/9/29.
// Copyright © 2016年 xiAo_Ju. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
fileprivate lazy var tableView: UITableView = {
let tableView = UITableView(frame: self.view.frame, style: .grouped)
tableView.dataSource = self
tableView.delegate = self
return tableView
}()
lazy var data: [[UIViewController.Type]] = [
[
FirstViewController.self,
SecondController.self,
ThirdController.self,
SCViewController.self
]
]
override func viewDidLoad() {
super.viewDidLoad()
title = "Wave"
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
view.addSubview(tableView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
}
}
extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.textLabel?.text = "\(data[indexPath.section][indexPath.row].classForCoder())"
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
let controller = data[indexPath.section][indexPath.row].init()
controller.view.backgroundColor = UIColor.white
controller.title = "\(controller.classForCoder)"
navigationController?.pushViewController(controller, animated: true)
}
}
| mit | ce1b5b7d612fa9f94ee306a730723782 | 30.142857 | 112 | 0.666514 | 5.215311 | false | false | false | false |
mightydeveloper/swift | stdlib/public/core/Print.swift | 9 | 6624 | //===--- Print.swift ------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 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
//
//===----------------------------------------------------------------------===//
/// Writes the textual representations of `items`, separated by
/// `separator` and terminated by `terminator`, into the standard
/// output.
///
/// The textual representations are obtained for each `item` via
/// the expression `String(item)`.
///
/// - Note: To print without a trailing newline, pass `terminator: ""`
///
/// - SeeAlso: `debugPrint`, Streamable`, `CustomStringConvertible`,
/// `CustomDebugStringConvertible`
@inline(never)
@_semantics("stdlib_binary_only")
public func print(
items: Any...,
separator: String = " ",
terminator: String = "\n"
) {
if let hook = _playgroundPrintHook {
var output = _TeeStream(left: "", right: _Stdout())
_print(
items, separator: separator, terminator: terminator, toStream: &output)
hook(output.left)
}
else {
var output = _Stdout()
_print(
items, separator: separator, terminator: terminator, toStream: &output)
}
}
/// Writes the textual representations of `items` most suitable for
/// debugging, separated by `separator` and terminated by
/// `terminator`, into the standard output.
///
/// The textual representations are obtained for each `item` via
/// the expression `String(reflecting: item)`.
///
/// - Note: To print without a trailing newline, pass `terminator: ""`
///
/// - SeeAlso: `print`, Streamable`, `CustomStringConvertible`,
/// `CustomDebugStringConvertible`
@inline(never)
@_semantics("stdlib_binary_only")
public func debugPrint(
items: Any...,
separator: String = " ",
terminator: String = "\n") {
if let hook = _playgroundPrintHook {
var output = _TeeStream(left: "", right: _Stdout())
_debugPrint(
items, separator: separator, terminator: terminator, toStream: &output)
hook(output.left)
}
else {
var output = _Stdout()
_debugPrint(
items, separator: separator, terminator: terminator, toStream: &output)
}
}
/// Writes the textual representations of `items`, separated by
/// `separator` and terminated by `terminator`, into `output`.
///
/// The textual representations are obtained for each `item` via
/// the expression `String(item)`.
///
/// - Note: To print without a trailing newline, pass `terminator: ""`
///
/// - SeeAlso: `debugPrint`, Streamable`, `CustomStringConvertible`,
/// `CustomDebugStringConvertible`
@inline(__always)
public func print<Target: OutputStreamType>(
items: Any...,
separator: String = " ",
terminator: String = "\n",
inout toStream output: Target
) {
_print(items, separator: separator, terminator: terminator, toStream: &output)
}
/// Writes the textual representations of `items` most suitable for
/// debugging, separated by `separator` and terminated by
/// `terminator`, into `output`.
///
/// The textual representations are obtained for each `item` via
/// the expression `String(reflecting: item)`.
///
/// - Note: To print without a trailing newline, pass `terminator: ""`
///
/// - SeeAlso: `print`, Streamable`, `CustomStringConvertible`,
/// `CustomDebugStringConvertible`
@inline(__always)
public func debugPrint<Target: OutputStreamType>(
items: Any...,
separator: String = " ",
terminator: String = "\n",
inout toStream output: Target
) {
_debugPrint(
items, separator: separator, terminator: terminator, toStream: &output)
}
@inline(never)
@_semantics("stdlib_binary_only")
internal func _print<Target: OutputStreamType>(
items: [Any],
separator: String = " ",
terminator: String = "\n",
inout toStream output: Target
) {
var prefix = ""
output._lock()
for item in items {
output.write(prefix)
_print_unlocked(item, &output)
prefix = separator
}
output.write(terminator)
output._unlock()
}
@inline(never)
@_semantics("stdlib_binary_only")
internal func _debugPrint<Target: OutputStreamType>(
items: [Any],
separator: String = " ",
terminator: String = "\n",
inout toStream output: Target
) {
var prefix = ""
output._lock()
for item in items {
output.write(prefix)
_debugPrint_unlocked(item, &output)
prefix = separator
}
output.write(terminator)
output._unlock()
}
//===----------------------------------------------------------------------===//
//===--- Migration Aids ---------------------------------------------------===//
@available(*, unavailable, message="Please wrap your tuple argument in parentheses: 'print((...))'")
public func print<T>(_: T) {}
@available(*, unavailable, message="Please wrap your tuple argument in parentheses: 'debugPrint((...))'")
public func debugPrint<T>(_: T) {}
@available(*, unavailable, message="Please use 'terminator: \"\"' instead of 'appendNewline: false': 'print((...), terminator: \"\")'")
public func print<T>(_: T, appendNewline: Bool) {}
@available(*, unavailable, message="Please use 'terminator: \"\"' instead of 'appendNewline: false': 'debugPrint((...), terminator: \"\")'")
public func debugPrint<T>(_: T, appendNewline: Bool) {}
//===--- FIXME: Not working due to <rdar://22101775> ----------------------===//
@available(*, unavailable, message="Please use the 'toStream' label for the target stream: 'print((...), toStream: &...)'")
public func print<T>(_: T, inout _: OutputStreamType) {}
@available(*, unavailable, message="Please use the 'toStream' label for the target stream: 'debugPrint((...), toStream: &...))'")
public func debugPrint<T>(_: T, inout _: OutputStreamType) {}
@available(*, unavailable, message="Please use 'terminator: \"\"' instead of 'appendNewline: false' and use the 'toStream' label for the target stream: 'print((...), terminator: \"\", toStream: &...)'")
public func print<T>(_: T, inout _: OutputStreamType, appendNewline: Bool) {}
@available(*, unavailable, message="Please use 'terminator: \"\"' instead of 'appendNewline: false' and use the 'toStream' label for the target stream: 'debugPrint((...), terminator: \"\", toStream: &...)'")
public func debugPrint<T>(
_: T, inout _: OutputStreamType, appendNewline: Bool
) {}
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
| apache-2.0 | 3cf1ae78a2e491e591cd9551a3daf231 | 35.596685 | 207 | 0.631039 | 4.416 | false | false | false | false |
CNKCQ/oschina | OSCHINA/ViewModels/Discover/BaseViewModel.swift | 1 | 1279 | //
// Copyright © 2016年 Jack. All rights reserved.
//
import Foundation
import RxSwift
import Moya
import ObjectMapper
class BaseViewModel {
var provider: RxMoyaProvider<GankIOService>
var page = 1
var offset = 20
var backgroundWorkScheduler: OperationQueueScheduler!
init() {
let operationQueue = OperationQueue()
operationQueue.maxConcurrentOperationCount = 3
operationQueue.qualityOfService = QualityOfService.userInitiated
backgroundWorkScheduler = OperationQueueScheduler(operationQueue: operationQueue)
let networkActivityPlugin = NetworkActivityPlugin { change in
switch change {
case .ended:
UIApplication.shared.isNetworkActivityIndicatorVisible = false
case .began:
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
}
provider = RxMoyaProvider<GankIOService>(plugins: [networkActivityPlugin, NetworkLoggerPlugin.init()])
// self.provider = RxMoyaProvider<GankIOService>() /// 不用Moya自带的log插件
}
// func parseObject<T: Mappable>(response: Response) throws -> T {
// return try Mapper<T>().map(JSONString: response.mapString())!
// }
}
| mit | 25db0f6b10c386c752f626652e004f5a | 33.108108 | 110 | 0.676704 | 5.463203 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.