repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
EPICmynamesBG/SKButton | SKButton-Demo4/SKButton-Demo4/GameScene.swift | 1 | 4658 | //
// GameScene.swift
// SKButton-Demo4
//
// Created by Brandon Groff on 12/10/15.
// Copyright (c) 2015 Brandon Groff. All rights reserved.
//
import SpriteKit
class GameScene: SKScene, SKButtonDelegate {
var buttonOne: SKButton!
var screenTaps: Int = 1
override func didMoveToView(view: SKView) {
/* Setup your scene here */
self.buttonOne = SKButton(color: UIColor.orangeColor())
//Note: Because I didn't initialize my GameScene using size: Device.screenSize,
// the default button centered in view position will not work
//manually set the position
self.buttonOne.position = CGPoint(x: self.size.width / 2, y: self.size.height / 2)
// change the size of the button
self.buttonOne.size = CGSize(width: 300, height: 100)
//change all the font properties
self.buttonOne.setFont("Avenir",
withColor: UIColor.whiteColor(),
withSize: 22)
//let's check the font properties
print(self.buttonOne.font)
//add some text
self.buttonOne.text = "Some text"
//tintColor, coming up
self.buttonOne.tintColor = UIColor.yellowColor()
//shrink effect, yes
self.buttonOne.shrinkOnTap = true
//shift the text
self.buttonOne.textOffset = CGPoint(x: -2, y: 10)
self.buttonOne.delegate = self
self.addChild(self.buttonOne)
self.addLabels()
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
for touch in touches {
let _ = touch.locationInNode(self)
self.screenTaps++
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
// some simple animations
if (self.screenTaps % 4 == 2){
self.screenTaps++
self.buttonOne.hide()
} else if (self.screenTaps % 4 == 0){
self.screenTaps++
self.buttonOne.showIn(self)
}
}
// recieved when button is initially pressed down
func skButtonTouchBegan(sender: SKButton) {
print("Beginning button touch")
}
//IMPORTANT: This is required by the SKButtonDelegate and to recieve button touches
func skButtonTouchEnded(sender: SKButton) {
self.createExplosion()
}
// a simple explosion animation, for demos sake
func createExplosion() {
var deviceResolution = "@2x"
if (self.size.height > 1000){
deviceResolution = "@3x"
}
let randomX = CGFloat(arc4random_uniform(UInt32(self.size.width - 50.0))) + 25.0
let randomY = CGFloat(arc4random_uniform(UInt32(self.size.height - 50.0))) + 25.0
let randomPoint = CGPoint(x: randomX, y: randomY)
let explosionAtlas = SKTextureAtlas(named: "Explosion")
var motionFrames = [SKTexture]()
let numImages = explosionAtlas.textureNames.count / 3
for (var i = 1; i <= numImages; i++){
let textureName = "explosion.\(i)\(deviceResolution).png"
motionFrames.append(explosionAtlas.textureNamed(textureName))
}
let firstFrame = motionFrames[0]
let explosion = SKSpriteNode(texture: firstFrame)
explosion.position = randomPoint
explosion.name = "explosion"
explosion.zPosition = 10
if (deviceResolution == "@3x"){
explosion.setScale(1.5)
}
let explodeAction = SKAction.animateWithTextures(motionFrames, timePerFrame: 0.025, resize: false, restore: true)
explosion.runAction(explodeAction) { () -> Void in
explosion.removeFromParent()
}
self.addChild(explosion)
}
// some simple labels, for demos sake
func addLabels() {
let label1 = SKLabelNode(text: "Button = explosion")
let label2 = SKLabelNode(text: "Anywhere else = button effect")
label1.fontName = "Chalkduster"
label2.fontName = "Chalkduster"
label1.position = CGPoint(x: self.size.width / 2, y: 3 * self.size.height / 4)
label2.position = CGPoint(x: self.size.width / 2, y: self.size.height / 4)
label1.fontSize = 22
label2.fontSize = 24
label1.fontColor = .blackColor()
label2.fontColor = .blackColor()
label1.zPosition = 2
label2.zPosition = 2
self.addChild(label1)
self.addChild(label2)
}
}
| mit | 3793014f2467db40d83bfc0ae2c2921b | 33 | 121 | 0.596393 | 4.461686 | false | false | false | false |
alexito4/SwiftSandbox | LinkedList.playground/Pages/Final.xcplaygroundpage/Sources/LinkedList.swift | 1 | 2972 |
public class Node<T> {
var value: T {
get {
return _value!
}
set {
_value = newValue
}
}
var _value: T?
var next: Node!
var previous: Node!
init() {
next = self
previous = self
}
}
extension LinkedList {
mutating func copy() -> LinkedList<T> {
var copy = LinkedList<T>()
for node in self {
copy.append(value: node)
}
return copy
}
}
public struct LinkedList<T> {
fileprivate var sentinel = Node<T>()
private var mutableSentinel: Node<T> {
mutating get {
if !isKnownUniquelyReferenced(&sentinel) {
sentinel = self.copy().sentinel
}
return sentinel
}
}
public init() {
}
public mutating func append(value: T) {
let newNode = Node<T>()
newNode.value = value
let sentinel = mutableSentinel
newNode.next = sentinel
newNode.previous = sentinel.previous
sentinel.previous.next = newNode
sentinel.previous = newNode
}
public func value(at index: Int) -> T? {
return node(at: index)?.value
}
private func node(at index: Int) -> Node<T>? {
if index >= 0 {
var node = sentinel.next!
var i = index
while let _ = node._value {
if i == 0 { return node }
i -= 1
node = node.next
}
}
return nil
}
public mutating func remove(at index: Int) -> T? {
let _ = mutableSentinel
let found = node(at: index)
guard let node = found else { return nil }
return remove(node)
}
public func remove(_ node: Node<T>) -> T {
node.previous.next = node.next
node.next.previous = node.previous
return node.value
}
public mutating func removeAll() {
let sentinel = mutableSentinel
sentinel.next = sentinel
sentinel.previous = sentinel
}
}
extension LinkedList: CustomStringConvertible {
public var description: String {
var text = "["
var node = sentinel.next!
while let value = node._value {
text += "\(value)"
node = node.next
if node._value != nil { text += ", " }
}
return text + "]"
}
}
public struct LinkedListIterator<T>: IteratorProtocol {
var node: Node<T>
mutating public func next() -> T? {
let next = node.next!
guard let value = next._value else { return nil }
defer { node = next }
return value
}
}
extension LinkedList: Sequence {
public func makeIterator() -> LinkedListIterator<T> {
return LinkedListIterator(node: sentinel)
}
}
| mit | 3594389e4b4c63db65c3ffb421ba37c7 | 20.852941 | 57 | 0.498991 | 4.71746 | false | false | false | false |
nathawes/swift | test/AutoDiff/SILOptimizer/activity_analysis.swift | 2 | 45737 | // RUN: %target-swift-emit-sil -verify -Xllvm -debug-only=differentiation 2>&1 %s | %FileCheck %s
// REQUIRES: asserts
import _Differentiation
// Check that `@noDerivative` struct projections have "NONE" activity.
struct HasNoDerivativeProperty: Differentiable {
var x: Float
@noDerivative var y: Float
}
@differentiable
func testNoDerivativeStructProjection(_ s: HasNoDerivativeProperty) -> Float {
var tmp = s
tmp.y = tmp.x
return tmp.x
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}testNoDerivativeStructProjection{{.*}} at (parameters=(0) results=(0))
// CHECK: [ACTIVE] %0 = argument of bb0 : $HasNoDerivativeProperty
// CHECK: [ACTIVE] %2 = alloc_stack $HasNoDerivativeProperty, var, name "tmp"
// CHECK: [ACTIVE] %4 = begin_access [read] [static] %2 : $*HasNoDerivativeProperty
// CHECK: [ACTIVE] %5 = struct_element_addr %4 : $*HasNoDerivativeProperty, #HasNoDerivativeProperty.x
// CHECK: [VARIED] %6 = load [trivial] %5 : $*Float
// CHECK: [ACTIVE] %8 = begin_access [modify] [static] %2 : $*HasNoDerivativeProperty
// CHECK: [NONE] %9 = struct_element_addr %8 : $*HasNoDerivativeProperty, #HasNoDerivativeProperty.y
// CHECK: [ACTIVE] %12 = begin_access [read] [static] %2 : $*HasNoDerivativeProperty
// CHECK: [ACTIVE] %13 = struct_element_addr %12 : $*HasNoDerivativeProperty, #HasNoDerivativeProperty.x
// CHECK: [ACTIVE] %14 = load [trivial] %13 : $*Float
// Check that non-differentiable `tuple_element_addr` projections are non-varied.
@differentiable(where T : Differentiable)
func testNondifferentiableTupleElementAddr<T>(_ x: T) -> T {
var tuple = (1, 1, (x, 1), 1)
tuple.0 = 1
tuple.2.0 = x
tuple.3 = 1
return tuple.2.0
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}testNondifferentiableTupleElementAddr{{.*}} at (parameters=(0) results=(0))
// CHECK: [ACTIVE] %0 = argument of bb0 : $*T
// CHECK: [ACTIVE] %1 = argument of bb0 : $*T
// CHECK: [ACTIVE] %3 = alloc_stack $(Int, Int, (T, Int), Int), var, name "tuple"
// CHECK: [USEFUL] %4 = tuple_element_addr %3 : $*(Int, Int, (T, Int), Int), 0
// CHECK: [USEFUL] %5 = tuple_element_addr %3 : $*(Int, Int, (T, Int), Int), 1
// CHECK: [ACTIVE] %6 = tuple_element_addr %3 : $*(Int, Int, (T, Int), Int), 2
// CHECK: [USEFUL] %7 = tuple_element_addr %3 : $*(Int, Int, (T, Int), Int), 3
// CHECK: [ACTIVE] %18 = tuple_element_addr %6 : $*(T, Int), 0
// CHECK: [USEFUL] %19 = tuple_element_addr %6 : $*(T, Int), 1
// CHECK: [ACTIVE] %35 = begin_access [modify] [static] %3 : $*(Int, Int, (T, Int), Int)
// CHECK: [USEFUL] %36 = tuple_element_addr %35 : $*(Int, Int, (T, Int), Int), 0
// CHECK: [ACTIVE] %41 = begin_access [modify] [static] %3 : $*(Int, Int, (T, Int), Int)
// CHECK: [ACTIVE] %42 = tuple_element_addr %41 : $*(Int, Int, (T, Int), Int), 2
// CHECK: [ACTIVE] %43 = tuple_element_addr %42 : $*(T, Int), 0
// CHECK: [ACTIVE] %51 = begin_access [modify] [static] %3 : $*(Int, Int, (T, Int), Int)
// CHECK: [USEFUL] %52 = tuple_element_addr %51 : $*(Int, Int, (T, Int), Int), 3
// CHECK: [ACTIVE] %55 = begin_access [read] [static] %3 : $*(Int, Int, (T, Int), Int)
// CHECK: [ACTIVE] %56 = tuple_element_addr %55 : $*(Int, Int, (T, Int), Int), 2
// CHECK: [ACTIVE] %57 = tuple_element_addr %56 : $*(T, Int), 0
// TF-781: check active local address + nested conditionals.
@differentiable(wrt: x)
func TF_781(_ x: Float, _ y: Float) -> Float {
var result = y
if true {
if true {
result = result * x // check activity of `result` and this `apply`
}
}
return result
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}TF_781{{.*}} at (parameters=(0) results=(0))
// CHECK: [ACTIVE] %0 = argument of bb0 : $Float
// CHECK: [USEFUL] %1 = argument of bb0 : $Float
// CHECK: [ACTIVE] %4 = alloc_stack $Float, var, name "result"
// CHECK: [ACTIVE] %19 = begin_access [read] [static] %4 : $*Float
// CHECK: [ACTIVE] %20 = load [trivial] %19 : $*Float
// CHECK: [ACTIVE] %23 = apply %22(%20, %0, %18) : $@convention(method) (Float, Float, @thin Float.Type) -> Float
// CHECK: [ACTIVE] %24 = begin_access [modify] [static] %4 : $*Float
// CHECK: [ACTIVE] %31 = begin_access [read] [static] %4 : $*Float
// CHECK: [ACTIVE] %32 = load [trivial] %31 : $*Float
// TF-954: check nested conditionals and addresses.
@differentiable
func TF_954(_ x: Float) -> Float {
var outer = x
outerIf: if true {
var inner = outer
inner = inner * x // check activity of this `apply`
if false {
break outerIf
}
outer = inner
}
return outer
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}TF_954{{.*}} at (parameters=(0) results=(0))
// CHECK: bb0:
// CHECK: [ACTIVE] %0 = argument of bb0 : $Float
// CHECK: [ACTIVE] %2 = alloc_stack $Float, var, name "outer"
// CHECK: bb1:
// CHECK: [ACTIVE] %10 = alloc_stack $Float, var, name "inner"
// CHECK: [ACTIVE] %11 = begin_access [read] [static] %2 : $*Float
// CHECK: [USEFUL] %14 = metatype $@thin Float.Type
// CHECK: [ACTIVE] %15 = begin_access [read] [static] %10 : $*Float
// CHECK: [ACTIVE] %16 = load [trivial] %15 : $*Float
// CHECK: [NONE] // function_ref static Float.* infix(_:_:)
// CHECK: %18 = function_ref @$sSf1moiyS2f_SftFZ : $@convention(method) (Float, Float, @thin Float.Type) -> Float
// CHECK: [ACTIVE] %19 = apply %18(%16, %0, %14) : $@convention(method) (Float, Float, @thin Float.Type) -> Float
// CHECK: [ACTIVE] %20 = begin_access [modify] [static] %10 : $*Float
// CHECK: bb3:
// CHECK: [ACTIVE] %31 = begin_access [read] [static] %10 : $*Float
// CHECK: [ACTIVE] %32 = load [trivial] %31 : $*Float
// CHECK: [ACTIVE] %34 = begin_access [modify] [static] %2 : $*Float
// CHECK: bb5:
// CHECK: [ACTIVE] %40 = begin_access [read] [static] %2 : $*Float
// CHECK: [ACTIVE] %41 = load [trivial] %40 : $*Float
//===----------------------------------------------------------------------===//
// Branching cast instructions
//===----------------------------------------------------------------------===//
@differentiable
func checked_cast_branch(_ x: Float) -> Float {
// expected-warning @+1 {{'is' test is always true}}
if Int.self is Any.Type {
return x + x
}
return x * x
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}checked_cast_branch{{.*}} at (parameters=(0) results=(0))
// CHECK: bb0:
// CHECK: [ACTIVE] %0 = argument of bb0 : $Float
// CHECK: [NONE] %2 = metatype $@thin Int.Type
// CHECK: [NONE] %3 = metatype $@thick Int.Type
// CHECK: bb1:
// CHECK: [NONE] %5 = argument of bb1 : $@thick Any.Type
// CHECK: [NONE] %6 = integer_literal $Builtin.Int1, -1
// CHECK: bb2:
// CHECK: [NONE] %8 = argument of bb2 : $@thick Int.Type
// CHECK: [NONE] %9 = integer_literal $Builtin.Int1, 0
// CHECK: bb3:
// CHECK: [NONE] %11 = argument of bb3 : $Builtin.Int1
// CHECK: [NONE] %12 = metatype $@thin Bool.Type
// CHECK: [NONE] // function_ref Bool.init(_builtinBooleanLiteral:)
// CHECK: [NONE] %14 = apply %13(%11, %12) : $@convention(method) (Builtin.Int1, @thin Bool.Type) -> Bool
// CHECK: [NONE] %15 = struct_extract %14 : $Bool, #Bool._value
// CHECK: bb4:
// CHECK: [USEFUL] %17 = metatype $@thin Float.Type
// CHECK: [NONE] // function_ref static Float.+ infix(_:_:)
// CHECK: [ACTIVE] %19 = apply %18(%0, %0, %17) : $@convention(method) (Float, Float, @thin Float.Type) -> Float
// CHECK: bb5:
// CHECK: [USEFUL] %21 = metatype $@thin Float.Type
// CHECK: [NONE] // function_ref static Float.* infix(_:_:)
// CHECK: [ACTIVE] %23 = apply %22(%0, %0, %21) : $@convention(method) (Float, Float, @thin Float.Type) -> Float
// CHECK-LABEL: sil hidden [ossa] @${{.*}}checked_cast_branch{{.*}} : $@convention(thin) (Float) -> Float {
// CHECK: checked_cast_br %3 : $@thick Int.Type to Any.Type, bb1, bb2
// CHECK: }
@differentiable
func checked_cast_addr_nonactive_result<T: Differentiable>(_ x: T) -> T {
if let _ = x as? Float {
// Do nothing with `y: Float?` value.
}
return x
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}checked_cast_addr_nonactive_result{{.*}} at (parameters=(0) results=(0))
// CHECK: bb0:
// CHECK: [ACTIVE] %0 = argument of bb0 : $*T
// CHECK: [ACTIVE] %1 = argument of bb0 : $*T
// CHECK: [VARIED] %3 = alloc_stack $T
// CHECK: [VARIED] %5 = alloc_stack $Float
// CHECK: bb1:
// CHECK: [VARIED] %7 = load [trivial] %5 : $*Float
// CHECK: [VARIED] %8 = enum $Optional<Float>, #Optional.some!enumelt, %7 : $Float
// CHECK: bb2:
// CHECK: [NONE] %11 = enum $Optional<Float>, #Optional.none!enumelt
// CHECK: bb3:
// CHECK: [VARIED] %14 = argument of bb3 : $Optional<Float>
// CHECK: bb4:
// CHECK: bb5:
// CHECK: [VARIED] %18 = argument of bb5 : $Float
// CHECK: bb6:
// CHECK: [NONE] %22 = tuple ()
// CHECK-LABEL: sil hidden [ossa] @${{.*}}checked_cast_addr_nonactive_result{{.*}} : $@convention(thin) <T where T : Differentiable> (@in_guaranteed T) -> @out T {
// CHECK: checked_cast_addr_br take_always T in %3 : $*T to Float in %5 : $*Float, bb1, bb2
// CHECK: }
// expected-error @+1 {{function is not differentiable}}
@differentiable
// expected-note @+1 {{when differentiating this function definition}}
func checked_cast_addr_active_result<T: Differentiable>(x: T) -> T {
// expected-note @+1 {{expression is not differentiable}}
if let y = x as? Float {
// Use `y: Float?` value in an active way.
return y as! T
}
return x
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}checked_cast_addr_active_result{{.*}} at (parameters=(0) results=(0))
// CHECK: bb0:
// CHECK: [ACTIVE] %0 = argument of bb0 : $*T
// CHECK: [ACTIVE] %1 = argument of bb0 : $*T
// CHECK: [ACTIVE] %3 = alloc_stack $T
// CHECK: [ACTIVE] %5 = alloc_stack $Float
// CHECK: bb1:
// CHECK: [ACTIVE] %7 = load [trivial] %5 : $*Float
// CHECK: [ACTIVE] %8 = enum $Optional<Float>, #Optional.some!enumelt, %7 : $Float
// CHECK: bb2:
// CHECK: [USEFUL] %11 = enum $Optional<Float>, #Optional.none!enumelt
// CHECK: bb3:
// CHECK: [ACTIVE] %14 = argument of bb3 : $Optional<Float>
// CHECK: bb4:
// CHECK: [ACTIVE] %16 = argument of bb4 : $Float
// CHECK: [ACTIVE] %19 = alloc_stack $Float
// CHECK: bb5:
// CHECK: bb6:
// CHECK: [NONE] %27 = tuple ()
// CHECK-LABEL: sil hidden [ossa] @${{.*}}checked_cast_addr_active_result{{.*}} : $@convention(thin) <T where T : Differentiable> (@in_guaranteed T) -> @out T {
// CHECK: checked_cast_addr_br take_always T in %3 : $*T to Float in %5 : $*Float, bb1, bb2
// CHECK: }
//===----------------------------------------------------------------------===//
// Array literal differentiation
//===----------------------------------------------------------------------===//
// Check `array.uninitialized_intrinsic` applications.
@differentiable
func testArrayUninitializedIntrinsic(_ x: Float, _ y: Float) -> [Float] {
return [x, y]
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}testArrayUninitializedIntrinsic{{.*}} at (parameters=(0 1) results=(0))
// CHECK: [ACTIVE] %0 = argument of bb0 : $Float
// CHECK: [ACTIVE] %1 = argument of bb0 : $Float
// CHECK: [USEFUL] %4 = integer_literal $Builtin.Word, 2
// CHECK: [NONE] // function_ref _allocateUninitializedArray<A>(_:)
// CHECK: [ACTIVE] %6 = apply %5<Float>(%4) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer)
// CHECK: [ACTIVE] (**%7**, %8) = destructure_tuple %6 : $(Array<Float>, Builtin.RawPointer)
// CHECK: [VARIED] (%7, **%8**) = destructure_tuple %6 : $(Array<Float>, Builtin.RawPointer)
// CHECK: [ACTIVE] %9 = pointer_to_address %8 : $Builtin.RawPointer to [strict] $*Float
// CHECK: [VARIED] %11 = integer_literal $Builtin.Word, 1
// CHECK: [ACTIVE] %12 = index_addr %9 : $*Float, %11 : $Builtin.Word
// CHECK: [NONE] // function_ref _finalizeUninitializedArray<A>(_:)
// CHECK: [ACTIVE] %15 = apply %14<Float>(%7) : $@convention(thin) <τ_0_0> (@owned Array<τ_0_0>) -> @owned Array<τ_0_0>
@differentiable(where T: Differentiable)
func testArrayUninitializedIntrinsicGeneric<T>(_ x: T, _ y: T) -> [T] {
return [x, y]
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}testArrayUninitializedIntrinsicGeneric{{.*}} at (parameters=(0 1) results=(0))
// CHECK: [ACTIVE] %0 = argument of bb0 : $*T
// CHECK: [ACTIVE] %1 = argument of bb0 : $*T
// CHECK: [USEFUL] %4 = integer_literal $Builtin.Word, 2
// CHECK: [NONE] // function_ref _allocateUninitializedArray<A>(_:)
// CHECK: [ACTIVE] %6 = apply %5<T>(%4) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer)
// CHECK: [ACTIVE] (**%7**, %8) = destructure_tuple %6 : $(Array<T>, Builtin.RawPointer)
// CHECK: [VARIED] (%7, **%8**) = destructure_tuple %6 : $(Array<T>, Builtin.RawPointer)
// CHECK: [ACTIVE] %9 = pointer_to_address %8 : $Builtin.RawPointer to [strict] $*T
// CHECK: [VARIED] %11 = integer_literal $Builtin.Word, 1
// CHECK: [ACTIVE] %12 = index_addr %9 : $*T, %11 : $Builtin.Word
// CHECK: [NONE] // function_ref _finalizeUninitializedArray<A>(_:)
// CHECK: [ACTIVE] %15 = apply %14<T>(%7) : $@convention(thin) <τ_0_0> (@owned Array<τ_0_0>) -> @owned Array<τ_0_0>
// TF-952: Test array literal initialized from an address (e.g. `var`).
@differentiable
func testArrayUninitializedIntrinsicAddress(_ x: Float, _ y: Float) -> [Float] {
var result = x
result = result * y
return [result, result]
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}testArrayUninitializedIntrinsicAddress{{.*}} at (parameters=(0 1) results=(0))
// CHECK: [ACTIVE] %0 = argument of bb0 : $Float
// CHECK: [ACTIVE] %1 = argument of bb0 : $Float
// CHECK: [ACTIVE] %4 = alloc_stack $Float, var, name "result"
// CHECK: [ACTIVE] %7 = begin_access [read] [static] %4 : $*Float
// CHECK: [ACTIVE] %8 = load [trivial] %7 : $*Float
// CHECK: [NONE] // function_ref static Float.* infix(_:_:)
// CHECK: [ACTIVE] %11 = apply %10(%8, %1, %6) : $@convention(method) (Float, Float, @thin Float.Type) -> Float
// CHECK: [ACTIVE] %12 = begin_access [modify] [static] %4 : $*Float
// CHECK: [USEFUL] %15 = integer_literal $Builtin.Word, 2
// CHECK: [NONE] // function_ref _allocateUninitializedArray<A>(_:)
// CHECK: [ACTIVE] %17 = apply %16<Float>(%15) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer)
// CHECK: [ACTIVE] (**%18**, %19) = destructure_tuple %17 : $(Array<Float>, Builtin.RawPointer)
// CHECK: [VARIED] (%18, **%19**) = destructure_tuple %17 : $(Array<Float>, Builtin.RawPointer)
// CHECK: [ACTIVE] %20 = pointer_to_address %19 : $Builtin.RawPointer to [strict] $*Float
// CHECK: [ACTIVE] %21 = begin_access [read] [static] %4 : $*Float
// CHECK: [VARIED] %24 = integer_literal $Builtin.Word, 1
// CHECK: [ACTIVE] %25 = index_addr %20 : $*Float, %24 : $Builtin.Word
// CHECK: [ACTIVE] %26 = begin_access [read] [static] %4 : $*Float
// CHECK: [NONE] // function_ref _finalizeUninitializedArray<A>(_:)
// CHECK: [ACTIVE] %30 = apply %29<Float>(%18) : $@convention(thin) <τ_0_0> (@owned Array<τ_0_0>) -> @owned Array<τ_0_0>
// TF-952: Test array literal initialized with `apply` direct results.
@differentiable
func testArrayUninitializedIntrinsicFunctionResult(_ x: Float, _ y: Float) -> [Float] {
return [x * y, x * y]
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}testArrayUninitializedIntrinsicFunctionResult{{.*}} at (parameters=(0 1) results=(0))
// CHECK: [ACTIVE] %0 = argument of bb0 : $Float
// CHECK: [ACTIVE] %1 = argument of bb0 : $Float
// CHECK: [USEFUL] %4 = integer_literal $Builtin.Word, 2
// CHECK: [NONE] // function_ref _allocateUninitializedArray<A>(_:)
// CHECK: [ACTIVE] %6 = apply %5<Float>(%4) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer)
// CHECK: [ACTIVE] (**%7**, %8) = destructure_tuple %6 : $(Array<Float>, Builtin.RawPointer)
// CHECK: [VARIED] (%7, **%8**) = destructure_tuple %6 : $(Array<Float>, Builtin.RawPointer)
// CHECK: [ACTIVE] %9 = pointer_to_address %8 : $Builtin.RawPointer to [strict] $*Float
// CHECK: [NONE] // function_ref static Float.* infix(_:_:)
// CHECK: [ACTIVE] %12 = apply %11(%0, %1, %10) : $@convention(method) (Float, Float, @thin Float.Type) -> Float
// CHECK: [VARIED] %14 = integer_literal $Builtin.Word, 1
// CHECK: [ACTIVE] %15 = index_addr %9 : $*Float, %14 : $Builtin.Word
// CHECK: [USEFUL] %16 = metatype $@thin Float.Type
// CHECK: [NONE] // function_ref static Float.* infix(_:_:)
// CHECK: [ACTIVE] %18 = apply %17(%0, %1, %16) : $@convention(method) (Float, Float, @thin Float.Type) -> Float
// CHECK: [NONE] // function_ref _finalizeUninitializedArray<A>(_:)
// CHECK: [ACTIVE] %21 = apply %20<Float>(%7) : $@convention(thin) <τ_0_0> (@owned Array<τ_0_0>) -> @owned Array<τ_0_0>
// TF-975: Test nested array literals.
@differentiable
func testArrayUninitializedIntrinsicNested(_ x: Float, _ y: Float) -> [Float] {
let array = [x, y]
return [array[0], array[1]]
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}testArrayUninitializedIntrinsicNested{{.*}} at (parameters=(0 1) results=(0))
// CHECK: [ACTIVE] %0 = argument of bb0 : $Float
// CHECK: [ACTIVE] %1 = argument of bb0 : $Float
// CHECK: [USEFUL] %4 = integer_literal $Builtin.Word, 2
// CHECK: [NONE] // function_ref _allocateUninitializedArray<A>(_:)
// CHECK: [ACTIVE] %6 = apply %5<Float>(%4) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer)
// CHECK: [ACTIVE] (**%7**, %8) = destructure_tuple %6 : $(Array<Float>, Builtin.RawPointer)
// CHECK: [VARIED] (%7, **%8**) = destructure_tuple %6 : $(Array<Float>, Builtin.RawPointer)
// CHECK: [ACTIVE] %9 = pointer_to_address %8 : $Builtin.RawPointer to [strict] $*Float
// CHECK: [VARIED] %11 = integer_literal $Builtin.Word, 1
// CHECK: [ACTIVE] %12 = index_addr %9 : $*Float, %11 : $Builtin.Word
// CHECK: [NONE] // function_ref _finalizeUninitializedArray<A>(_:)
// CHECK: [ACTIVE] %15 = apply %14<Float>(%7) : $@convention(thin) <τ_0_0> (@owned Array<τ_0_0>) -> @owned Array<τ_0_0>
// CHECK: [USEFUL] %17 = integer_literal $Builtin.Word, 2
// CHECK: [NONE] // function_ref _allocateUninitializedArray<A>(_:)
// CHECK: [ACTIVE] %19 = apply %18<Float>(%17) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer)
// CHECK: [ACTIVE] (**%20**, %21) = destructure_tuple %19 : $(Array<Float>, Builtin.RawPointer)
// CHECK: [VARIED] (%20, **%21**) = destructure_tuple %19 : $(Array<Float>, Builtin.RawPointer)
// CHECK: [ACTIVE] %22 = pointer_to_address %21 : $Builtin.RawPointer to [strict] $*Float
// CHECK: [ACTIVE] %23 = begin_borrow %15 : $Array<Float>
// CHECK: [USEFUL] %24 = integer_literal $Builtin.IntLiteral, 0
// CHECK: [USEFUL] %25 = metatype $@thin Int.Type
// CHECK: [NONE] // function_ref Int.init(_builtinIntegerLiteral:)
// CHECK: [USEFUL] %27 = apply %26(%24, %25) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int
// CHECK: [NONE] // function_ref Array.subscript.getter
// CHECK: [NONE] %29 = apply %28<Float>(%22, %27, %23) : $@convention(method) <τ_0_0> (Int, @guaranteed Array<τ_0_0>) -> @out τ_0_0
// CHECK: [VARIED] %30 = integer_literal $Builtin.Word, 1
// CHECK: [ACTIVE] %31 = index_addr %22 : $*Float, %30 : $Builtin.Word
// CHECK: [ACTIVE] %32 = begin_borrow %15 : $Array<Float>
// CHECK: [USEFUL] %33 = integer_literal $Builtin.IntLiteral, 1
// CHECK: [USEFUL] %34 = metatype $@thin Int.Type
// CHECK: [NONE] // function_ref Int.init(_builtinIntegerLiteral:)
// CHECK: [USEFUL] %36 = apply %35(%33, %34) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int
// CHECK: [NONE] // function_ref Array.subscript.getter
// CHECK: [NONE] %38 = apply %37<Float>(%31, %36, %32) : $@convention(method) <τ_0_0> (Int, @guaranteed Array<τ_0_0>) -> @out τ_0_0
// CHECK: [NONE] // function_ref _finalizeUninitializedArray<A>(_:)
// CHECK: [ACTIVE] %40 = apply %39<Float>(%20) : $@convention(thin) <τ_0_0> (@owned Array<τ_0_0>) -> @owned Array<τ_0_0>
// TF-978: Test array literal initialized with `apply` indirect results.
struct Wrapper<T: Differentiable>: Differentiable {
var value: T
}
@differentiable
func testArrayUninitializedIntrinsicApplyIndirectResult<T>(_ x: T, _ y: T) -> [Wrapper<T>] {
return [Wrapper(value: x), Wrapper(value: y)]
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}testArrayUninitializedIntrinsicApplyIndirectResult{{.*}} at (parameters=(0 1) results=(0))
// CHECK: [ACTIVE] %0 = argument of bb0 : $*T
// CHECK: [ACTIVE] %1 = argument of bb0 : $*T
// CHECK: [USEFUL] %4 = integer_literal $Builtin.Word, 2
// CHECK: [NONE] // function_ref _allocateUninitializedArray<A>(_:)
// CHECK: [ACTIVE] %6 = apply %5<Wrapper<T>>(%4) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer)
// CHECK: [ACTIVE] (**%7**, %8) = destructure_tuple %6 : $(Array<Wrapper<T>>, Builtin.RawPointer)
// CHECK: [VARIED] (%7, **%8**) = destructure_tuple %6 : $(Array<Wrapper<T>>, Builtin.RawPointer)
// CHECK: [ACTIVE] %9 = pointer_to_address %8 : $Builtin.RawPointer to [strict] $*Wrapper<T>
// CHECK: [USEFUL] %10 = metatype $@thin Wrapper<T>.Type
// CHECK: [ACTIVE] %11 = alloc_stack $T
// CHECK: [NONE] // function_ref Wrapper.init(value:)
// CHECK: [NONE] %14 = apply %13<T>(%9, %11, %10) : $@convention(method) <τ_0_0 where τ_0_0 : Differentiable> (@in τ_0_0, @thin Wrapper<τ_0_0>.Type) -> @out Wrapper<τ_0_0>
// CHECK: [VARIED] %16 = integer_literal $Builtin.Word, 1
// CHECK: [ACTIVE] %17 = index_addr %9 : $*Wrapper<T>, %16 : $Builtin.Word
// CHECK: [USEFUL] %18 = metatype $@thin Wrapper<T>.Type
// CHECK: [ACTIVE] %19 = alloc_stack $T
// CHECK: [NONE] // function_ref Wrapper.init(value:)
// CHECK: [NONE] %22 = apply %21<T>(%17, %19, %18) : $@convention(method) <τ_0_0 where τ_0_0 : Differentiable> (@in τ_0_0, @thin Wrapper<τ_0_0>.Type) -> @out Wrapper<τ_0_0>
// CHECK: [NONE] // function_ref _finalizeUninitializedArray<A>(_:)
// CHECK: [ACTIVE] %25 = apply %24<Wrapper<T>>(%7) : $@convention(thin) <τ_0_0> (@owned Array<τ_0_0>) -> @owned Array<τ_0_0>
//===----------------------------------------------------------------------===//
// `inout` argument differentiation
//===----------------------------------------------------------------------===//
struct Mut: Differentiable {}
extension Mut {
@differentiable(wrt: x)
mutating func mutatingMethod(_ x: Mut) {}
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}3MutV14mutatingMethodyyACF at (parameters=(0) results=(0))
// CHECK: [VARIED] %0 = argument of bb0 : $Mut
// CHECK: [USEFUL] %1 = argument of bb0 : $*Mut
// TODO(TF-985): Find workaround to avoid marking non-wrt `inout` argument as
// active.
@differentiable(wrt: x)
func nonActiveInoutArg(_ nonactive: inout Mut, _ x: Mut) {
nonactive.mutatingMethod(x)
nonactive = x
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}17nonActiveInoutArgyyAA3MutVz_ADtF at (parameters=(1) results=(0))
// CHECK: [ACTIVE] %0 = argument of bb0 : $*Mut
// CHECK: [ACTIVE] %1 = argument of bb0 : $Mut
// CHECK: [ACTIVE] %4 = begin_access [modify] [static] %0 : $*Mut
// CHECK: [NONE] // function_ref Mut.mutatingMethod(_:)
// CHECK: [NONE] %6 = apply %5(%1, %4) : $@convention(method) (Mut, @inout Mut) -> ()
// CHECK: [ACTIVE] %8 = begin_access [modify] [static] %0 : $*Mut
@differentiable(wrt: x)
func activeInoutArgMutatingMethod(_ x: Mut) -> Mut {
var result = x
result.mutatingMethod(result)
return result
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}28activeInoutArgMutatingMethodyAA3MutVADF at (parameters=(0) results=(0))
// CHECK: [ACTIVE] %0 = argument of bb0 : $Mut
// CHECK: [ACTIVE] %2 = alloc_stack $Mut, var, name "result"
// CHECK: [ACTIVE] %4 = begin_access [read] [static] %2 : $*Mut
// CHECK: [ACTIVE] %5 = load [trivial] %4 : $*Mut
// CHECK: [ACTIVE] %7 = begin_access [modify] [static] %2 : $*Mut
// CHECK: [NONE] // function_ref Mut.mutatingMethod(_:)
// CHECK: [NONE] %9 = apply %8(%5, %7) : $@convention(method) (Mut, @inout Mut) -> ()
// CHECK: [ACTIVE] %11 = begin_access [read] [static] %2 : $*Mut
// CHECK: [ACTIVE] %12 = load [trivial] %11 : $*Mut
@differentiable(wrt: x)
func activeInoutArgMutatingMethodVar(_ nonactive: inout Mut, _ x: Mut) {
var result = nonactive
result.mutatingMethod(x)
nonactive = result
}
// CHECK_LABEL: [AD] Activity info for ${{.*}}31activeInoutArgMutatingMethodVaryyAA3MutVz_ADtF at (parameters=(1) results=(0))
// CHECK: [ACTIVE] %0 = argument of bb0 : $*Mut
// CHECK: [ACTIVE] %1 = argument of bb0 : $Mut
// CHECK: [ACTIVE] %4 = alloc_stack $Mut, var, name "result"
// CHECK: [ACTIVE] %5 = begin_access [read] [static] %0 : $*Mut
// CHECK: [ACTIVE] %8 = begin_access [modify] [static] %4 : $*Mut
// CHECK: [NONE] // function_ref Mut.mutatingMethod(_:)
// CHECK: %9 = function_ref @${{.*}}3MutV14mutatingMethodyyACF : $@convention(method) (Mut, @inout Mut) -> ()
// CHECK: [NONE] %10 = apply %9(%1, %8) : $@convention(method) (Mut, @inout Mut) -> ()
// CHECK: [ACTIVE] %12 = begin_access [read] [static] %4 : $*Mut
// CHECK: [ACTIVE] %13 = load [trivial] %12 : $*Mut
// CHECK: [ACTIVE] %15 = begin_access [modify] [static] %0 : $*Mut
// CHECK: [NONE] %19 = tuple ()
@differentiable(wrt: x)
func activeInoutArgMutatingMethodTuple(_ nonactive: inout Mut, _ x: Mut) {
var result = (nonactive, x)
result.0.mutatingMethod(result.0)
nonactive = result.0
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}33activeInoutArgMutatingMethodTupleyyAA3MutVz_ADtF at (parameters=(1) results=(0))
// CHECK: [ACTIVE] %0 = argument of bb0 : $*Mut
// CHECK: [ACTIVE] %1 = argument of bb0 : $Mut
// CHECK: [ACTIVE] %4 = alloc_stack $(Mut, Mut), var, name "result"
// CHECK: [ACTIVE] %5 = tuple_element_addr %4 : $*(Mut, Mut), 0
// CHECK: [ACTIVE] %6 = tuple_element_addr %4 : $*(Mut, Mut), 1
// CHECK: [ACTIVE] %7 = begin_access [read] [static] %0 : $*Mut
// CHECK: [ACTIVE] %11 = begin_access [read] [static] %4 : $*(Mut, Mut)
// CHECK: [ACTIVE] %12 = tuple_element_addr %11 : $*(Mut, Mut), 0
// CHECK: [ACTIVE] %13 = load [trivial] %12 : $*Mut
// CHECK: [ACTIVE] %15 = begin_access [modify] [static] %4 : $*(Mut, Mut)
// CHECK: [ACTIVE] %16 = tuple_element_addr %15 : $*(Mut, Mut), 0
// CHECK: [NONE] // function_ref Mut.mutatingMethod(_:)
// CHECK: [NONE] %18 = apply %17(%13, %16) : $@convention(method) (Mut, @inout Mut) -> ()
// CHECK: [ACTIVE] %20 = begin_access [read] [static] %4 : $*(Mut, Mut)
// CHECK: [ACTIVE] %21 = tuple_element_addr %20 : $*(Mut, Mut), 0
// CHECK: [ACTIVE] %22 = load [trivial] %21 : $*Mut
// CHECK: [ACTIVE] %24 = begin_access [modify] [static] %0 : $*Mut
// Check `inout` arguments.
@differentiable
func activeInoutArg(_ x: Float) -> Float {
var result = x
result += x
return result
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}activeInoutArg{{.*}} at (parameters=(0) results=(0))
// CHECK: [ACTIVE] %0 = argument of bb0 : $Float
// CHECK: [ACTIVE] %2 = alloc_stack $Float, var, name "result"
// CHECK: [ACTIVE] %5 = begin_access [modify] [static] %2 : $*Float
// CHECK: [NONE] // function_ref static Float.+= infix(_:_:)
// CHECK: [NONE] %7 = apply %6(%5, %0, %4) : $@convention(method) (@inout Float, Float, @thin Float.Type) -> ()
// CHECK: [ACTIVE] %9 = begin_access [read] [static] %2 : $*Float
// CHECK: [ACTIVE] %10 = load [trivial] %9 : $*Float
@differentiable
func activeInoutArgNonactiveInitialResult(_ x: Float) -> Float {
var result: Float = 1
result += x
return result
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}activeInoutArgNonactiveInitialResult{{.*}} at (parameters=(0) results=(0))
// CHECK: [ACTIVE] %0 = argument of bb0 : $Float
// CHECK: [ACTIVE] %2 = alloc_stack $Float, var, name "result"
// CHECK: [NONE] // function_ref Float.init(_builtinIntegerLiteral:)
// CHECK: [USEFUL] %6 = apply %5(%3, %4) : $@convention(method) (Builtin.IntLiteral, @thin Float.Type) -> Float
// CHECK: [USEFUL] %8 = metatype $@thin Float.Type
// CHECK: [ACTIVE] %9 = begin_access [modify] [static] %2 : $*Float
// CHECK: [NONE] // function_ref static Float.+= infix(_:_:)
// CHECK: [NONE] %11 = apply %10(%9, %0, %8) : $@convention(method) (@inout Float, Float, @thin Float.Type) -> ()
// CHECK: [ACTIVE] %13 = begin_access [read] [static] %2 : $*Float
// CHECK: [ACTIVE] %14 = load [trivial] %13 : $*Float
//===----------------------------------------------------------------------===//
// Throwing function differentiation (`try_apply`)
//===----------------------------------------------------------------------===//
// TF-433: Test `try_apply`.
func rethrowing(_ x: () throws -> Void) rethrows -> Void {}
@differentiable
func testTryApply(_ x: Float) -> Float {
rethrowing({})
return x
}
// TF-433: differentiation diagnoses `try_apply` before activity info is printed.
// CHECK-LABEL: [AD] Activity info for ${{.*}}testTryApply{{.*}} at (parameters=(0) results=(0))
// CHECK: bb0:
// CHECK: [ACTIVE] %0 = argument of bb0 : $Float
// CHECK: [NONE] // function_ref closure #1 in testTryApply(_:)
// CHECK: [NONE] %3 = convert_function %2 : $@convention(thin) () -> () to $@convention(thin) @noescape () -> ()
// CHECK: [NONE] %4 = thin_to_thick_function %3 : $@convention(thin) @noescape () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK: [NONE] %5 = convert_function %4 : $@noescape @callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> @error Error
// CHECK: [NONE] // function_ref rethrowing(_:)
// CHECK: bb1:
// CHECK: [NONE] %8 = argument of bb1 : $()
// CHECK: bb2:
// CHECK: [NONE] %10 = argument of bb2 : $Error
//===----------------------------------------------------------------------===//
// Coroutine differentiation (`begin_apply`)
//===----------------------------------------------------------------------===//
struct HasCoroutineAccessors: Differentiable {
var stored: Float
var computed: Float {
// `_read` is a coroutine: `(Self) -> () -> ()`.
_read { yield stored }
// `_modify` is a coroutine: `(inout Self) -> () -> ()`.
_modify { yield &stored }
}
}
// expected-error @+1 {{function is not differentiable}}
@differentiable
// expected-note @+1 {{when differentiating this function definition}}
func testAccessorCoroutines(_ x: HasCoroutineAccessors) -> HasCoroutineAccessors {
var x = x
// expected-note @+1 {{differentiation of coroutine calls is not yet supported}}
x.computed = x.computed
return x
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}testAccessorCoroutines{{.*}} at (parameters=(0) results=(0))
// CHECK: [ACTIVE] %0 = argument of bb0 : $HasCoroutineAccessors
// CHECK: [ACTIVE] %2 = alloc_stack $HasCoroutineAccessors, var, name "x"
// CHECK: [ACTIVE] %4 = begin_access [read] [static] %2 : $*HasCoroutineAccessors
// CHECK: [ACTIVE] %5 = load [trivial] %4 : $*HasCoroutineAccessors
// CHECK: [NONE] // function_ref HasCoroutineAccessors.computed.read
// CHECK: [ACTIVE] (**%7**, %8) = begin_apply %6(%5) : $@yield_once @convention(method) (HasCoroutineAccessors) -> @yields Float
// CHECK: [VARIED] (%7, **%8**) = begin_apply %6(%5) : $@yield_once @convention(method) (HasCoroutineAccessors) -> @yields Float
// CHECK: [ACTIVE] %9 = alloc_stack $Float
// CHECK: [ACTIVE] %11 = load [trivial] %9 : $*Float
// CHECK: [ACTIVE] %14 = begin_access [modify] [static] %2 : $*HasCoroutineAccessors
// CHECK: [NONE] // function_ref HasCoroutineAccessors.computed.modify
// CHECK: %15 = function_ref @${{.*}}21HasCoroutineAccessorsV8computedSfvM : $@yield_once @convention(method) (@inout HasCoroutineAccessors) -> @yields @inout Float
// CHECK: [ACTIVE] (**%16**, %17) = begin_apply %15(%14) : $@yield_once @convention(method) (@inout HasCoroutineAccessors) -> @yields @inout Float
// CHECK: [VARIED] (%16, **%17**) = begin_apply %15(%14) : $@yield_once @convention(method) (@inout HasCoroutineAccessors) -> @yields @inout Float
// CHECK: [ACTIVE] %22 = begin_access [read] [static] %2 : $*HasCoroutineAccessors
// CHECK: [ACTIVE] %23 = load [trivial] %22 : $*HasCoroutineAccessors
// TF-1078: Test `begin_apply` active `inout` argument.
// `Array.subscript.modify` is the applied coroutine.
// expected-error @+1 {{function is not differentiable}}
@differentiable
// expected-note @+1 {{when differentiating this function definition}}
func testBeginApplyActiveInoutArgument(array: [Float], x: Float) -> Float {
var array = array
// Array subscript assignment below calls `Array.subscript.modify`.
// expected-note @+1 {{differentiation of coroutine calls is not yet supported}}
array[0] = x
return array[0]
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}testBeginApplyActiveInoutArgument{{.*}} at (parameters=(0 1) results=(0))
// CHECK: [ACTIVE] %0 = argument of bb0 : $Array<Float>
// CHECK: [ACTIVE] %1 = argument of bb0 : $Float
// CHECK: [ACTIVE] %4 = alloc_stack $Array<Float>, var, name "array"
// CHECK: [ACTIVE] %5 = copy_value %0 : $Array<Float>
// CHECK: [USEFUL] %7 = integer_literal $Builtin.IntLiteral, 0
// CHECK: [USEFUL] %8 = metatype $@thin Int.Type
// CHECK: [NONE] // function_ref Int.init(_builtinIntegerLiteral:)
// CHECK: [USEFUL] %10 = apply %9(%7, %8) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int
// CHECK: [ACTIVE] %11 = begin_access [modify] [static] %4 : $*Array<Float>
// CHECK: [NONE] // function_ref Array.subscript.modify
// CHECK: [ACTIVE] (**%13**, %14) = begin_apply %12<Float>(%10, %11) : $@yield_once @convention(method) <τ_0_0> (Int, @inout Array<τ_0_0>) -> @yields @inout τ_0_0
// CHECK: [VARIED] (%13, **%14**) = begin_apply %12<Float>(%10, %11) : $@yield_once @convention(method) <τ_0_0> (Int, @inout Array<τ_0_0>) -> @yields @inout τ_0_0
// CHECK: [USEFUL] %18 = integer_literal $Builtin.IntLiteral, 0
// CHECK: [USEFUL] %19 = metatype $@thin Int.Type
// CHECK: [NONE] // function_ref Int.init(_builtinIntegerLiteral:)
// CHECK: [USEFUL] %21 = apply %20(%18, %19) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int
// CHECK: [ACTIVE] %22 = begin_access [read] [static] %4 : $*Array<Float>
// CHECK: [ACTIVE] %23 = load_borrow %22 : $*Array<Float>
// CHECK: [ACTIVE] %24 = alloc_stack $Float
// CHECK: [NONE] // function_ref Array.subscript.getter
// CHECK: [NONE] %26 = apply %25<Float>(%24, %21, %23) : $@convention(method) <τ_0_0> (Int, @guaranteed Array<τ_0_0>) -> @out τ_0_0
// CHECK: [ACTIVE] %27 = load [trivial] %24 : $*Float
// TF-1115: Test `begin_apply` active `inout` argument with non-active initial result.
// expected-error @+1 {{function is not differentiable}}
@differentiable
// expected-note @+1 {{when differentiating this function definition}}
func testBeginApplyActiveButInitiallyNonactiveInoutArgument(x: Float) -> Float {
// `var array` is initially non-active.
var array: [Float] = [0]
// Array subscript assignment below calls `Array.subscript.modify`.
// expected-note @+1 {{differentiation of coroutine calls is not yet supported}}
array[0] = x
return array[0]
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}testBeginApplyActiveButInitiallyNonactiveInoutArgument{{.*}} at (parameters=(0) results=(0))
// CHECK: [ACTIVE] %0 = argument of bb0 : $Float
// CHECK: [ACTIVE] %2 = alloc_stack $Array<Float>, var, name "array"
// CHECK: [USEFUL] %3 = integer_literal $Builtin.Word, 1
// CHECK: [NONE] // function_ref _allocateUninitializedArray<A>(_:)
// CHECK: [USEFUL] %5 = apply %4<Float>(%3) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer)
// CHECK: [USEFUL] (**%6**, %7) = destructure_tuple %5 : $(Array<Float>, Builtin.RawPointer)
// CHECK: [NONE] (%6, **%7**) = destructure_tuple %5 : $(Array<Float>, Builtin.RawPointer)
// CHECK: [USEFUL] %8 = pointer_to_address %7 : $Builtin.RawPointer to [strict] $*Float
// CHECK: [USEFUL] %9 = integer_literal $Builtin.IntLiteral, 0
// CHECK: [USEFUL] %10 = metatype $@thin Float.Type
// CHECK: [NONE] // function_ref Float.init(_builtinIntegerLiteral:)
// CHECK: [USEFUL] %12 = apply %11(%9, %10) : $@convention(method) (Builtin.IntLiteral, @thin Float.Type) -> Float
// CHECK: [NONE] // function_ref _finalizeUninitializedArray<A>(_:)
// CHECK: [USEFUL] %15 = apply %14<Float>(%6) : $@convention(thin) <τ_0_0> (@owned Array<τ_0_0>) -> @owned Array<τ_0_0>
// CHECK: [USEFUL] %17 = integer_literal $Builtin.IntLiteral, 0
// CHECK: [USEFUL] %18 = metatype $@thin Int.Type
// CHECK: [NONE] // function_ref Int.init(_builtinIntegerLiteral:)
// CHECK: [USEFUL] %20 = apply %19(%17, %18) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int
// CHECK: [ACTIVE] %21 = begin_access [modify] [static] %2 : $*Array<Float>
// CHECK: [NONE] // function_ref Array.subscript.modify
// CHECK: [ACTIVE] (**%23**, %24) = begin_apply %22<Float>(%20, %21) : $@yield_once @convention(method) <τ_0_0> (Int, @inout Array<τ_0_0>) -> @yields @inout τ_0_0
// CHECK: [VARIED] (%23, **%24**) = begin_apply %22<Float>(%20, %21) : $@yield_once @convention(method) <τ_0_0> (Int, @inout Array<τ_0_0>) -> @yields @inout τ_0_0
// CHECK: [USEFUL] %28 = integer_literal $Builtin.IntLiteral, 0
// CHECK: [USEFUL] %29 = metatype $@thin Int.Type
// CHECK: [NONE] // function_ref Int.init(_builtinIntegerLiteral:)
// CHECK: [USEFUL] %31 = apply %30(%28, %29) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int
// CHECK: [ACTIVE] %32 = begin_access [read] [static] %2 : $*Array<Float>
// CHECK: [ACTIVE] %33 = load_borrow %32 : $*Array<Float>
// CHECK: [ACTIVE] %34 = alloc_stack $Float
// CHECK: [NONE] // function_ref Array.subscript.getter
// CHECK: [NONE] %36 = apply %35<Float>(%34, %31, %33) : $@convention(method) <τ_0_0> (Int, @guaranteed Array<τ_0_0>) -> @out τ_0_0
// CHECK: [ACTIVE] %37 = load [trivial] %34 : $*Float
//===----------------------------------------------------------------------===//
// Class differentiation
//===----------------------------------------------------------------------===//
class C: Differentiable {
@differentiable
var float: Float
init(_ float: Float) {
self.float = float
}
@differentiable
func method(_ x: Float) -> Float {
x * float
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}1CC6methodyS2fF at (parameters=(0 1) results=(0))
// CHECK: bb0:
// CHECK: [ACTIVE] %0 = argument of bb0 : $Float
// CHECK: [ACTIVE] %1 = argument of bb0 : $C
// CHECK: [USEFUL] %4 = metatype $@thin Float.Type
// CHECK: [VARIED] %5 = class_method %1 : $C, #C.float!getter : (C) -> () -> Float, $@convention(method) (@guaranteed C) -> Float
// CHECK: [ACTIVE] %6 = apply %5(%1) : $@convention(method) (@guaranteed C) -> Float
// CHECK: [NONE] // function_ref static Float.* infix(_:_:)
// CHECK: %7 = function_ref @$sSf1moiyS2f_SftFZ : $@convention(method) (Float, Float, @thin Float.Type) -> Float
// CHECK: [ACTIVE] %8 = apply %7(%0, %6, %4) : $@convention(method) (Float, Float, @thin Float.Type) -> Float
}
// TF-1176: Test class property `modify` accessor.
@differentiable
func testClassModifyAccessor(_ c: inout C) {
c.float *= c.float
}
// FIXME(TF-1176): Some values are incorrectly not marked as active: `%16`, etc.
// CHECK-LABEL: [AD] Activity info for ${{.*}}testClassModifyAccessor{{.*}} at (parameters=(0) results=(0))
// CHECK: [ACTIVE] %0 = argument of bb0 : $*C
// CHECK: [NONE] %2 = metatype $@thin Float.Type
// CHECK: [ACTIVE] %3 = begin_access [read] [static] %0 : $*C
// CHECK: [VARIED] %4 = load [copy] %3 : $*C
// CHECK: [ACTIVE] %6 = begin_access [read] [static] %0 : $*C
// CHECK: [VARIED] %7 = load [copy] %6 : $*C
// CHECK: [VARIED] %9 = begin_borrow %7 : $C
// CHECK: [VARIED] %10 = class_method %9 : $C, #C.float!getter : (C) -> () -> Float, $@convention(method) (@guaranteed C) -> Float
// CHECK: [VARIED] %11 = apply %10(%9) : $@convention(method) (@guaranteed C) -> Float
// CHECK: [VARIED] %14 = begin_borrow %4 : $C
// CHECK: [VARIED] %15 = class_method %14 : $C, #C.float!modify : (C) -> () -> (), $@yield_once @convention(method) (@guaranteed C) -> @yields @inout Float
// CHECK: [VARIED] (**%16**, %17) = begin_apply %15(%14) : $@yield_once @convention(method) (@guaranteed C) -> @yields @inout Float
// CHECK: [VARIED] (%16, **%17**) = begin_apply %15(%14) : $@yield_once @convention(method) (@guaranteed C) -> @yields @inout Float
// CHECK: [NONE] // function_ref static Float.*= infix(_:_:)
// CHECK: [NONE] %19 = apply %18(%16, %11, %2) : $@convention(method) (@inout Float, Float, @thin Float.Type) -> ()
// CHECK: [NONE] %23 = tuple ()
//===----------------------------------------------------------------------===//
// Enum differentiation
//===----------------------------------------------------------------------===//
// expected-error @+1 {{function is not differentiable}}
@differentiable
// expected-note @+1 {{when differentiating this function definition}}
func testActiveOptional(_ x: Float) -> Float {
var maybe: Float? = 10
// expected-note @+1 {{expression is not differentiable}}
maybe = x
return maybe!
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}testActiveOptional{{.*}} at (parameters=(0) results=(0))
// CHECK: bb0:
// CHECK: [ACTIVE] %0 = argument of bb0 : $Float
// CHECK: [ACTIVE] %2 = alloc_stack $Optional<Float>, var, name "maybe"
// CHECK: [USEFUL] %3 = integer_literal $Builtin.IntLiteral, 10
// CHECK: [USEFUL] %4 = metatype $@thin Float.Type
// CHECK: [NONE] // function_ref Float.init(_builtinIntegerLiteral:)
// CHECK: [USEFUL] %6 = apply %5(%3, %4) : $@convention(method) (Builtin.IntLiteral, @thin Float.Type) -> Float
// CHECK: [USEFUL] %7 = enum $Optional<Float>, #Optional.some!enumelt, %6 : $Float
// CHECK: [ACTIVE] %9 = enum $Optional<Float>, #Optional.some!enumelt, %0 : $Float
// CHECK: [ACTIVE] %10 = begin_access [modify] [static] %2 : $*Optional<Float>
// CHECK: [ACTIVE] %13 = begin_access [read] [static] %2 : $*Optional<Float>
// CHECK: [ACTIVE] %14 = load [trivial] %13 : $*Optional<Float>
// CHECK: bb1:
// CHECK: [NONE] // function_ref _diagnoseUnexpectedNilOptional(_filenameStart:_filenameLength:_filenameIsASCII:_line:_isImplicitUnwrap:)
// CHECK: [NONE] %24 = apply %23(%17, %18, %19, %20, %22) : $@convention(thin) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, Builtin.Word, Builtin.Int1) -> ()
// CHECK: bb2:
// CHECK: [ACTIVE] %26 = argument of bb2 : $Float
enum DirectEnum: Differentiable & AdditiveArithmetic {
case case0
case case1(Float)
case case2(Float, Float)
typealias TangentVector = Self
static var zero: Self { fatalError() }
static func +(_ lhs: Self, _ rhs: Self) -> Self { fatalError() }
static func -(_ lhs: Self, _ rhs: Self) -> Self { fatalError() }
}
// expected-error @+1 {{function is not differentiable}}
@differentiable(wrt: e)
// expected-note @+2 {{when differentiating this function definition}}
// expected-note @+1 {{differentiating enum values is not yet supported}}
func testActiveEnumValue(_ e: DirectEnum, _ x: Float) -> Float {
switch e {
case .case0: return x
case let .case1(y1): return y1
case let .case2(y1, y2): return y1 + y2
}
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}testActiveEnumValue{{.*}} at (parameters=(0) results=(0))
// CHECK: bb0:
// CHECK: [ACTIVE] %0 = argument of bb0 : $DirectEnum
// CHECK: [USEFUL] %1 = argument of bb0 : $Float
// CHECK: bb1:
// CHECK: bb2:
// CHECK: [ACTIVE] %6 = argument of bb2 : $Float
// CHECK: bb3:
// CHECK: [ACTIVE] %9 = argument of bb3 : $(Float, Float)
// CHECK: [ACTIVE] (**%10**, %11) = destructure_tuple %9 : $(Float, Float)
// CHECK: [ACTIVE] (%10, **%11**) = destructure_tuple %9 : $(Float, Float)
// CHECK: [USEFUL] %14 = metatype $@thin Float.Type
// CHECK: [NONE] // function_ref static Float.+ infix(_:_:)
// CHECK: %15 = function_ref @$sSf1poiyS2f_SftFZ : $@convention(method) (Float, Float, @thin Float.Type) -> Float
// CHECK: [ACTIVE] %16 = apply %15(%10, %11, %14) : $@convention(method) (Float, Float, @thin Float.Type) -> Float
// CHECK: bb4:
// CHECK: [ACTIVE] %18 = argument of bb4 : $Float
enum IndirectEnum<T: Differentiable>: Differentiable & AdditiveArithmetic {
case case1(T)
case case2(Float, T)
typealias TangentVector = Self
static func ==(_ lhs: Self, _ rhs: Self) -> Bool { fatalError() }
static var zero: Self { fatalError() }
static func +(_ lhs: Self, _ rhs: Self) -> Self { fatalError() }
static func -(_ lhs: Self, _ rhs: Self) -> Self { fatalError() }
}
// expected-error @+1 {{function is not differentiable}}
@differentiable(wrt: e)
// expected-note @+2 {{when differentiating this function definition}}
// expected-note @+1 {{differentiating enum values is not yet supported}}
func testActiveEnumAddr<T>(_ e: IndirectEnum<T>) -> T {
switch e {
case let .case1(y1): return y1
case let .case2(_, y2): return y2
}
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}testActiveEnumAddr{{.*}} at (parameters=(0) results=(0))
// CHECK: bb0:
// CHECK: [ACTIVE] %0 = argument of bb0 : $*T
// CHECK: [ACTIVE] %1 = argument of bb0 : $*IndirectEnum<T>
// CHECK: [ACTIVE] %3 = alloc_stack $IndirectEnum<T>
// CHECK: bb1:
// CHECK: [ACTIVE] %6 = unchecked_take_enum_data_addr %3 : $*IndirectEnum<T>, #IndirectEnum.case1!enumelt
// CHECK: [ACTIVE] %7 = alloc_stack $T, let, name "y1"
// CHECK: bb2:
// CHECK: [ACTIVE] {{.*}} = unchecked_take_enum_data_addr {{.*}} : $*IndirectEnum<T>, #IndirectEnum.case2!enumelt
// CHECK: [ACTIVE] {{.*}} = tuple_element_addr {{.*}} : $*(Float, T), 0
// CHECK: [VARIED] {{.*}} = load [trivial] {{.*}} : $*Float
// CHECK: [ACTIVE] {{.*}} = tuple_element_addr {{.*}} : $*(Float, T), 1
// CHECK: [ACTIVE] {{.*}} = alloc_stack $T, let, name "y2"
// CHECK: bb3:
// CHECK: [NONE] {{.*}} = tuple ()
| apache-2.0 | 15101e793f5e82043268aede17a621d7 | 52.096512 | 174 | 0.611896 | 3.090558 | false | false | false | false |
sztoth/PodcastChapters | PodcastChapters/Utilities/Notifications/AppNotificationCenter.swift | 1 | 2704 | //
// AppNotificationCenter.swift
// PodcastChapters
//
// Created by Szabolcs Toth on 2016. 02. 13..
// Copyright © 2016. Szabolcs Toth. All rights reserved.
//
import Foundation
protocol AppNotificationCenterType {
func clearAllNotifications()
func deliver(_ notification: AppNotification)
}
class AppNotificationCenter: NSObject {
fileprivate let userNotificationCenter: NSUserNotificationCenter
fileprivate var notifications = [AppNotification]()
fileprivate var timer: Timer?
init(userNotificationCenter: NSUserNotificationCenter = NSUserNotificationCenter.default) {
self.userNotificationCenter = userNotificationCenter
super.init()
self.userNotificationCenter.delegate = self
}
}
// MARK: - Notification related
extension AppNotificationCenter: AppNotificationCenterType {
func clearAllNotifications() {
timer = nil
userNotificationCenter.removeAllDeliveredNotifications()
notifications.removeAll()
}
func deliver(_ notification: AppNotification) {
clearAllNotifications()
notifications.append(notification)
let userNotification = NSUserNotification(appNotification: notification)
userNotificationCenter.deliver(userNotification)
timer = Timer(interval: Constant.refreshInterval) { [weak self] _ in
self?.clearAllNotifications()
}
}
}
// MARK: - Private
fileprivate extension AppNotificationCenter {
func performActionWithIdentifier(_ identifier: String) {
guard let notification = notifications.filter({ $0.identifier == identifier }).first else { return }
notification.actionHandler()
clearNotificationWithIdentifier(identifier)
}
func clearNotificationWithIdentifier(_ identifier: String) {
guard let index = notifications.index(where: { $0.identifier == identifier }) else { return }
notifications.remove(at: index)
}
}
// MARK: - NSUserNotificationCenterDelegate
extension AppNotificationCenter: NSUserNotificationCenterDelegate {
func userNotificationCenter(_ center: NSUserNotificationCenter, shouldPresent notification: NSUserNotification) -> Bool {
return true
}
func userNotificationCenter(_ center: NSUserNotificationCenter, didActivate notification: NSUserNotification) {
guard let identifier = notification.identifier else { return }
if notification.activationType == .actionButtonClicked {
performActionWithIdentifier(identifier)
}
}
}
// MARK: - Constant
fileprivate extension AppNotificationCenter {
enum Constant {
static let refreshInterval: TimeInterval = 120.0
}
}
| mit | bf379c00fc45139a62c1a3b613302334 | 28.380435 | 125 | 0.7229 | 5.714588 | false | false | false | false |
practicalswift/swift | test/Constraints/diagnostics.swift | 1 | 56034 | // RUN: %target-typecheck-verify-swift
protocol P {
associatedtype SomeType
}
protocol P2 {
func wonka()
}
extension Int : P {
typealias SomeType = Int
}
extension Double : P {
typealias SomeType = Double
}
func f0(_ x: Int,
_ y: Float) { }
func f1(_: @escaping (Int, Float) -> Int) { }
func f2(_: (_: (Int) -> Int)) -> Int {}
func f3(_: @escaping (_: @escaping (Int) -> Float) -> Int) {}
func f4(_ x: Int) -> Int { }
func f5<T : P2>(_ : T) { }
func f6<T : P, U : P>(_ t: T, _ u: U) where T.SomeType == U.SomeType {}
var i : Int
var d : Double
// Check the various forms of diagnostics the type checker can emit.
// Tuple size mismatch.
f1(
f4 // expected-error {{cannot convert value of type '(Int) -> Int' to expected argument type '(Int, Float) -> Int'}}
)
// Tuple element unused.
f0(i, i,
i) // expected-error{{extra argument in call}}
// Position mismatch
f5(f4) // expected-error {{argument type '(Int) -> Int' does not conform to expected type 'P2'}}
// Tuple element not convertible.
f0(i,
d // expected-error {{cannot convert value of type 'Double' to expected argument type 'Float'}}
)
// Function result not a subtype.
f1(
f0 // expected-error {{cannot convert value of type '(Int, Float) -> ()' to expected argument type '(Int, Float) -> Int'}}
)
f3(
f2 // expected-error {{cannot convert value of type '(@escaping ((Int) -> Int)) -> Int' to expected argument type '(@escaping (Int) -> Float) -> Int'}}
)
f4(i, d) // expected-error {{extra argument in call}}
// Missing member.
i.wobble() // expected-error{{value of type 'Int' has no member 'wobble'}}
// Generic member does not conform.
extension Int {
func wibble<T: P2>(_ x: T, _ y: T) -> T { return x }
func wubble<T>(_ x: (Int) -> T) -> T { return x(self) }
}
i.wibble(3, 4) // expected-error {{argument type 'Int' does not conform to expected type 'P2'}}
// Generic member args correct, but return type doesn't match.
struct A : P2 {
func wonka() {}
}
let a = A()
for j in i.wibble(a, a) { // expected-error {{type 'A' does not conform to protocol 'Sequence'}}
}
// Generic as part of function/tuple types
func f6<T:P2>(_ g: (Void) -> T) -> (c: Int, i: T) { // expected-warning {{when calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'?}} {{20-26=()}}
return (c: 0, i: g(()))
}
func f7() -> (c: Int, v: A) {
let g: (Void) -> A = { _ in return A() } // expected-warning {{when calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'?}} {{10-16=()}}
return f6(g) // expected-error {{cannot convert return expression of type '(c: Int, i: A)' to return type '(c: Int, v: A)'}}
}
func f8<T:P2>(_ n: T, _ f: @escaping (T) -> T) {}
f8(3, f4) // expected-error {{argument type 'Int' does not conform to expected type 'P2'}}
typealias Tup = (Int, Double)
func f9(_ x: Tup) -> Tup { return x }
f8((1,2.0), f9) // expected-error {{argument type 'Tup' (aka '(Int, Double)') does not conform to expected type 'P2'}}
// <rdar://problem/19658691> QoI: Incorrect diagnostic for calling nonexistent members on literals
1.doesntExist(0) // expected-error {{value of type 'Int' has no member 'doesntExist'}}
[1, 2, 3].doesntExist(0) // expected-error {{value of type '[Int]' has no member 'doesntExist'}}
"awfawf".doesntExist(0) // expected-error {{value of type 'String' has no member 'doesntExist'}}
// Does not conform to protocol.
f5(i) // expected-error {{argument type 'Int' does not conform to expected type 'P2'}}
// Make sure we don't leave open existentials when diagnosing.
// <rdar://problem/20598568>
func pancakes(_ p: P2) {
f4(p.wonka) // expected-error{{cannot convert value of type '() -> ()' to expected argument type 'Int'}}
f4(p.wonka()) // expected-error{{cannot convert value of type '()' to expected argument type 'Int'}}
}
protocol Shoes {
static func select(_ subject: Shoes) -> Self
}
// Here the opaque value has type (metatype_type (archetype_type ... ))
func f(_ x: Shoes, asType t: Shoes.Type) {
return t.select(x) // expected-error{{unexpected non-void return value in void function}}
}
precedencegroup Starry {
associativity: left
higherThan: MultiplicationPrecedence
}
infix operator **** : Starry
func ****(_: Int, _: String) { }
i **** i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}}
infix operator ***~ : Starry
func ***~(_: Int, _: String) { }
i ***~ i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}}
@available(*, unavailable, message: "call the 'map()' method on the sequence")
public func myMap<C : Collection, T>( // expected-note {{'myMap' has been explicitly marked unavailable here}}
_ source: C, _ transform: (C.Iterator.Element) -> T
) -> [T] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, message: "call the 'map()' method on the optional value")
public func myMap<T, U>(_ x: T?, _ f: (T) -> U) -> U? {
fatalError("unavailable function can't be called")
}
// <rdar://problem/20142523>
func rdar20142523() {
myMap(0..<10, { x in // expected-error{{'myMap' is unavailable: call the 'map()' method on the sequence}}
()
return x
})
}
// <rdar://problem/21080030> Bad diagnostic for invalid method call in boolean expression: (_, ExpressibleByIntegerLiteral)' is not convertible to 'ExpressibleByIntegerLiteral
func rdar21080030() {
var s = "Hello"
// SR-7599: This should be `cannot_call_non_function_value`
if s.count() == 0 {} // expected-error{{cannot invoke 'count' with no arguments}}
}
// <rdar://problem/21248136> QoI: problem with return type inference mis-diagnosed as invalid arguments
func r21248136<T>() -> T { preconditionFailure() } // expected-note 2 {{in call to function 'r21248136()'}}
r21248136() // expected-error {{generic parameter 'T' could not be inferred}}
let _ = r21248136() // expected-error {{generic parameter 'T' could not be inferred}}
// <rdar://problem/16375647> QoI: Uncallable funcs should be compile time errors
func perform<T>() {} // expected-error {{generic parameter 'T' is not used in function signature}}
// <rdar://problem/17080659> Error Message QOI - wrong return type in an overload
func recArea(_ h: Int, w : Int) {
return h * w // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/17224804> QoI: Error In Ternary Condition is Wrong
func r17224804(_ monthNumber : Int) {
// expected-error @+2 {{binary operator '+' cannot be applied to operands of type 'String' and 'Int'}}
// expected-note @+1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}}
let monthString = (monthNumber <= 9) ? ("0" + monthNumber) : String(monthNumber)
}
// <rdar://problem/17020197> QoI: Operand of postfix '!' should have optional type; type is 'Int?'
func r17020197(_ x : Int?, y : Int) {
if x! { } // expected-error {{'Int' is not convertible to 'Bool'}}
// <rdar://problem/12939553> QoI: diagnostic for using an integer in a condition is utterly terrible
if y {} // expected-error {{'Int' is not convertible to 'Bool'}}
}
// <rdar://problem/20714480> QoI: Boolean expr not treated as Bool type when function return type is different
func validateSaveButton(_ text: String) {
return (text.count > 0) ? true : false // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/20201968> QoI: poor diagnostic when calling a class method via a metatype
class r20201968C {
func blah() {
r20201968C.blah() // expected-error {{instance member 'blah' cannot be used on type 'r20201968C'; did you mean to use a value of this type instead?}}
}
}
// <rdar://problem/21459429> QoI: Poor compilation error calling assert
func r21459429(_ a : Int) {
assert(a != nil, "ASSERT COMPILATION ERROR")
// expected-warning @-1 {{comparing non-optional value of type 'Int' to 'nil' always returns true}}
}
// <rdar://problem/21362748> [WWDC Lab] QoI: cannot subscript a value of type '[Int]?' with an index of type 'Int'
struct StructWithOptionalArray {
var array: [Int]?
}
func testStructWithOptionalArray(_ foo: StructWithOptionalArray) -> Int {
return foo.array[0] // expected-error {{value of optional type '[Int]?' must be unwrapped to refer to member 'subscript' of wrapped base type '[Int]'}}
// expected-note@-1{{chain the optional using '?' to access member 'subscript' only for non-'nil' base values}}{{19-19=?}}
// expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}{{19-19=!}}
}
// <rdar://problem/19774755> Incorrect diagnostic for unwrapping non-optional bridged types
var invalidForceUnwrap = Int()! // expected-error {{cannot force unwrap value of non-optional type 'Int'}} {{31-32=}}
// <rdar://problem/20905802> Swift using incorrect diagnostic sometimes on String().asdf
String().asdf // expected-error {{value of type 'String' has no member 'asdf'}}
// <rdar://problem/21553065> Spurious diagnostic: '_' can only appear in a pattern or on the left side of an assignment
protocol r21553065Protocol {}
class r21553065Class<T : AnyObject> {} // expected-note{{requirement specified as 'T' : 'AnyObject'}}
_ = r21553065Class<r21553065Protocol>() // expected-error {{'r21553065Class' requires that 'r21553065Protocol' be a class type}}
// Type variables not getting erased with nested closures
struct Toe {
let toenail: Nail // expected-error {{use of undeclared type 'Nail'}}
func clip() {
toenail.inspect { x in
toenail.inspect { y in }
}
}
}
// <rdar://problem/21447318> dot'ing through a partially applied member produces poor diagnostic
class r21447318 {
var x = 42
func doThing() -> r21447318 { return self }
}
func test21447318(_ a : r21447318, b : () -> r21447318) {
a.doThing.doThing() // expected-error {{method 'doThing' was used as a property; add () to call it}} {{12-12=()}}
b.doThing() // expected-error {{function 'b' was used as a property; add () to call it}} {{4-4=()}}
}
// <rdar://problem/20409366> Diagnostics for init calls should print the class name
class r20409366C {
init(a : Int) {}
init?(a : r20409366C) {
let req = r20409366C(a: 42)? // expected-error {{cannot use optional chaining on non-optional value of type 'r20409366C'}} {{32-33=}}
}
}
// <rdar://problem/18800223> QoI: wrong compiler error when swift ternary operator branches don't match
func r18800223(_ i : Int) {
// 20099385
_ = i == 0 ? "" : i // expected-error {{result values in '? :' expression have mismatching types 'String' and 'Int'}}
// 19648528
_ = true ? [i] : i // expected-error {{result values in '? :' expression have mismatching types '[Int]' and 'Int'}}
var buttonTextColor: String?
_ = (buttonTextColor != nil) ? 42 : {$0}; // expected-error {{type of expression is ambiguous without more context}}
}
// <rdar://problem/21883806> Bogus "'_' can only appear in a pattern or on the left side of an assignment" is back
_ = { $0 } // expected-error {{unable to infer closure type in the current context}}
_ = 4() // expected-error {{cannot call value of non-function type 'Int'}}{{6-8=}}
_ = 4(1) // expected-error {{cannot call value of non-function type 'Int'}}
// <rdar://problem/21784170> Incongruous `unexpected trailing closure` error in `init` function which is cast and called without trailing closure.
func rdar21784170() {
let initial = (1.0 as Double, 2.0 as Double)
(Array.init as (Double...) -> Array<Double>)(initial as (Double, Double)) // expected-error {{cannot convert value of type '(Double, Double)' to expected argument type 'Double'}}
}
// <rdar://problem/21829141> BOGUS: unexpected trailing closure
func expect<T, U>(_: T) -> (U.Type) -> Int { return { a in 0 } }
func expect<T, U>(_: T, _: Int = 1) -> (U.Type) -> String { return { a in "String" } }
let expectType1 = expect(Optional(3))(Optional<Int>.self)
let expectType1Check: Int = expectType1
// <rdar://problem/19804707> Swift Enum Scoping Oddity
func rdar19804707() {
enum Op {
case BinaryOperator((Double, Double) -> Double)
}
var knownOps : Op
knownOps = Op.BinaryOperator({$1 - $0})
knownOps = Op.BinaryOperator(){$1 - $0}
knownOps = Op.BinaryOperator{$1 - $0}
knownOps = .BinaryOperator({$1 - $0})
// rdar://19804707 - trailing closures for contextual member references.
knownOps = .BinaryOperator(){$1 - $0}
knownOps = .BinaryOperator{$1 - $0}
_ = knownOps
}
func f7(_ a: Int) -> (_ b: Int) -> Int {
return { b in a+b }
}
_ = f7(1)(1)
f7(1.0)(2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f7(1)(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f7(1)(b: 1.0) // expected-error{{extraneous argument label 'b:' in call}}
let f8 = f7(2)
_ = f8(1)
f8(10) // expected-warning {{result of call to function returning 'Int' is unused}}
f8(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f8(b: 1.0) // expected-error {{extraneous argument label 'b:' in call}}
class CurriedClass {
func method1() {}
func method2(_ a: Int) -> (_ b : Int) -> () { return { b in () } }
func method3(_ a: Int, b : Int) {} // expected-note 5 {{'method3(_:b:)' declared here}}
}
let c = CurriedClass()
_ = c.method1
c.method1(1) // expected-error {{argument passed to call that takes no arguments}}
_ = c.method2(1)
_ = c.method2(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1)(2)
c.method2(1)(c: 2) // expected-error {{extraneous argument label 'c:' in call}}
c.method2(1)(c: 2.0) // expected-error {{extraneous argument label 'c:' in call}}
c.method2(1)(2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1.0)(2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1.0)(2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method1(c)()
_ = CurriedClass.method1(c)
CurriedClass.method1(c)(1) // expected-error {{argument passed to call that takes no arguments}}
CurriedClass.method1(2.0)(1) // expected-error {{instance member 'method1' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
CurriedClass.method2(c)(32)(b: 1) // expected-error{{extraneous argument label 'b:' in call}}
_ = CurriedClass.method2(c)
_ = CurriedClass.method2(c)(32)
_ = CurriedClass.method2(1,2) // expected-error {{instance member 'method2' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
CurriedClass.method2(c)(1.0)(b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method2(c)(1)(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method2(c)(2)(c: 1.0) // expected-error {{extraneous argument label 'c:'}}
CurriedClass.method3(c)(32, b: 1)
_ = CurriedClass.method3(c)
_ = CurriedClass.method3(c)(1, 2) // expected-error {{missing argument label 'b:' in call}} {{32-32=b: }}
_ = CurriedClass.method3(c)(1, b: 2)(32) // expected-error {{cannot call value of non-function type '()'}}
_ = CurriedClass.method3(1, 2) // expected-error {{instance member 'method3' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
CurriedClass.method3(c)(1.0, b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method3(c)(1) // expected-error {{missing argument for parameter 'b' in call}}
CurriedClass.method3(c)(c: 1.0) // expected-error {{missing argument for parameter #1 in call}}
extension CurriedClass {
func f() {
method3(1, b: 2)
method3() // expected-error {{missing argument for parameter #1 in call}}
method3(42) // expected-error {{missing argument for parameter 'b' in call}}
method3(self) // expected-error {{missing argument for parameter 'b' in call}}
}
}
extension CurriedClass {
func m1(_ a : Int, b : Int) {}
func m2(_ a : Int) {}
}
// <rdar://problem/23718816> QoI: "Extra argument" error when accidentally currying a method
CurriedClass.m1(2, b: 42) // expected-error {{instance member 'm1' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
// <rdar://problem/22108559> QoI: Confusing error message when calling an instance method as a class method
CurriedClass.m2(12) // expected-error {{instance member 'm2' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
// <rdar://problem/20491794> Error message does not tell me what the problem is
enum Color {
case Red
case Unknown(description: String)
static func rainbow() -> Color {}
static func overload(a : Int) -> Color {}
static func overload(b : Int) -> Color {}
static func frob(_ a : Int, b : inout Int) -> Color {}
static var svar: Color { return .Red }
}
// FIXME: This used to be better: "'map' produces '[T]', not the expected contextual result type '(Int, Color)'"
let _: (Int, Color) = [1,2].map({ ($0, .Unknown("")) }) // expected-error {{expression type '((Int) throws -> _) throws -> [_]' is ambiguous without more context}}
let _: [(Int, Color)] = [1,2].map({ ($0, .Unknown("")) })// expected-error {{missing argument label 'description:' in call}}
let _: [Color] = [1,2].map { _ in .Unknown("") }// expected-error {{missing argument label 'description:' in call}} {{44-44=description: }}
let _: (Int) -> (Int, Color) = { ($0, .Unknown("")) } // expected-error {{missing argument label 'description:' in call}} {{48-48=description: }}
let _: Color = .Unknown("") // expected-error {{missing argument label 'description:' in call}} {{25-25=description: }}
let _: Color = .Unknown // expected-error {{member 'Unknown' expects argument of type '(description: String)'}}
let _: Color = .Unknown(42) // expected-error {{missing argument label 'description:' in call}}
let _ : Color = .rainbow(42) // expected-error {{argument passed to call that takes no arguments}}
let _ : (Int, Float) = (42.0, 12) // expected-error {{cannot convert value of type 'Double' to specified type 'Int'}}
let _ : Color = .rainbow // expected-error {{member 'rainbow' is a function; did you mean to call it?}} {{25-25=()}}
let _: Color = .overload(a : 1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
let _: Color = .overload(1.0) // expected-error {{ambiguous reference to member 'overload'}}
// expected-note @-1 {{overloads for 'overload' exist with these partially matching parameter lists: (a: Int), (b: Int)}}
let _: Color = .overload(1) // expected-error {{ambiguous reference to member 'overload'}}
// expected-note @-1 {{overloads for 'overload' exist with these partially matching parameter lists: (a: Int), (b: Int)}}
let _: Color = .frob(1.0, &i) // expected-error {{missing argument label 'b:' in call}}
let _: Color = .frob(1.0, b: &i) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
let _: Color = .frob(1, i) // expected-error {{missing argument label 'b:' in call}}
// expected-error@-1 {{passing value of type 'Int' to an inout parameter requires explicit '&'}}
let _: Color = .frob(1, b: i) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{28-28=&}}
let _: Color = .frob(1, &d) // expected-error {{missing argument label 'b:' in call}}
let _: Color = .frob(1, b: &d) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
var someColor : Color = .red // expected-error {{enum type 'Color' has no case 'red'; did you mean 'Red'}}
someColor = .red // expected-error {{enum type 'Color' has no case 'red'; did you mean 'Red'}}
someColor = .svar() // expected-error {{static property 'svar' is not a function}}
someColor = .svar(1) // expected-error {{static property 'svar' is not a function}}
func testTypeSugar(_ a : Int) {
typealias Stride = Int
let x = Stride(a)
x+"foo" // expected-error {{binary operator '+' cannot be applied to operands of type 'Stride' (aka 'Int') and 'String'}}
// expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}}
}
// <rdar://problem/21974772> SegFault in FailureDiagnosis::visitInOutExpr
func r21974772(_ y : Int) {
let x = &(1.0 + y) // expected-error {{use of extraneous '&'}}
}
// <rdar://problem/22020088> QoI: missing member diagnostic on optional gives worse error message than existential/bound generic/etc
protocol r22020088P {}
func r22020088Foo<T>(_ t: T) {}
func r22020088bar(_ p: r22020088P?) {
r22020088Foo(p.fdafs) // expected-error {{value of type 'r22020088P?' has no member 'fdafs'}}
}
// <rdar://problem/22288575> QoI: poor diagnostic involving closure, bad parameter label, and mismatch return type
func f(_ arguments: [String]) -> [ArraySlice<String>] {
return arguments.split(maxSplits: 1, omittingEmptySubsequences: false, whereSeparator: { $0 == "--" })
}
struct AOpts : OptionSet {
let rawValue : Int
}
class B {
func function(_ x : Int8, a : AOpts) {}
func f2(_ a : AOpts) {}
static func f1(_ a : AOpts) {}
}
class GenClass<T> {}
struct GenStruct<T> {}
enum GenEnum<T> {}
func test(_ a : B) {
B.f1(nil) // expected-error {{'nil' is not compatible with expected argument type 'AOpts'}}
a.function(42, a: nil) // expected-error {{'nil' is not compatible with expected argument type 'AOpts'}}
a.function(42, nil) // expected-error {{missing argument label 'a:' in call}}
a.f2(nil) // expected-error {{'nil' is not compatible with expected argument type 'AOpts'}}
func foo1(_ arg: Bool) -> Int {return nil}
func foo2<T>(_ arg: T) -> GenClass<T> {return nil}
func foo3<T>(_ arg: T) -> GenStruct<T> {return nil}
func foo4<T>(_ arg: T) -> GenEnum<T> {return nil}
// expected-error@-4 {{'nil' is incompatible with return type 'Int'}}
// expected-error@-4 {{'nil' is incompatible with return type 'GenClass<T>'}}
// expected-error@-4 {{'nil' is incompatible with return type 'GenStruct<T>'}}
// expected-error@-4 {{'nil' is incompatible with return type 'GenEnum<T>'}}
let clsr1: () -> Int = {return nil}
let clsr2: () -> GenClass<Bool> = {return nil}
let clsr3: () -> GenStruct<String> = {return nil}
let clsr4: () -> GenEnum<Double?> = {return nil}
// expected-error@-4 {{'nil' is not compatible with closure result type 'Int'}}
// expected-error@-4 {{'nil' is not compatible with closure result type 'GenClass<Bool>'}}
// expected-error@-4 {{'nil' is not compatible with closure result type 'GenStruct<String>'}}
// expected-error@-4 {{'nil' is not compatible with closure result type 'GenEnum<Double?>'}}
var number = 0
var genClassBool = GenClass<Bool>()
var funcFoo1 = foo1
number = nil
genClassBool = nil
funcFoo1 = nil
// expected-error@-3 {{'nil' cannot be assigned to type 'Int'}}
// expected-error@-3 {{'nil' cannot be assigned to type 'GenClass<Bool>'}}
// expected-error@-3 {{'nil' cannot be assigned to type '(Bool) -> Int'}}
}
// <rdar://problem/21684487> QoI: invalid operator use inside a closure reported as a problem with the closure
typealias MyClosure = ([Int]) -> Bool
func r21684487() {
var closures = Array<MyClosure>()
let testClosure = {(list: [Int]) -> Bool in return true}
let closureIndex = closures.index{$0 === testClosure} // expected-error {{cannot check reference equality of functions;}}
}
// <rdar://problem/18397777> QoI: special case comparisons with nil
func r18397777(_ d : r21447318?) {
let c = r21447318()
if c != nil { // expected-warning {{comparing non-optional value of type 'r21447318' to 'nil' always returns true}}
}
if d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '!= nil' instead}} {{6-6=(}} {{7-7= != nil)}}
}
if !d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '!= nil' instead}} {{7-7=(}} {{8-8= != nil)}}
}
if !Optional(c) { // expected-error {{optional type 'Optional<r21447318>' cannot be used as a boolean; test for '!= nil' instead}} {{7-7=(}} {{18-18= != nil)}}
}
}
// <rdar://problem/22255907> QoI: bad diagnostic if spurious & in argument list
func r22255907_1<T>(_ a : T, b : Int) {}
func r22255907_2<T>(_ x : Int, a : T, b: Int) {}
func reachabilityForInternetConnection() {
var variable: Int = 42
r22255907_1(&variable, b: 2.1) // expected-error {{'&' used with non-inout argument of type 'Int'}} {{15-16=}}
r22255907_2(1, a: &variable, b: 2.1)// expected-error {{'&' used with non-inout argument of type 'Int'}} {{21-22=}}
}
// <rdar://problem/21601687> QoI: Using "=" instead of "==" in if statement leads to incorrect error message
if i = 6 { } // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{6-7===}}
_ = (i = 6) ? 42 : 57 // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{8-9===}}
// <rdar://problem/22263468> QoI: Not producing specific argument conversion diagnostic for tuple init
func r22263468(_ a : String?) {
typealias MyTuple = (Int, String)
_ = MyTuple(42, a) // expected-error {{value of optional type 'String?' must be unwrapped to a value of type 'String'}}
// expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}}
// expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}
}
// rdar://22470302 - Crash with parenthesized call result.
class r22470302Class {
func f() {}
}
func r22470302(_ c: r22470302Class) {
print((c.f)(c)) // expected-error {{argument passed to call that takes no arguments}}
}
// <rdar://problem/21928143> QoI: Pointfree reference to generic initializer in generic context does not compile
extension String {
@available(*, unavailable, message: "calling this is unwise")
func unavail<T : Sequence> // expected-note 2 {{'unavail' has been explicitly marked unavailable here}}
(_ a : T) -> String where T.Iterator.Element == String {}
}
extension Array {
func g() -> String {
return "foo".unavail([""]) // expected-error {{'unavail' is unavailable: calling this is unwise}}
}
func h() -> String {
return "foo".unavail([0]) // expected-error {{'unavail' is unavailable: calling this is unwise}}
}
}
// <rdar://problem/22519983> QoI: Weird error when failing to infer archetype
func safeAssign<T: RawRepresentable>(_ lhs: inout T) -> Bool {}
// expected-note @-1 {{in call to function 'safeAssign'}}
let a = safeAssign // expected-error {{generic parameter 'T' could not be inferred}}
// <rdar://problem/21692808> QoI: Incorrect 'add ()' fixit with trailing closure
struct Radar21692808<Element> {
init(count: Int, value: Element) {}
}
func radar21692808() -> Radar21692808<Int> {
return Radar21692808<Int>(count: 1) { // expected-error {{cannot invoke initializer for type 'Radar21692808<Int>' with an argument list of type '(count: Int, () -> Int)'}}
// expected-note @-1 {{expected an argument list of type '(count: Int, value: Element)'}}
return 1
}
}
// <rdar://problem/17557899> - This shouldn't suggest calling with ().
func someOtherFunction() {}
func someFunction() -> () {
// Producing an error suggesting that this
return someOtherFunction // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/23560128> QoI: trying to mutate an optional dictionary result produces bogus diagnostic
func r23560128() {
var a : (Int,Int)?
a.0 = 42 // expected-error{{value of optional type '(Int, Int)?' must be unwrapped to refer to member '0' of wrapped base type '(Int, Int)'}}
// expected-note@-1{{chain the optional }}
// expected-note@-2{{force-unwrap using '!'}}
}
// <rdar://problem/21890157> QoI: wrong error message when accessing properties on optional structs without unwrapping
struct ExampleStruct21890157 {
var property = "property"
}
var example21890157: ExampleStruct21890157?
example21890157.property = "confusing" // expected-error {{value of optional type 'ExampleStruct21890157?' must be unwrapped to refer to member 'property' of wrapped base type 'ExampleStruct21890157'}}
// expected-note@-1{{chain the optional }}
// expected-note@-2{{force-unwrap using '!'}}
struct UnaryOp {}
_ = -UnaryOp() // expected-error {{unary operator '-' cannot be applied to an operand of type 'UnaryOp'}}
// expected-note@-1 {{overloads for '-' exist with these partially matching parameter lists: (Double), (Float)}}
// <rdar://problem/23433271> Swift compiler segfault in failure diagnosis
func f23433271(_ x : UnsafePointer<Int>) {}
func segfault23433271(_ a : UnsafeMutableRawPointer) {
f23433271(a[0]) // expected-error {{value of type 'UnsafeMutableRawPointer' has no subscripts}}
}
// <rdar://problem/23272739> Poor diagnostic due to contextual constraint
func r23272739(_ contentType: String) {
let actualAcceptableContentTypes: Set<String> = []
return actualAcceptableContentTypes.contains(contentType) // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/23641896> QoI: Strings in Swift cannot be indexed directly with integer offsets
func r23641896() {
var g = "Hello World"
g.replaceSubrange(0...2, with: "ce") // expected-error {{cannot convert value of type 'ClosedRange<Int>' to expected argument type 'Range<String.Index>'}}
_ = g[12] // expected-error {{'subscript(_:)' is unavailable: cannot subscript String with an Int, see the documentation comment for discussion}}
}
// <rdar://problem/23718859> QoI: Incorrectly flattening ((Int,Int)) argument list to (Int,Int) when printing note
func test17875634() {
var match: [(Int, Int)] = []
var row = 1
var col = 2
match.append(row, col) // expected-error {{instance method 'append' expects a single parameter of type '(Int, Int)'}} {{16-16=(}} {{24-24=)}}
}
// <https://github.com/apple/swift/pull/1205> Improved diagnostics for enums with associated values
enum AssocTest {
case one(Int)
}
if AssocTest.one(1) == AssocTest.one(1) {} // expected-error{{binary operator '==' cannot be applied to two 'AssocTest' operands}}
// expected-note @-1 {{binary operator '==' cannot be synthesized for enums with associated values}}
// <rdar://problem/24251022> Swift 2: Bad Diagnostic Message When Adding Different Integer Types
func r24251022() {
var a = 1
var b: UInt32 = 2
_ = a + b // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'UInt32'}} expected-note {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (UInt32, UInt32)}}
a += a + // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'UInt32'}} expected-note {{overloads for '+' exist with these partially matching parameter lists:}}
b
a += b // expected-error {{binary operator '+=' cannot be applied to operands of type 'Int' and 'UInt32'}} expected-note {{overloads for '+=' exist with these partially matching parameter lists: (inout Int, Int), (inout UInt32, UInt32)}}
}
func overloadSetResultType(_ a : Int, b : Int) -> Int {
// https://twitter.com/_jlfischer/status/712337382175952896
// TODO: <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands"
return a == b && 1 == 2 // expected-error {{cannot convert return expression of type 'Bool' to return type 'Int'}}
}
postfix operator +++
postfix func +++ <T>(_: inout T) -> T { fatalError() }
// <rdar://problem/21523291> compiler error message for mutating immutable field is incorrect
func r21523291(_ bytes : UnsafeMutablePointer<UInt8>) {
let i = 42 // expected-note {{change 'let' to 'var' to make it mutable}}
_ = bytes[i+++] // expected-error {{cannot pass immutable value to mutating operator: 'i' is a 'let' constant}}
}
// SR-1594: Wrong error description when using === on non-class types
class SR1594 {
func sr1594(bytes : UnsafeMutablePointer<Int>, _ i : Int?) {
_ = (i === nil) // expected-error {{value of type 'Int?' cannot be compared by reference; did you mean to compare by value?}} {{12-15===}}
_ = (bytes === nil) // expected-error {{type 'UnsafeMutablePointer<Int>' is not optional, value can never be nil}}
_ = (self === nil) // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns false}}
_ = (i !== nil) // expected-error {{value of type 'Int?' cannot be compared by reference; did you mean to compare by value?}} {{12-15=!=}}
_ = (bytes !== nil) // expected-error {{type 'UnsafeMutablePointer<Int>' is not optional, value can never be nil}}
_ = (self !== nil) // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns true}}
}
}
func nilComparison(i: Int, o: AnyObject) {
_ = i == nil // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns false}}
_ = nil == i // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns false}}
_ = i != nil // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns true}}
_ = nil != i // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns true}}
// FIXME(integers): uncomment these tests once the < is no longer ambiguous
// _ = i < nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil < i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = i <= nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil <= i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = i > nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil > i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = i >= nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil >= i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
_ = o === nil // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns false}}
_ = o !== nil // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns true}}
}
func secondArgumentNotLabeled(a: Int, _ b: Int) { }
secondArgumentNotLabeled(10, 20)
// expected-error@-1 {{missing argument label 'a:' in call}}
// <rdar://problem/23709100> QoI: incorrect ambiguity error due to implicit conversion
func testImplConversion(a : Float?) -> Bool {}
func testImplConversion(a : Int?) -> Bool {
let someInt = 42
let a : Int = testImplConversion(someInt) // expected-error {{argument labels '(_:)' do not match any available overloads}}
// expected-note @-1 {{overloads for 'testImplConversion' exist with these partially matching parameter lists: (a: Float?), (a: Int?)}}
}
// <rdar://problem/23752537> QoI: Bogus error message: Binary operator '&&' cannot be applied to two 'Bool' operands
class Foo23752537 {
var title: String?
var message: String?
}
extension Foo23752537 {
func isEquivalent(other: Foo23752537) {
// TODO: <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands"
// expected-error @+1 {{unexpected non-void return value in void function}}
return (self.title != other.title && self.message != other.message)
}
}
// <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands"
func rdar27391581(_ a : Int, b : Int) -> Int {
return a == b && b != 0
// expected-error @-1 {{cannot convert return expression of type 'Bool' to return type 'Int'}}
}
// <rdar://problem/22276040> QoI: not great error message with "withUnsafePointer" sametype constraints
func read2(_ p: UnsafeMutableRawPointer, maxLength: Int) {}
func read<T : BinaryInteger>() -> T? {
var buffer : T
let n = withUnsafeMutablePointer(to: &buffer) { (p) in
read2(UnsafePointer(p), maxLength: MemoryLayout<T>.size) // expected-error {{cannot convert value of type 'UnsafePointer<_>' to expected argument type 'UnsafeMutableRawPointer'}}
}
}
func f23213302() {
var s = Set<Int>()
s.subtract(1) // expected-error {{cannot convert value of type 'Int' to expected argument type 'Set<Int>'}}
}
// <rdar://problem/24202058> QoI: Return of call to overloaded function in void-return context
func rdar24202058(a : Int) {
return a <= 480 // expected-error {{unexpected non-void return value in void function}}
}
// SR-1752: Warning about unused result with ternary operator
struct SR1752 {
func foo() {}
}
let sr1752: SR1752?
true ? nil : sr1752?.foo() // don't generate a warning about unused result since foo returns Void
// <rdar://problem/27891805> QoI: FailureDiagnosis doesn't look through 'try'
struct rdar27891805 {
init(contentsOf: String, encoding: String) throws {}
init(contentsOf: String, usedEncoding: inout String) throws {}
init<T>(_ t: T) {}
}
try rdar27891805(contentsOfURL: nil, usedEncoding: nil)
// expected-error@-1 {{argument labels '(contentsOfURL:, usedEncoding:)' do not match any available overloads}}
// expected-note@-2 {{overloads for 'rdar27891805' exist with these partially matching parameter lists: (contentsOf: String, encoding: String), (contentsOf: String, usedEncoding: inout String)}}
// Make sure RawRepresentable fix-its don't crash in the presence of type variables
class NSCache<K, V> {
func object(forKey: K) -> V? {}
}
class CacheValue {
func value(x: Int) -> Int {} // expected-note {{found this candidate}}
func value(y: String) -> String {} // expected-note {{found this candidate}}
}
func valueForKey<K>(_ key: K) -> CacheValue? {
let cache = NSCache<K, CacheValue>()
return cache.object(forKey: key)?.value // expected-error {{ambiguous reference to member 'value(x:)'}}
}
// SR-2242: poor diagnostic when argument label is omitted
func r27212391(x: Int, _ y: Int) {
let _: Int = x + y
}
func r27212391(a: Int, x: Int, _ y: Int) {
let _: Int = a + x + y
}
r27212391(3, 5) // expected-error {{missing argument label 'x:' in call}}
r27212391(3, y: 5) // expected-error {{incorrect argument labels in call (have '_:y:', expected 'x:_:')}}
r27212391(3, x: 5) // expected-error {{argument 'x' must precede unnamed argument #1}} {{11-11=x: 5, }} {{12-18=}}
r27212391(y: 3, x: 5) // expected-error {{incorrect argument labels in call (have 'y:x:', expected 'x:_:')}} {{11-12=x}} {{17-20=}}
r27212391(y: 3, 5) // expected-error {{incorrect argument label in call (have 'y:_:', expected 'x:_:')}}
r27212391(x: 3, x: 5) // expected-error {{extraneous argument label 'x:' in call}}
r27212391(a: 1, 3, y: 5) // expected-error {{incorrect argument labels in call (have 'a:_:y:', expected 'a:x:_:')}}
r27212391(1, x: 3, y: 5) // expected-error {{incorrect argument labels in call (have '_:x:y:', expected 'a:x:_:')}}
r27212391(a: 1, y: 3, x: 5) // expected-error {{incorrect argument labels in call (have 'a:y:x:', expected 'a:x:_:')}} {{17-18=x}} {{23-26=}}
r27212391(a: 1, 3, x: 5) // expected-error {{argument 'x' must precede unnamed argument #2}} {{17-17=x: 5, }} {{18-24=}}
// SR-1255
func foo1255_1() {
return true || false // expected-error {{unexpected non-void return value in void function}}
}
func foo1255_2() -> Int {
return true || false // expected-error {{cannot convert return expression of type 'Bool' to return type 'Int'}}
}
// Diagnostic message for initialization with binary operations as right side
let foo1255_3: String = 1 + 2 + 3 // expected-error {{cannot convert value of type 'Int' to specified type 'String'}}
let foo1255_4: Dictionary<String, String> = ["hello": 1 + 2] // expected-error {{cannot convert value of type 'Int' to expected dictionary value type 'String'}}
let foo1255_5: Dictionary<String, String> = [(1 + 2): "world"] // expected-error {{cannot convert value of type 'Int' to expected dictionary key type 'String'}}
let foo1255_6: [String] = [1 + 2 + 3] // expected-error {{cannot convert value of type 'Int' to expected element type 'String'}}
// SR-2208
struct Foo2208 {
func bar(value: UInt) {}
}
func test2208() {
let foo = Foo2208()
let a: Int = 1
let b: Int = 2
let result = a / b
foo.bar(value: a / b) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
foo.bar(value: result) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
foo.bar(value: UInt(result)) // Ok
}
// SR-2164: Erroneous diagnostic when unable to infer generic type
struct SR_2164<A, B> { // expected-note 3 {{'B' declared as parameter to type 'SR_2164'}} expected-note 2 {{'A' declared as parameter to type 'SR_2164'}} expected-note * {{generic type 'SR_2164' declared here}}
init(a: A) {}
init(b: B) {}
init(c: Int) {}
init(_ d: A) {}
init(e: A?) {}
}
struct SR_2164_Array<A, B> { // expected-note {{'B' declared as parameter to type 'SR_2164_Array'}} expected-note * {{generic type 'SR_2164_Array' declared here}}
init(_ a: [A]) {}
}
struct SR_2164_Dict<A: Hashable, B> { // expected-note {{'B' declared as parameter to type 'SR_2164_Dict'}} expected-note * {{generic type 'SR_2164_Dict' declared here}}
init(a: [A: Double]) {}
}
SR_2164(a: 0) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(b: 1) // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(c: 2) // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(3) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164_Array([4]) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(e: 5) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164_Dict(a: ["pi": 3.14]) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164<Int>(a: 0) // expected-error {{generic type 'SR_2164' specialized with too few type parameters (got 1, but expected 2)}}
SR_2164<Int>(b: 1) // expected-error {{generic type 'SR_2164' specialized with too few type parameters (got 1, but expected 2)}}
let _ = SR_2164<Int, Bool>(a: 0) // Ok
let _ = SR_2164<Int, Bool>(b: true) // Ok
SR_2164<Int, Bool, Float>(a: 0) // expected-error {{generic type 'SR_2164' specialized with too many type parameters (got 3, but expected 2)}}
SR_2164<Int, Bool, Float>(b: 0) // expected-error {{generic type 'SR_2164' specialized with too many type parameters (got 3, but expected 2)}}
// <rdar://problem/29850459> Swift compiler misreports type error in ternary expression
let r29850459_flag = true
let r29850459_a: Int = 0
let r29850459_b: Int = 1
func r29850459() -> Bool { return false }
let _ = (r29850459_flag ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}}
let _ = ({ true }() ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}}
let _ = (r29850459() ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}}
let _ = ((r29850459_flag || r29850459()) ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}}
// SR-6272: Tailored diagnostics with fixits for numerical conversions
func SR_6272_a() {
enum Foo: Int {
case bar
}
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Int' and 'Float'}} {{35-35=Int(}} {{43-43=)}}
// expected-note@+1 {{expected an argument list of type '(Int, Int)'}}
let _: Int = Foo.bar.rawValue * Float(0)
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Int' and 'Float'}} {{18-18=Float(}} {{34-34=)}}
// expected-note@+1 {{expected an argument list of type '(Float, Float)'}}
let _: Float = Foo.bar.rawValue * Float(0)
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Int' and 'Float'}} {{none}}
// expected-note@+1 {{overloads for '*' exist with these partially matching parameter lists: (Float, Float), (Int, Int)}}
Foo.bar.rawValue * Float(0)
}
func SR_6272_b() {
let lhs = Float(3)
let rhs = Int(0)
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Float' and 'Int'}} {{24-24=Float(}} {{27-27=)}}
// expected-note@+1 {{expected an argument list of type '(Float, Float)'}}
let _: Float = lhs * rhs
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Float' and 'Int'}} {{16-16=Int(}} {{19-19=)}}
// expected-note@+1 {{expected an argument list of type '(Int, Int)'}}
let _: Int = lhs * rhs
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Float' and 'Int'}} {{none}}
// expected-note@+1 {{overloads for '*' exist with these partially matching parameter lists: (Float, Float), (Int, Int)}}
lhs * rhs
}
func SR_6272_c() {
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Int' and 'String'}} {{none}}
// expected-note@+1 {{expected an argument list of type '(Int, Int)'}}
Int(3) * "0"
struct S {}
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Int' and 'S'}} {{none}}
// expected-note@+1 {{expected an argument list of type '(Int, Int)'}}
Int(10) * S()
}
struct SR_6272_D: ExpressibleByIntegerLiteral {
typealias IntegerLiteralType = Int
init(integerLiteral: Int) {}
static func +(lhs: SR_6272_D, rhs: Int) -> Float { return 42.0 } // expected-note {{found this candidate}}
}
func SR_6272_d() {
let x: Float = 1.0
// expected-error@+2 {{binary operator '+' cannot be applied to operands of type 'SR_6272_D' and 'Float'}} {{none}}
// expected-note@+1 {{overloads for '+' exist with these partially matching parameter lists: (Float, Float), (SR_6272_D, Int)}}
let _: Float = SR_6272_D(integerLiteral: 42) + x
// expected-error@+2 {{binary operator '+' cannot be applied to operands of type 'SR_6272_D' and 'Double'}} {{none}}
// expected-note@+1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (SR_6272_D, Int)}}
let _: Float = SR_6272_D(integerLiteral: 42) + 42.0
// expected-error@+2 {{binary operator '+' cannot be applied to operands of type 'SR_6272_D' and 'Float'}} {{none}}
// expected-note@+1 {{overloads for '+' exist with these partially matching parameter lists: (Float, Float), (SR_6272_D, Int)}}
let _: Float = SR_6272_D(integerLiteral: 42) + x + 1.0
}
// Ambiguous overload inside a trailing closure
func ambiguousCall() -> Int {} // expected-note {{found this candidate}}
func ambiguousCall() -> Float {} // expected-note {{found this candidate}}
func takesClosure(fn: () -> ()) {}
takesClosure() { ambiguousCall() } // expected-error {{ambiguous use of 'ambiguousCall()'}}
// SR-4692: Useless diagnostics calling non-static method
class SR_4692_a {
private static func foo(x: Int, y: Bool) {
self.bar(x: x)
// expected-error@-1 {{instance member 'bar' cannot be used on type 'SR_4692_a'}}
}
private func bar(x: Int) {
}
}
class SR_4692_b {
static func a() {
self.f(x: 3, y: true)
// expected-error@-1 {{instance member 'f' cannot be used on type 'SR_4692_b'}}
}
private func f(a: Int, b: Bool, c: String) {
self.f(x: a, y: b)
}
private func f(x: Int, y: Bool) {
}
}
// rdar://problem/32101765 - Keypath diagnostics are not actionable/helpful
struct R32101765 { let prop32101765 = 0 }
let _: KeyPath<R32101765, Float> = \.prop32101765
// expected-error@-1 {{key path value type 'Int' cannot be converted to contextual type 'Float'}}
let _: KeyPath<R32101765, Float> = \R32101765.prop32101765
// expected-error@-1 {{key path value type 'Int' cannot be converted to contextual type 'Float'}}
let _: KeyPath<R32101765, Float> = \.prop32101765.unknown
// expected-error@-1 {{type 'Int' has no member 'unknown'}}
let _: KeyPath<R32101765, Float> = \R32101765.prop32101765.unknown
// expected-error@-1 {{type 'Int' has no member 'unknown'}}
// rdar://problem/32390726 - Bad Diagnostic: Don't suggest `var` to `let` when binding inside for-statement
for var i in 0..<10 { // expected-warning {{variable 'i' was never mutated; consider removing 'var' to make it constant}} {{5-9=}}
_ = i + 1
}
// rdar://problem/32726044 - shrink reduced domains too far
public protocol P_32726044 {}
extension Int: P_32726044 {}
extension Float: P_32726044 {}
public func *(lhs: P_32726044, rhs: P_32726044) -> Double {
fatalError()
}
func rdar32726044() -> Float {
var f: Float = 0
f = Float(1) * 100 // Ok
let _: Float = Float(42) + 0 // Ok
return f
}
// SR-5045 - Attempting to return result of reduce(_:_:) in a method with no return produces ambiguous error
func sr5045() {
let doubles: [Double] = [1, 2, 3]
return doubles.reduce(0, +)
// expected-error@-1 {{unexpected non-void return value in void function}}
}
// rdar://problem/32934129 - QoI: misleading diagnostic
class L_32934129<T : Comparable> {
init(_ value: T) { self.value = value }
init(_ value: T, _ next: L_32934129<T>?) {
self.value = value
self.next = next
}
var value: T
var next: L_32934129<T>? = nil
func length() -> Int {
func inner(_ list: L_32934129<T>?, _ count: Int) {
guard let list = list else { return count } // expected-error {{unexpected non-void return value in void function}}
return inner(list.next, count + 1)
}
return inner(self, 0) // expected-error {{cannot convert return expression of type '()' to return type 'Int'}}
}
}
// rdar://problem/31671195 - QoI: erroneous diagnostic - cannot call value of non-function type
class C_31671195 {
var name: Int { fatalError() }
func name(_: Int) { fatalError() }
}
C_31671195().name(UInt(0))
// expected-error@-1 {{cannot convert value of type 'UInt' to expected argument type 'Int'}}
// rdar://problem/28456467 - QoI: erroneous diagnostic - cannot call value of non-function type
class AST_28456467 {
var hasStateDef: Bool { return false }
}
protocol Expr_28456467 {}
class ListExpr_28456467 : AST_28456467, Expr_28456467 {
let elems: [Expr_28456467]
init(_ elems:[Expr_28456467] ) {
self.elems = elems
}
override var hasStateDef: Bool {
return elems.first(where: { $0.hasStateDef }) != nil
// expected-error@-1 {{value of type 'Expr_28456467' has no member 'hasStateDef'}}
}
}
// rdar://problem/31849281 - Let's play "bump the argument"
struct rdar31849281 { var foo, a, b, c: Int }
_ = rdar31849281(a: 101, b: 102, c: 103, foo: 104) // expected-error {{argument 'foo' must precede argument 'a'}} {{18-18=foo: 104, }} {{40-50=}}
_ = rdar31849281(a: 101, c: 103, b: 102, foo: 104) // expected-error {{argument 'foo' must precede argument 'a'}} {{18-18=foo: 104, }} {{40-50=}}
_ = rdar31849281(foo: 104, a: 101, c: 103, b: 102) // expected-error {{argument 'b' must precede argument 'c'}} {{36-36=b: 102, }} {{42-50=}}
_ = rdar31849281(b: 102, c: 103, a: 101, foo: 104) // expected-error {{incorrect argument labels in call (have 'b:c:a:foo:', expected 'foo:a:b:c:')}} {{18-19=foo}} {{26-27=a}} {{34-35=b}} {{42-45=c}}
_ = rdar31849281(foo: 104, b: 102, c: 103, a: 101) // expected-error {{argument 'a' must precede argument 'b'}} {{28-28=a: 101, }} {{42-50=}}
func var_31849281(_ a: Int, _ b: Int..., c: Int) {}
var_31849281(1, c: 10, 3, 4, 5, 6, 7, 8, 9) // expected-error {{unnamed argument #3 must precede argument 'c'}} {{17-17=3, 4, 5, 6, 7, 8, 9, }} {{22-43=}}
func fun_31849281(a: (Bool) -> Bool, b: (Int) -> (String), c: [Int?]) {}
fun_31849281(c: [nil, 42], a: { !$0 }, b: { (num: Int) -> String in return "\(num)" })
// expected-error @-1 {{incorrect argument labels in call (have 'c:a:b:', expected 'a:b:c:')}} {{14-15=a}} {{28-29=b}} {{40-41=c}}
fun_31849281(a: { !$0 }, c: [nil, 42], b: { (num: Int) -> String in return String(describing: num) })
// expected-error @-1 {{argument 'b' must precede argument 'c'}} {{26-26=b: { (num: Int) -> String in return String(describing: num) }, }} {{38-101=}}
fun_31849281(a: { !$0 }, c: [nil, 42], b: { "\($0)" })
// expected-error @-1 {{argument 'b' must precede argument 'c'}} {{26-26=b: { "\\($0)" }, }} {{38-54=}}
func f_31849281(x: Int, y: Int, z: Int) {}
f_31849281(42, y: 10, x: 20) // expected-error {{incorrect argument labels in call (have '_:y:x:', expected 'x:y:z:')}} {{12-12=x: }} {{23-24=z}}
func sr5081() {
var a = ["1", "2", "3", "4", "5"]
var b = [String]()
b = a[2...4] // expected-error {{cannot assign value of type 'ArraySlice<String>' to type '[String]'}}
}
func rdar17170728() {
var i: Int? = 1
var j: Int?
var k: Int? = 2
let _ = [i, j, k].reduce(0 as Int?) {
$0 && $1 ? $0! + $1! : ($0 ? $0! : ($1 ? $1! : nil))
// expected-error@-1 {{cannot force unwrap value of non-optional type 'Bool'}} {{18-19=}}
// expected-error@-2 {{cannot force unwrap value of non-optional type 'Bool'}} {{24-25=}}
// expected-error@-3 {{cannot force unwrap value of non-optional type 'Bool'}} {{36-37=}}
// expected-error@-4 {{cannot force unwrap value of non-optional type 'Bool'}} {{48-49=}}
}
let _ = [i, j, k].reduce(0 as Int?) {
$0 && $1 ? $0 + $1 : ($0 ? $0 : ($1 ? $1 : nil))
// expected-error@-1 {{ambiguous use of operator '+'}}
}
}
// https://bugs.swift.org/browse/SR-5934 - failure to emit diagnostic for bad
// generic constraints
func elephant<T, U>(_: T) where T : Collection, T.Element == U, T.Element : Hashable {} // expected-note {{where 'U' = 'T'}}
func platypus<T>(a: [T]) {
_ = elephant(a) // expected-error {{global function 'elephant' requires that 'T' conform to 'Hashable'}}
}
// Another case of the above.
func badTypes() {
let sequence:AnySequence<[Int]> = AnySequence() { AnyIterator() { [3] }}
let array = [Int](sequence)
// expected-error@-1 {{initializer 'init(_:)' requires the types 'Int' and '[Int]' be equivalent}}
}
// rdar://34357545
func unresolvedTypeExistential() -> Bool {
return (Int.self==_{})
// expected-error@-1 {{ambiguous reference to member '=='}}
}
func rdar43525641(_ a: Int, _ b: Int = 0, c: Int = 0, _ d: Int) {}
rdar43525641(1, c: 2, 3) // Ok
| apache-2.0 | 31da963d2a01a7e43d9ea8a6b49bff01 | 44.854337 | 240 | 0.663187 | 3.535268 | false | false | false | false |
practicalswift/swift | benchmark/single-source/NibbleSort.swift | 2 | 1009 | // NibbleSort benchmark
//
// Source: https://gist.github.com/airspeedswift/f4daff4ea5c6de9e1fdf
import TestsUtils
public var NibbleSort = BenchmarkInfo(
name: "NibbleSort",
runFunction: run_NibbleSort,
tags: [.validation],
legacyFactor: 10
)
@inline(never)
public func run_NibbleSort(_ N: Int) {
let vRef: UInt64 = 0xfeedbba000000000
let v: UInt64 = 0xbadbeef
var c = NibbleCollection(v)
for _ in 1...1_000*N {
c.val = v
c.sort()
if c.val != vRef {
break
}
}
CheckResults(c.val == vRef)
}
struct NibbleCollection {
var val: UInt64
init(_ val: UInt64) { self.val = val }
}
extension NibbleCollection: RandomAccessCollection, MutableCollection {
typealias Index = UInt64
var startIndex: UInt64 { return 0 }
var endIndex: UInt64 { return 16 }
subscript(idx: UInt64) -> UInt64 {
get {
return (val >> (idx*4)) & 0xf
}
set(n) {
let mask = (0xf as UInt64) << (idx * 4)
val &= ~mask
val |= n << (idx * 4)
}
}
}
| apache-2.0 | 7f1a22fece5abf94585234d4b984ca04 | 18.403846 | 71 | 0.625372 | 3.104615 | false | false | false | false |
ascode/JF-IOS-Swift_demos | IOSDemos/Controller/PlayVoiceFormNetViewController.swift | 1 | 1576 | //
// PlayVoiceFormNetViewController.swift
// IOSDemos
//
// Created by 金飞 on 28/12/2016.
// Copyright © 2016 Enjia. All rights reserved.
//
import UIKit
class PlayVoiceFormNetViewController: UIViewController, PlayVoiceFormNetViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let kselfviewW: CGFloat = UIScreen.main.bounds.width
let kselfviewH: CGFloat = UIScreen.main.bounds.height - UIApplication.shared.statusBarFrame.height
let kselfviewX: CGFloat = UIScreen.main.bounds.origin.x
let kselfviewY: CGFloat = UIScreen.main.bounds.origin.y + UIApplication.shared.statusBarFrame.height
let selfview: PlayVoiceFormNetView = PlayVoiceFormNetView(frame: CGRect(x: kselfviewX, y: kselfviewY, width: kselfviewW, height: kselfviewH))
selfview.backgroundColor = UIColor.white
selfview._delegate = self
self.view = selfview
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func btnBackPressed(btnObj: UIButton) {
self.dismiss(animated: true) {
}
}
/*
// 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.
}
*/
}
| artistic-2.0 | c56e94cec2e508e0ab11fc3c9d08dafe | 31.061224 | 149 | 0.685551 | 4.475783 | false | false | false | false |
jxxcarlson/AsciidocEdit | adviewer/Regex.swift | 1 | 888 | //
// regex.swift
// AsciidocEdit
//
// Created by James Carlson on 11/5/14.
// Copyright (c) 2014 James Carlson. All rights reserved.
//
import Foundation
prefix operator / { }
prefix func / (pattern:String) -> NSRegularExpression {
var options: NSRegularExpressionOptions =
NSRegularExpressionOptions.DotMatchesLineSeparators
return NSRegularExpression(pattern:pattern,
options:options, error:nil)!
}
infix operator =~ { }
func =~ (left: String, right: NSRegularExpression) -> Bool {
let matches = right.numberOfMatchesInString(left,
options: nil,
range: NSMakeRange(0, left.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)))
return matches > 0
}
/***
// http://nomothetis.svbtle.com/clean-regular-expressions-using-conversions
let alpha = "math, \\[\na^2 + b^2\n\\], ho ho!"
println(alpha)
alpha =~ /"\\[.*\\]"
***/
| mit | fb49edf638df6600b2bad60f7b4d4a92 | 18.733333 | 85 | 0.676802 | 3.794872 | false | false | false | false |
AndreyPanov/ApplicationCoordinator | ApplicationCoordinator/Application/AppDelegate.swift | 1 | 1558 | @UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var rootController: UINavigationController {
return self.window!.rootViewController as! UINavigationController
}
private lazy var applicationCoordinator: Coordinator = self.makeCoordinator()
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let notification = launchOptions?[.remoteNotification] as? [String: AnyObject]
let deepLink = DeepLinkOption.build(with: notification)
applicationCoordinator.start(with: deepLink)
return true
}
private func makeCoordinator() -> Coordinator {
return ApplicationCoordinator(
router: RouterImp(rootController: self.rootController),
coordinatorFactory: CoordinatorFactoryImp()
)
}
//MARK: Handle push notifications and deep links
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
let dict = userInfo as? [String: AnyObject]
let deepLink = DeepLinkOption.build(with: dict)
applicationCoordinator.start(with: deepLink)
}
func application(_ application: UIApplication, continue userActivity: NSUserActivity,
restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
let deepLink = DeepLinkOption.build(with: userActivity)
applicationCoordinator.start(with: deepLink)
return true
}
}
| mit | 2e387caad493627e318a67ed00846822 | 37.95 | 113 | 0.727214 | 5.70696 | false | false | false | false |
nodes-ios/NStack | Pods/Quick/Sources/Quick/Callsite.swift | 15 | 979 | import Foundation
#if canImport(Darwin) && !SWIFT_PACKAGE
@objcMembers
public class _CallsiteBase: NSObject {}
#else
public class _CallsiteBase: NSObject {}
#endif
/**
An object encapsulating the file and line number at which
a particular example is defined.
*/
final public class Callsite: _CallsiteBase {
/**
The absolute path of the file in which an example is defined.
*/
public let file: String
/**
The line number on which an example is defined.
*/
public let line: UInt
internal init(file: String, line: UInt) {
self.file = file
self.line = line
}
}
extension Callsite {
/**
Returns a boolean indicating whether two Callsite objects are equal.
If two callsites are in the same file and on the same line, they must be equal.
*/
@nonobjc public static func == (lhs: Callsite, rhs: Callsite) -> Bool {
return lhs.file == rhs.file && lhs.line == rhs.line
}
}
| mit | 2ed34fa5faaf3104425f190c8fedf25c | 24.102564 | 87 | 0.6476 | 4.165957 | false | false | false | false |
JesusAntonioGil/MemeMe | MemeMe/Model/ActivityManager.swift | 1 | 1423 | //
// ActivityManager.swift
// MemeMe
//
// Created by Jesus Antonio Gil on 13/2/16.
// Copyright © 2016 Jesus Antonio Gil. All rights reserved.
//
import UIKit
import QuartzCore
class ActivityManager: NSObject {
//Injected
var viewController: UIViewController!
var userDefaultsManager: UserDefaultsManager!
//MARK: PUBLIC
func shareImage(meme: Meme) {
let shareItems = [meme.memeImage]
let activityViewController: UIActivityViewController = UIActivityViewController(activityItems: shareItems, applicationActivities: nil)
activityViewController.excludedActivityTypes = [UIActivityTypePrint, UIActivityTypePostToWeibo, UIActivityTypeCopyToPasteboard, UIActivityTypeAddToReadingList, UIActivityTypePostToVimeo]
activityViewController.completionWithItemsHandler = {
(activity, success, items, error) in
self.userDefaultsManager.saveImage(meme.memeImage)
}
viewController.presentViewController(activityViewController, animated: true, completion: nil)
}
class func getImageFromView(view: UIView) -> UIImage {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
view.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let img: UIImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
}
| mit | 2711f52170ed20aa2df67af41a0a7182 | 33.682927 | 194 | 0.728551 | 5.710843 | false | false | false | false |
fellipecaetano/Democracy-iOS | Pods/RandomKit/Sources/RandomKit/Types/RandomGenerator/Seedable.swift | 3 | 5941 | //
// Seedable.swift
// RandomKit
//
// The MIT License (MIT)
//
// Copyright (c) 2015-2017 Nikolai Vazquez
//
// 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.
//
/// A type that can be instantiated with a `Seed`.
public protocol Seedable {
/// The seed type.
associatedtype Seed
/// Creates an instance from `seed`.
init(seed: Seed)
/// Reseeds `self` with `seed`.
mutating func reseed(with seed: Seed)
}
extension Seedable {
/// Reseeds `self` with `seed`.
public mutating func reseed(with seed: Seed) {
self = Self(seed: seed)
}
}
/// A type that can be seeded by a sequence.
public protocol SeedableFromSequence {
/// The seed sequence's element type.
associatedtype SeedSequenceElement
/// Creates an instance from `seed`.
init<S: Sequence>(seed: S) where S.Iterator.Element == SeedSequenceElement
/// Reseeds `self` with `seed`.
mutating func reseed<S: Sequence>(with seed: S) where S.Iterator.Element == SeedSequenceElement
}
extension SeedableFromSequence {
/// Reseeds `self` with `seed`.
public mutating func reseed<S: Sequence>(with sequence: S) where S.Iterator.Element == SeedSequenceElement {
self = Self(seed: sequence)
}
}
/// A type that can be seeded by another `randomGenerator`.
public protocol SeedableFromRandomGenerator: Random {
/// The default byte threshold at which `self` is reseeded in a `ReseedingRandomGenerator`.
static var reseedingThreshold: Int { get }
/// Creates an instance seeded with `randomGenerator`.
init<R: RandomGenerator>(seededWith randomGenerator: inout R)
/// Reseeds self with `randomGenerator`.
mutating func reseed<R: RandomGenerator>(with randomGenerator: inout R)
}
extension SeedableFromRandomGenerator {
/// The default byte threshold at which `self` is reseeded in a `ReseedingRandomGenerator` (32KB).
public static var reseedingThreshold: Int {
return 1024 * 32
}
/// Returns an instance seeded with `DeviceRandom.default`.
public static var seeded: Self {
return Self(seededWith: &DeviceRandom.default)
}
/// Generates a random value of `Self` using `randomGenerator`.
public static func random<R: RandomGenerator>(using randomGenerator: inout R) -> Self {
return Self(seededWith: &randomGenerator)
}
/// Reseeds self with `randomGenerator`.
public mutating func reseed<R: RandomGenerator>(with randomGenerator: inout R) {
self = Self(seededWith: &randomGenerator)
}
/// Reseeds self with `DeviceRandom.default`.
public mutating func reseed() {
reseed(with: &DeviceRandom.default)
}
}
extension RandomGenerator where Self: SeedableFromRandomGenerator {
/// Returns an instance that reseeds itself with `DeviceRandom.default`.
public static var reseeding: ReseedingRandomGenerator<Self, DeviceRandom> {
return reseeding(with: .default)
}
#if swift(>=3.2)
/// Returns an instance that reseeds itself with `reseeder`.
public static func reseeding<R>(with reseeder: R) -> ReseedingRandomGenerator<Self, R> {
return ReseedingRandomGenerator(reseeder: reseeder)
}
#else
/// Returns an instance that reseeds itself with `reseeder`.
public static func reseeding<R: RandomGenerator>(with reseeder: R) -> ReseedingRandomGenerator<Self, R> {
return ReseedingRandomGenerator(reseeder: reseeder)
}
#endif
}
extension Seedable where Self: SeedableFromRandomGenerator, Seed: Random {
/// Creates an instance seeded with `randomGenerator`.
public init<R: RandomGenerator>(seededWith randomGenerator: inout R) {
self.init(seed: Seed.random(using: &randomGenerator))
}
}
extension Seedable where Self: SeedableFromSequence, Seed: Sequence, Seed.Iterator.Element == Self.SeedSequenceElement {
@inline(__always)
private init<S: Sequence>(_seed: S) where S.Iterator.Element == SeedSequenceElement {
self.init(seed: _seed)
}
/// Creates an instance from `seed`.
public init(seed: Seed) {
// Required to specify initializer with same argument.
self.init(_seed: seed)
}
@inline(__always)
private mutating func _reseed<S: Sequence>(with _seed: S) where S.Iterator.Element == SeedSequenceElement {
reseed(with: _seed)
}
/// Reseeds `self` with `seed`.
public mutating func reseed(with seed: Seed) {
// Required to specify method with same name.
_reseed(with: seed)
}
}
extension Seedable where Self: SeedableFromSequence, Self.SeedSequenceElement == Seed {
/// Creates an instance from `seed`.
public init(seed: Seed) {
self.init(seed: CollectionOfOne(seed))
}
/// Reseeds `self` with `seed`.
public mutating func reseed(with seed: Seed) {
reseed(with: CollectionOfOne(seed))
}
}
| mit | 90cf49bfe1fde0cdcb5f0592939e4c74 | 30.94086 | 120 | 0.694833 | 4.114266 | false | false | false | false |
maxoly/PulsarKit | PulsarKit/PulsarKit/Sources/Sizes/SplittedSize.swift | 1 | 5397 | //
// SegmentedSize.swift
// PulsarKit
//
// Created by Massimo Oliviero on 21/03/2018.
// Copyright © 2019 Nacoon. All rights reserved.
//
import Foundation
public struct SplittedSize {
public let numOfElementsInWidth: CGFloat?
public let numOfElementsInHeight: CGFloat?
public let widthSize: Sizeable?
public let heightSize: Sizeable?
public init(numOfElementsInWidth: CGFloat, numOfElementsInHeight: CGFloat) {
self.numOfElementsInWidth = numOfElementsInWidth
self.numOfElementsInHeight = numOfElementsInHeight
self.widthSize = nil
self.heightSize = nil
}
public init(numOfElementsInWidth: CGFloat, heightSize: Sizeable? = nil) {
self.numOfElementsInWidth = numOfElementsInWidth
self.numOfElementsInHeight = nil
self.widthSize = nil
self.heightSize = heightSize
}
public init(numOfElementsInHeight: CGFloat, widthSize: Sizeable? = nil) {
self.numOfElementsInWidth = nil
self.numOfElementsInHeight = numOfElementsInHeight
self.widthSize = widthSize
self.heightSize = nil
}
}
// MARK: - Sizeable
extension SplittedSize: Sizeable {
public func size<View: UIView>(for view: View, descriptor: Descriptor, model: AnyHashable, in container: UIScrollView, at indexPath: IndexPath) -> CGSize {
let direction = scrollDirection(in: container)
let containerSize = adjustedSize(for: container, at: indexPath)
switch direction {
case .vertical:
let width = widthSize(for: view,
descriptor: descriptor,
model: model,
in: container,
at: indexPath,
alternativeSize: alternativeSize(for: .width))
let height = heightSize(for: view,
descriptor: descriptor,
model: model,
in: container,
at: indexPath,
alternativeSize: alternativeSize(for: .height, with: CGSize(width: width, height: containerSize.height)))
return CGSize(width: width, height: height)
case .horizontal:
let height = heightSize(for: view,
descriptor: descriptor,
model: model,
in: container,
at: indexPath,
alternativeSize: alternativeSize(for: .height))
let width = widthSize(for: view,
descriptor: descriptor,
model: model,
in: container,
at: indexPath,
alternativeSize: alternativeSize(for: .width, with: CGSize(width: containerSize.width, height: height)))
return CGSize(width: width, height: height)
@unknown default:
return .zero
}
}
}
private extension SplittedSize {
func alternativeSize(for dimension: SizeDimension, with proposedSize: CGSize? = nil) -> Sizeable {
switch dimension {
case .width:
return widthSize ?? AutolayoutSize(proposedContainerSize: proposedSize)
case .height:
return heightSize ?? AutolayoutSize(proposedContainerSize: proposedSize)
}
}
func widthSize<View: UIView>(for view: View,
descriptor: Descriptor,
model: AnyHashable,
in container: UIScrollView,
at indexPath: IndexPath,
alternativeSize: Sizeable) -> CGFloat {
let widthSpacing = itemsSpacing(for: .width, in: container, at: indexPath)
let containerSize = adjustedSize(for: container, at: indexPath)
if let segments = numOfElementsInWidth {
let totalWidthSpacing = widthSpacing * (segments - 1)
return (containerSize.width - totalWidthSpacing) / segments
}
return alternativeSize.size(for: view, descriptor: descriptor, model: model, in: container, at: indexPath).width
}
func heightSize<View: UIView>(for view: View,
descriptor: Descriptor,
model: AnyHashable,
in container: UIScrollView,
at indexPath: IndexPath,
alternativeSize: Sizeable) -> CGFloat {
let containerSize = adjustedSize(for: container, at: indexPath)
let heightSpacing = itemsSpacing(for: .height, in: container, at: indexPath)
if let segments = numOfElementsInHeight {
let totalHeightSpacing = heightSpacing * (segments - 1)
return (containerSize.height - totalHeightSpacing) / segments
}
return alternativeSize.size(for: view, descriptor: descriptor, model: model, in: container, at: indexPath).height
}
}
| mit | 5ac89caead6bf314764b6f76421db507 | 40.19084 | 159 | 0.542068 | 5.59751 | false | false | false | false |
blomma/stray | stray/Tag+CoreDataClass.swift | 1 | 649 | import Foundation
import CoreData
import CloudKit
class Tag: NSManagedObject, CoreDataStackEntity {
override func awakeFromInsert() {
super.awakeFromInsert()
self.id = UUID().uuidString
}
}
extension Tag: CloudKitStackEntity {
var recordType: String { return Tag.entityName }
var recordName: String { return "\(recordType).\(id)" }
var recordZoneName: String { return Tag.entityName }
func record() -> CKRecord {
let id = recordID()
let record = CKRecord(recordType: recordType, recordID: id)
if let name = name { record["name"] = name as CKRecordValue }
record["sortIndex"] = sortIndex as CKRecordValue
return record
}
}
| gpl-3.0 | ea338def898fd93b61c7280aaf374ba2 | 23.037037 | 63 | 0.727273 | 3.957317 | false | false | false | false |
SwiftAndroid/swift | test/Inputs/clang-importer-sdk/swift-modules/ObjectiveC.swift | 4 | 1868 | @_exported import ObjectiveC // Clang module
// The iOS/arm64 target uses _Bool for Objective-C's BOOL. We include
// x86_64 here as well because the iOS simulator also uses _Bool.
#if ((os(iOS) || os(tvOS)) && (arch(arm64) || arch(x86_64))) || os(watchOS)
public struct ObjCBool : Boolean {
private var value : Bool
public init(_ value: Bool) {
self.value = value
}
/// \brief Allow use in a Boolean context.
public var boolValue: Bool {
return value
}
}
#else
public struct ObjCBool : Boolean {
private var value : UInt8
public init(_ value: Bool) {
self.value = value ? 1 : 0
}
public init(_ value: UInt8) {
self.value = value
}
/// \brief Allow use in a Boolean context.
public var boolValue: Bool {
if value == 0 { return false }
return true
}
}
#endif
extension ObjCBool : BooleanLiteralConvertible {
public init(booleanLiteral: Bool) {
self.init(booleanLiteral)
}
}
public struct Selector : StringLiteralConvertible {
private var ptr : OpaquePointer
public init(_ value: String) {
self.init(stringLiteral: value)
}
public init(unicodeScalarLiteral value: String) {
self.init(stringLiteral: value)
}
public init(extendedGraphemeClusterLiteral value: String) {
self.init(stringLiteral: value)
}
public init (stringLiteral value: String) {
self = sel_registerName(value)
}
}
public struct NSZone {
public var pointer : OpaquePointer
}
internal func _convertBoolToObjCBool(_ x: Bool) -> ObjCBool {
return ObjCBool(x)
}
internal func _convertObjCBoolToBool(_ x: ObjCBool) -> Bool {
return Bool(x)
}
public func ~=(x: NSObject, y: NSObject) -> Bool {
return true
}
extension NSObject : Equatable, Hashable {
public var hashValue: Int {
return hash
}
}
public func == (lhs: NSObject, rhs: NSObject) -> Bool {
return lhs.isEqual(rhs)
}
| apache-2.0 | e2cce2237ffdf544d0898fe650da7573 | 19.755556 | 75 | 0.675589 | 3.820041 | false | false | false | false |
KagasiraBunJee/TryHard | TryHard/THPublicBT.swift | 1 | 8399 | //
// THPublicBT.swift
// TryHard
//
// Created by Sergey on 6/14/16.
// Copyright © 2016 Sergey Polishchuk. All rights reserved.
//
import UIKit
import CoreBluetooth
class THPublicBT: UIViewController, UITableViewDelegate, UITableViewDataSource, CBCentralManagerDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var scanButton: UIButton!
@IBOutlet weak var refreshButton: UIButton!
@IBOutlet weak var stopButton: UIButton!
var devices = [CBPeripheral]()
var centralManager = CBCentralManager()
var connectedDevice:CBPeripheral!
var miManager:MIServiceManager!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
centralManager = CBCentralManager(delegate: self, queue: nil)
miManager = MIServiceManager.sharedManager()
scanButton.enabled = false
}
func enabled() {
scanButton.enabled = true
}
//MARK:- TableViewHelper
func didDiscoverPeripheral(peripheral: CBPeripheral) {
for (index, device) in devices.enumerate() {
if device == peripheral {
devices.removeAtIndex(index)
break
}
}
devices.append(peripheral)
tableView.reloadData()
}
//MARK:- IBActions
@IBAction func scanAction(sender: AnyObject) {
devices = []
tableView.reloadData()
centralManager.scanForPeripheralsWithServices([CBUUID(string: MIService.MILI.rawValue)], options: nil)
print("start scanning")
}
@IBAction func refresh(sender: AnyObject) {
}
@IBAction func stopAction(sender: AnyObject) {
centralManager.stopScan()
print("stop scanning")
}
//MARK:- UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return devices.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let device = devices[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier("deviceCell")!
cell.textLabel!.text = device.name ?? "Empty name"
return cell
}
//MARK:- UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let device = devices[indexPath.row]
centralManager.connectPeripheral(device, options: nil)
}
//MARK:- CBCentralManagerDelegate
func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
didDiscoverPeripheral(peripheral)
}
func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
print("did connect to peripheral", peripheral.name)
connectedDevice = peripheral
centralManager.stopScan()
if let name = peripheral.name where name == "MI" {
connectedDevice.delegate = self
connectedDevice.discoverServices(nil)
}
}
func centralManager(central: CBCentralManager, didFailToConnectPeripheral peripheral: CBPeripheral, error: NSError?) {
print("failed connection with ", peripheral.name)
}
func centralManagerDidUpdateState(central: CBCentralManager) {
switch (central.state) {
case .PoweredOff:
print("CoreBluetooth BLE hardware is powered off")
case .PoweredOn:
print("CoreBluetooth BLE hardware is powered on and ready")
enabled()
case .Resetting:
print("CoreBluetooth BLE hardware is resetting")
case .Unauthorized:
print("CoreBluetooth BLE state is unauthorized")
case .Unknown:
print("CoreBluetooth BLE state is unknown");
case .Unsupported:
print("CoreBluetooth BLE hardware is unsupported on this platform");
}
}
}
//MARK:- CBPeripheralDelegate
extension THPublicBT : CBPeripheralDelegate {
func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) {
NSLog("Peripheral services")
print("peripheral: ", peripheral.name)
for service in peripheral.services! {
switch MIService(rawValue: service.UUID.UUIDString)! {
case .MILI:
peripheral.discoverCharacteristics(nil, forService: service)
print("MILI service")
case .Alert:
peripheral.discoverCharacteristics(nil, forService: service)
default:
break
}
}
print("-----------------")
}
func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) {
NSLog("Peripheral characteristics")
print("service: ", service.UUID.UUIDString)
if MIService(rawValue: service.UUID.UUIDString)! == .MILI {
for ch in service.characteristics! {
miManager.add(ch)
switch MICharacteristic(rawValue: ch.UUID.UUIDString)! {
case .PAIR:
connectedDevice.writeValue("2".dataUsingEncoding(NSUTF8StringEncoding)!, forCharacteristic: ch, type: .WithResponse)
default:
break
}
}
} else if MIService(rawValue: service.UUID.UUIDString)! == .Alert {
for ch in service.characteristics! {
miManager.add(ch)
// switch MICharacteristic(rawValue: ch.UUID.UUIDString)! {
// case .Alert:
// let value = [0x02]
// let data = NSData(bytes: value, length: value.count)
// connectedDevice.writeValue(data, forCharacteristic: ch, type: .WithoutResponse)
// default:
// break
// }
}
}
print("-----------------")
}
func peripheral(peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) {
print("didModifyServices: ", invalidatedServices)
}
func peripheral(peripheral: CBPeripheral, didDiscoverIncludedServicesForService service: CBService, error: NSError?) {
print("didDiscoverIncludedServicesForService: ", service)
}
func peripheral(peripheral: CBPeripheral, didWriteValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
switch MICharacteristic(rawValue: characteristic.UUID.UUIDString)! {
case .PAIR:
connectedDevice.readValueForCharacteristic(characteristic)
default:
break
}
}
func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
print("didUpdateValueForCharacteristic: ", characteristic)
switch MICharacteristic(rawValue: characteristic.UUID.UUIDString)! {
case .PAIR:
let data = characteristic.value
// let c = CBMutableCharacteristic(type: CBUUID(string: MICharacteristic.Alert.rawValue), properties: .Notify, value: nil, permissions: .Writeable)
let value = [0x02]
let data1 = NSData(bytes: value, length: value.count)
peripheral.writeValue(data1, forCharacteristic: miManager.get(.Alert)!, type: .WithoutResponse)
default:
break
}
}
func peripheral(peripheral: CBPeripheral, didUpdateNotificationStateForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
print("didUpdateNotificationStateForCharacteristic: ", characteristic)
}
func peripheral(peripheral: CBPeripheral, didDiscoverDescriptorsForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
print("didDiscoverDescriptorsForCharacteristic", characteristic)
}
}
| mit | 4085a60155ce1f8fe1e0e67e8e5b68cb | 33.138211 | 158 | 0.616575 | 5.807746 | false | false | false | false |
konhondros/InfiniteScrollDialExample | InfiniteScrollDial/InfiniteScrollDial.swift | 1 | 17080 | //
// InfiniteScrollDial.swift
// InfiniteScrollDial
//
// Created by konhondros on 30/6/15.
// Copyright (c) 2015 http://www.konhondros.com All rights reserved.
//
import Foundation
import Cocoa
protocol InfiniteScrollDialDelegate {
func dialValueDidChange(value newValue: Float)
}
class InfiniteScrollDial: NSScrollView {
// MARK: - Properties
var delegate: InfiniteScrollDialDelegate!
var visibleUnits = Array<InfiniteScrollUnit>()
var unitContainerView: NSView!
var minValue: Int!
var maxValue: Int!
var initialValue: Float = 0
var driftLock: Bool = false
// MARK: - Initializers
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
self.commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
self.commonInit()
}
func commonInit() {
// Enable layer support
self.wantsLayer = true
// Comment next group if you dont like gradient mask
let gradient: CAGradientLayer = CAGradientLayer()
gradient.colors = [
NSColor(red: 0, green: 0, blue: 0, alpha: 0.0).cgColor,
NSColor(red: 0, green: 0, blue: 0, alpha: 1).cgColor,
NSColor(red: 0, green: 0, blue: 0, alpha: 1).cgColor,
NSColor(red: 0, green: 0, blue: 0, alpha: 0.0).cgColor]
gradient.locations = [0.0 , 0.3, 0.7, 1]
gradient.startPoint = CGPoint(x: 0.0, y: 1.0)
gradient.endPoint = CGPoint(x: 1.0, y: 1.0)
gradient.frame = CGRect(x: 0.0, y: 0.0, width: self.frame.size.width, height: self.frame.size.height)
self.layer!.mask = gradient
// Container view create
self.unitContainerView = NSView(frame: CGRect(x: 0, y: 0, width: 4000, height: self.frame.height))
// Limits
self.minValue = -1000
self.maxValue = 1000
self.scrollsDynamically = false
//self.hasHorizontalScroller = true
//self.hasVerticalScroller = false
// Set elasticities
self.verticalScrollElasticity = .none
self.horizontalScrollElasticity = .allowed
// Set background color behind dial
self.backgroundColor = NSColor.white
// Set the container view as documentView
self.documentView = self.unitContainerView
// Initialize units
//self.defineUnits(minX: 0, maxX: self.frame.width)
// Set continuously notification
self.postsBoundsChangedNotifications = true
NotificationCenter.default.addObserver(self, selector: #selector(InfiniteScrollDial.boundsDidChange), name: NSNotification.Name.NSViewBoundsDidChange, object: nil)
}
// MARK: - Methods
func setMinValue(value newValue: Int) {
if newValue < maxValue {
self.minValue = newValue
if self.valueInCenter() > Float(newValue) {
self.setDialValue(value: self.valueInCenter())
} else {
self.setDialValue(value: Float(newValue))
}
}
}
func setMaxValue(value newValue: Int) {
if newValue > minValue {
self.maxValue = newValue
if self.valueInCenter() < Float(newValue) {
self.setDialValue(value: self.valueInCenter())
} else {
self.setDialValue(value: Float(newValue))
}
}
}
func boundsDidChange() {
if self.driftLock {
return
}
if self.visibleUnits.count > 0 {
let firstUnit = self.visibleUnits.first
let lastUnit = self.visibleUnits.last
if firstUnit!.value > self.minValue && lastUnit!.value < self.maxValue {
self.driftContentToCenter()
}
if lastUnit!.value >= self.maxValue {
self.driftContentToEnd()
}
if firstUnit!.value <= self.minValue {
self.driftContentToBeginning()
}
// Send current center value to delegate
self.delegate.dialValueDidChange(value: self.valueInCenter())
}
self.defineUnits()
}
func driftContentToCenter() {
if self.driftLock {
return
}
let contentWidth = self.unitContainerView.frame.size.width
let centerOffsetX: CGFloat = (contentWidth - self.bounds.size.width) / 2.0;
if documentVisibleRect.midX < contentWidth * 0.25 || documentVisibleRect.midX > contentWidth * 0.75 {
let driftOffset = centerOffsetX - self.contentView.bounds.origin.x
DispatchQueue.main.async(execute: {
self.driftLock = true;
self.documentView!.scroll(NSMakePoint(centerOffsetX, 0))
for unit in self.visibleUnits {
unit.frame.origin.x += driftOffset
}
self.driftLock = false
})
}
}
func driftContentToBeginning() {
if self.driftLock {
return
}
let firstUnit = self.visibleUnits.first
_ = self.unitContainerView.frame.size.width
let balanceToCenter = (self.frame.size.width / 2) / self.visibleUnits.first!.frame.size.width - 0.5
let pixelsIntervalToCenter = firstUnit!.frame.size.width * balanceToCenter
if firstUnit!.frame.origin.x > 0 + pixelsIntervalToCenter {
self.driftLock = true
DispatchQueue.main.async(execute: {
self.documentView!.scroll(NSMakePoint(self.documentVisibleRect.minX - firstUnit!.frame.minX + pixelsIntervalToCenter, 0))
var i: Int = 0
for unit in self.visibleUnits {
let originX: CGFloat = CGFloat(i) * unit.frame.size.width
unit.frame.origin.x = originX + pixelsIntervalToCenter
unit.value = self.minValue + i
i += 1
}
self.driftLock = false
})
}
}
func driftContentToEnd() {
if self.driftLock == true {
return
}
let lastUnit = self.visibleUnits.last
let contentWidth = self.unitContainerView.frame.size.width
let balanceToCenter = (self.frame.size.width / 2) / self.visibleUnits.first!.frame.size.width - 0.5
let pixelsIntervalToCenter = lastUnit!.frame.size.width * balanceToCenter
if lastUnit!.frame.origin.x < ( contentWidth - lastUnit!.frame.size.width) - pixelsIntervalToCenter {
self.driftLock = true
DispatchQueue.main.async(execute: {
self.documentView!.scroll(NSMakePoint(( contentWidth + (self.documentVisibleRect.maxX - lastUnit!.frame.maxX) ) - self.frame.size.width - pixelsIntervalToCenter, 0))
var i: Int = 0
for unit in self.visibleUnits {
let originX: CGFloat = contentWidth - ( CGFloat(self.visibleUnits.count) * unit.frame.size.width) + (CGFloat(i) * unit.frame.size.width)
unit.frame.origin.x = originX - pixelsIntervalToCenter
unit.value = ( self.maxValue - self.visibleUnits.count ) + i + 1
i += 1
}
self.driftLock = false
})
}
}
func insertUnit(_ value: Int) -> InfiniteScrollUnit {
let unit: InfiniteScrollUnit = InfiniteScrollUnit(frame: CGRect(x: 0, y: 0, width: 200, height: self.unitContainerView.frame.height))
unit.value = value
self.unitContainerView.addSubview(unit)
return unit
}
func placeNewUnitOnRight(_ rightEdge: CGFloat) -> CGFloat {
let previousUnit = self.visibleUnits.last
var newUnitValue: Int!
if previousUnit != nil {
newUnitValue = previousUnit!.value + 1
} else {
newUnitValue = 0;
}
let unit = self.insertUnit(newUnitValue)
self.visibleUnits.append(unit)
var frame: CGRect = unit.frame
frame.origin.x = rightEdge
frame.origin.y = 0
unit.frame = frame
return frame.maxX
}
func placeNewUnitOnLeft(_ leftEdge: CGFloat) -> CGFloat {
let nextUnit = self.visibleUnits.first
let unit = self.insertUnit(nextUnit!.value - 1)
self.visibleUnits.insert(unit, at: 0)
var frame: CGRect = unit.frame
frame.origin.x = leftEdge - frame.size.width
frame.origin.y = 0
unit.frame = frame
return frame.minX
}
func defineUnits() {
// If not units define first
if self.visibleUnits.count == 0 {
self.placeNewUnitOnRight(documentVisibleRect.minX)
self.setDialValue(value: self.initialValue)
}
// Add units that are missing on right side
var lastUnit = self.visibleUnits.last
var rightEdge: CGFloat = lastUnit!.frame.maxX
while rightEdge < documentVisibleRect.maxX {
rightEdge = self.placeNewUnitOnRight(rightEdge)
//println("New unit on right side \(self.visibleUnits.last!.value)")
}
// Add units that are missing on left side
var firstUnit = self.visibleUnits.first
var leftEdge: CGFloat = firstUnit!.frame.minX
while leftEdge > documentVisibleRect.minX {
leftEdge = self.placeNewUnitOnLeft(leftEdge)
//println("New unit on left side \(self.visibleUnits.first!.value)")
}
// Remove units that have fallen off right edge
lastUnit = self.visibleUnits.last
while lastUnit!.frame.origin.x > documentVisibleRect.maxX {
//println("Remove unit from right side")
lastUnit?.removeFromSuperview()
self.visibleUnits.removeLast()
lastUnit = self.visibleUnits.last
}
// Remove units that have fallen off left edge
firstUnit = self.visibleUnits.first;
while firstUnit!.frame.maxX < documentVisibleRect.minX {
//println("Remove unit from right side")
firstUnit!.removeFromSuperview()
self.visibleUnits.remove(at: 0)
firstUnit = self.visibleUnits[0]
}
}
func scrollToPointX(X x: CGFloat) {
self.documentView!.scroll(NSMakePoint(x, 0))
}
func valueInCenter() -> Float {
let firstUnit = self.visibleUnits.first
let value: CGFloat = CGFloat(firstUnit!.value)
// value in px of first unit interval from left edge
let firstUnitPixelInterval = documentVisibleRect.minX - firstUnit!.frame.minX
// Metric float value of first item from left edge from 0 to 1
let firstUnitFloatInterval = firstUnitPixelInterval / firstUnit!.frame.size.width
// Metric value from left edge to center of scrollview
let balanceToCenter = (self.frame.size.width / 2) / firstUnit!.frame.size.width
// Final value is value + firstUnitFloatInterval + balanceToCenter - 0.5 because the center of number in center of unit
let finalValue = value + firstUnitFloatInterval + balanceToCenter - 0.5
return Float(finalValue)
}
func setDialValue(value newValue: Float) {
if self.driftLock {
return
}
if self.visibleUnits.count > 0 {
let balanceToCenter = (self.frame.size.width / 2) / self.visibleUnits.first!.frame.size.width
if newValue <= Float(CGFloat(self.maxValue) - balanceToCenter) && newValue >= Float(CGFloat(self.minValue) + balanceToCenter) {
let contentWidth = self.unitContainerView.frame.size.width
let centerOffsetX: CGFloat = (contentWidth - self.bounds.size.width) / 2.0;
let valueInLeftEdge = CGFloat(newValue) - balanceToCenter + 0.5
let valueForFirstUnit = Int(floor(valueInLeftEdge))
let firstUnitOffsetMultiplier = valueInLeftEdge - CGFloat(valueForFirstUnit)
let firstUnitPixelInterval = self.visibleUnits.first!.frame.size.width * firstUnitOffsetMultiplier
DispatchQueue.main.async(execute: {
self.documentView!.scroll(NSMakePoint(centerOffsetX, 0))
self.visibleUnits.removeAll(keepingCapacity: true)
self.unitContainerView.subviews.removeAll(keepingCapacity: true)
let unit = self.insertUnit(valueForFirstUnit)
self.visibleUnits.append(unit)
var frame: CGRect = unit.frame
frame.origin.x = self.documentVisibleRect.minX - firstUnitPixelInterval
frame.origin.y = 0
unit.frame = frame
self.boundsDidChange()
})
} else if newValue > Float(CGFloat(self.maxValue) - balanceToCenter) && newValue <= Float(self.maxValue) {
let valueInLeftEdge = CGFloat(newValue) - balanceToCenter;
let firstUnitValue = floor(valueInLeftEdge)
let firstUnitOriginX = self.unitContainerView.frame.size.width - ((CGFloat(self.maxValue) + balanceToCenter) - firstUnitValue + 0.5) * self.visibleUnits.first!.frame.size.width
let offsetToLeftEdge = ( valueInLeftEdge - firstUnitValue + 0.5 ) * self.visibleUnits.first!.frame.size.width
DispatchQueue.main.async(execute: {
self.driftLock = true
self.documentView!.scroll(NSMakePoint(round(firstUnitOriginX + offsetToLeftEdge), 0))
self.visibleUnits.removeAll(keepingCapacity: true)
self.unitContainerView.subviews.removeAll(keepingCapacity: true)
let unit = self.insertUnit(Int(firstUnitValue))
self.visibleUnits.append(unit)
var frame: CGRect = unit.frame
frame.origin.x = round(firstUnitOriginX)
frame.origin.y = 0
unit.frame = frame
self.defineUnits()
self.driftLock = false
self.boundsDidChange()
})
} else if newValue < Float(CGFloat(self.maxValue) + balanceToCenter) && newValue >= Float(self.minValue) {
let valueInLeftEdge = CGFloat(newValue) - balanceToCenter
let valueInBeggining = CGFloat(self.minValue) - balanceToCenter
let firstUnitValue = floor(valueInLeftEdge + 0.5)
let documentFirstValue = floor(valueInBeggining + 0.5)
let documentFirstValueOriginX = 0 - ( self.visibleUnits.first!.frame.size.width - ( ( 0.5 - ( valueInBeggining - documentFirstValue ) ) * self.visibleUnits.first!.frame.size.width) )
let documentOffsetPixels = round(( valueInLeftEdge - valueInBeggining ) * self.visibleUnits.first!.frame.size.width)
var firstUnitValueOriginX: CGFloat!
if firstUnitValue > documentFirstValue {
firstUnitValueOriginX = (( firstUnitValue - documentFirstValue ) * self.visibleUnits.first!.frame.size.width) + documentFirstValueOriginX
} else {
firstUnitValueOriginX = documentFirstValueOriginX
}
DispatchQueue.main.async(execute: {
self.driftLock = true
self.documentView!.scroll(NSMakePoint(documentOffsetPixels, 0))
self.visibleUnits.removeAll(keepingCapacity: true)
self.unitContainerView.subviews.removeAll(keepingCapacity: true)
let unit = self.insertUnit(Int(firstUnitValue))
self.visibleUnits.append(unit)
var frame: CGRect = unit.frame
frame.origin.x = round(firstUnitValueOriginX)
frame.origin.y = 0
unit.frame = frame
self.defineUnits()
self.driftLock = false
self.boundsDidChange()
})
}
}
}
}
| mit | dc6692da06f37e73ed83156d47664068 | 36.871397 | 198 | 0.565574 | 4.859175 | false | false | false | false |
omiz/Pulse | Pulse/PulseLayer.swift | 1 | 6653 | //
// PulseLayer.swift
// Pulse
//
// Created by Omar Allaham on 1/19/17.
// Copyright © 2017 Bemaxnet. All rights reserved.
//
import QuartzCore
import UIKit
private typealias PulseAccessor = PulseLayer
private typealias PulseInit = PulseLayer
private typealias PulseSetup = PulseLayer
private typealias PulseCAAnimationDelegate = PulseLayer
class PulseLayer: CAReplicatorLayer {
/**
get only var indicate the if the layer is animating
Type: Bool
*/
open var isAnimating: Bool {
return self.effect.animationKeys()?.count ?? 0 > 0
}
/**
Pulse radius
The default value of this property is 60
on frame update value will be updated
Type: CGFloat
*/
open var radius: CGFloat = 60 {
didSet {
let diameter: CGFloat = radius * 2
self.effect.bounds = CGRect(x: 0, y: 0, width: diameter, height:diameter)
self.effect.cornerRadius = self.radius
}
}
/**
The pulse radius start animation point
value should be from 0.0 to 1.0
The default value of this property is 0.0
Type: CGFloat
*/
open var radiusFromValue: CGFloat = 0 {
didSet {
if isAnimating {
animate()
}
}
}
/**
The pulse Alpha start animation point
value should be from 0.0 to 1.0
The default value of this property is: 0.45
Type: CGFloat
*/
open var alphaFromValue: CGFloat = 0.45 {
didSet {
if isAnimating {
animate()
}
}
}
/**
The pulse Opacity mid animation point
value should be from 0.0 to 1.0
The default value of this property is 0.2
Type: NSNumber
*/
open var keyTimeForHalfOpacity: NSNumber = 0.2 {
didSet {
if isAnimating {
animate()
}
}
}
/**
The pulse duration for each replicated.
The default value of this property is 3
Type: TimeInterval
*/
open var animationDuration: TimeInterval = 3 {
didSet {
self.instanceDelay = (self.animationDuration + self.pulseInterval) / Double(self.count)
}
}
/**
The pulse interval between each replicated.
The default value of this property is 0
Type: TimeInterval
*/
open var pulseInterval: TimeInterval = 0 {
didSet {
if (pulseInterval == .infinity) {
self.effect.removeAnimation(forKey: "pulse")
}
}
}
/**
This value indicate if the animation should use timingFunction
The default value of this property is true
Type: Bool
*/
open var useTimingFunction: Bool = true {
didSet {
if isAnimating {
animate()
}
}
}
/**
This count of the visible pulses
The default value of this property is 1
Type: NSInteger
*/
open var count: NSInteger = 1 {
didSet {
self.instanceCount = count
self.instanceDelay = (self.animationDuration + self.pulseInterval) / Double(count)
}
}
/**
This start delay of the animation
The default value of this property is 1
Type: TimeInterval
*/
open var startInterval: TimeInterval = 1 {
didSet {
self.instanceDelay = startInterval
}
}
/**
This color of the pulse
Type: CGColor?
*/
open var color: UIColor = UIColor.lightGray {
didSet {
self.effect.backgroundColor = color.cgColor
}
}
let effect: CALayer = CALayer()
var animationGroup: CAAnimationGroup!
override init() {
super.init()
self.effect.contentsScale = UIScreen.main.scale
self.effect.opacity = 0
self.addSublayer(self.effect)
self.setupDefaults()
}
override init(layer: Any) {
super.init(layer: layer)
}
required init(coder aDecoder: NSCoder) {
super.init()
}
}
extension PulseInit {
convenience init(in layer: CALayer) {
self.init()
layer.addSublayer(self)
frame = layer.frame
position = layer.position
}
}
extension PulseAccessor {
/**
Starts the pulse animation
return: void
*/
open func animate() {
if isAnimating {
stop()
}
setupAnimationGroup()
self.effect.add(animationGroup!, forKey: "pulse")
}
/**
Stops the animation
return: void
*/
open func stop() {
self.effect.removeAllAnimations()
}
override var frame: CGRect {
didSet {
self.effect.frame = bounds
radius = min(frame.width, frame.height)
}
}
/**
Repeat count
Type: Float
*/
override var repeatCount: Float {
didSet {
self.animationGroup?.repeatCount = repeatCount
}
}
}
extension PulseSetup {
func setupDefaults() {
radiusFromValue = 0.0
keyTimeForHalfOpacity = 0.2
animationDuration = 3
pulseInterval = 0
useTimingFunction = true
self.repeatCount = .infinity
self.radius = 60
self.count = 1
self.startInterval = 1
self.color = UIColor(red: 0, green: 0.455, blue: 0.756, alpha: alphaFromValue)
}
func setupAnimationGroup() {
animationGroup = CAAnimationGroup()
animationGroup.duration = self.animationDuration + self.pulseInterval
animationGroup.repeatCount = self.repeatCount
if self.useTimingFunction {
let defaultCurve = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault)
animationGroup.timingFunction = defaultCurve
}
let animations: [CAAnimation] = [scale(), opacityAnimation()]
animationGroup.animations = animations
animationGroup.delegate = self
}
private func scale() -> CAAnimation {
let anim = CABasicAnimation(keyPath: "transform.scale.xy")
anim.fromValue = self.radiusFromValue
anim.toValue = 1.0
anim.duration = self.animationDuration
return anim
}
private func opacityAnimation() -> CAAnimation {
let anim = CAKeyframeAnimation(keyPath: "opacity")
anim.duration = self.animationDuration
let alphaFromValue = self.color.cgColor.alpha
anim.values = [alphaFromValue, alphaFromValue * 0.5, 0];
anim.keyTimes = [0, keyTimeForHalfOpacity, 1.0];
return anim
}
}
extension PulseCAAnimationDelegate: CAAnimationDelegate {
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
// self.effect.removeAllAnimations()
//
// self.effect.removeFromSuperlayer()
//
// self.removeFromSuperlayer()
}
}
| mit | 40941db9618f64ab622e78aaeed09687 | 18.114943 | 96 | 0.610192 | 4.629088 | false | false | false | false |
darrarski/DRNet | DRNet/DRNet/Operation.swift | 1 | 4771 | //
// Operation.swift
// DRNet
//
// Created by Dariusz Rybicki on 02/11/14.
// Copyright (c) 2014 Darrarski. All rights reserved.
//
import Foundation
public class Operation {
public typealias OnErrorClosure = (response: Response, deserializedData: AnyObject?, errors: [NSError], shouldHandle: UnsafeMutablePointer<Bool>) -> Void
public typealias OnSuccessClosure = (response: Response, deserializedData: AnyObject?, shouldHandle: UnsafeMutablePointer<Bool>) -> Void
public typealias HandlerClosure = (operation: Operation, request: Request, task: Task, response: Response, deserializedData: AnyObject?, errors: [NSError]?) -> Void
public typealias OnCompleteClosure = (response: Response, deserializedData: AnyObject?, errors: [NSError]?) -> Void
public let validators: [ResponseValidator] = []
public let dataDeserializer: ResponseDeserializer? = nil
public let handlerClosure: HandlerClosure?
public var aborted: Bool {
return _aborted
}
private var _aborted = false
public init(validators: [ResponseValidator]?, dataDeserializer: ResponseDeserializer?, handlerClosure: HandlerClosure?) {
if let validators = validators {
self.validators = validators
}
self.dataDeserializer = dataDeserializer
self.handlerClosure = handlerClosure
}
public func perfromRequest(request: Request, usingProvider provider: Provider, onError: OnErrorClosure? = nil, onSuccess: OnSuccessClosure? = nil, onComplete: OnCompleteClosure? = nil) {
let task = Task(provider: provider)
perfromRequest(request, withTask: task, onError: onError, onSuccess: onSuccess, onComplete: onComplete)
}
public func perfromRequest(request: Request, withTask task: Task, onError: OnErrorClosure? = nil, onSuccess: OnSuccessClosure? = nil, onComplete: OnCompleteClosure? = nil) {
task.performRequest(request, completion: { [weak self] (response) -> Void in
if let sself = self {
if sself.aborted { return }
var deserializedData: AnyObject?
var errorsSet = NSMutableOrderedSet()
if let error = response.error {
errorsSet.addObject(error)
}
for validator: ResponseValidator in sself.validators {
if let errors = validator.validateResponse(response, forRequest: request) {
errorsSet.addObjectsFromArray(errors)
}
}
if let deserializer = sself.dataDeserializer {
let (data: AnyObject?, errors) = deserializer.deserializeResponseData(response)
deserializedData = data
if let errors = errors {
errorsSet.addObjectsFromArray(errors)
}
}
if sself.aborted { return }
var shouldHandle = true
if errorsSet.count > 0 {
if let onError = onError {
onError(
response: response,
deserializedData: deserializedData,
errors: errorsSet.array as [NSError],
shouldHandle: &shouldHandle
)
}
}
else {
if let onSuccess = onSuccess {
onSuccess(
response: response,
deserializedData: deserializedData,
shouldHandle: &shouldHandle
)
}
}
if sself.aborted { return }
let errors = errorsSet.count > 0 ? errorsSet.array as? [NSError] : nil
if shouldHandle {
sself.handlerClosure?(
operation: sself,
request: request,
task: task,
response: response,
deserializedData: deserializedData,
errors: errors
)
}
if let onComplete = onComplete {
onComplete(
response: response,
deserializedData: deserializedData,
errors: errors
)
}
}
})
}
public func abort() {
_aborted = true
}
} | mit | 2ec027f4af9f37b8ec7fe68f0094ebf6 | 38.438017 | 190 | 0.522113 | 6.008816 | false | false | false | false |
NodeDesigners/applovinhack | AppLovinHack/AppLovinHack/AppDelegate.swift | 1 | 1313 | //
// AppDelegate.swift
// AppLovinHack
//
// Created by Ahmed Modan on 4/16/16.
// Copyright © 2016 Ahmed Modan. All rights reserved.
//
import UIKit
import TVMLKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, TVApplicationControllerDelegate {
var window: UIWindow?
var appController: TVApplicationController?
static let TVBaseURL = "http://localhost:9001/"
static let TVBootURL = "\(AppDelegate.TVBaseURL)js/application.js"
// We'll hold a reference to the app controller in an optional property
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
// 1
let appControllerContext = TVApplicationControllerContext()
// 2
guard let javaScriptURL = NSURL(string: AppDelegate.TVBootURL) else {
fatalError("unable to create NSURL")
}
appControllerContext.javaScriptApplicationURL = javaScriptURL
appControllerContext.launchOptions["BASEURL"] = AppDelegate.TVBaseURL
// 3
appController = TVApplicationController(context: appControllerContext, window: window, delegate: self)
return true
}
}
| mit | 614af90dba0f81b9449a4733d3959d80 | 30.238095 | 127 | 0.696646 | 5.269076 | false | false | false | false |
FraDeliro/ISaMaterialLogIn | Example/Pods/Material/Sources/iOS/CollectionViewLayout.swift | 1 | 6384 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
open class CollectionViewLayout: UICollectionViewLayout {
/// Used to calculate the dimensions of the cells.
open var offset = CGPoint.zero
/// The size of items.
open var itemSize = CGSize.zero
/// A preset wrapper around contentEdgeInsets.
open var contentEdgeInsetsPreset = EdgeInsetsPreset.none {
didSet {
contentEdgeInsets = EdgeInsetsPresetToValue(preset: contentEdgeInsetsPreset)
}
}
/// A wrapper around grid.contentEdgeInsets.
open var contentEdgeInsets = EdgeInsets.zero
/// Size of the content.
open fileprivate(set) var contentSize = CGSize.zero
/// Layout attribute items.
open fileprivate(set) lazy var layoutItems = [(UICollectionViewLayoutAttributes, NSIndexPath)]()
/// Cell data source items.
open fileprivate(set) var dataSourceItems: [CollectionViewDataSourceItem]?
/// Scroll direction.
open var scrollDirection = UICollectionViewScrollDirection.vertical
/// A preset wrapper around interimSpace.
open var interimSpacePreset = InterimSpacePreset.none {
didSet {
interimSpace = InterimSpacePresetToValue(preset: interimSpacePreset)
}
}
/// Spacing between items.
open var interimSpace: InterimSpace = 0
open override var collectionViewContentSize: CGSize {
return contentSize
}
/**
Retrieves the index paths for the items within the passed in CGRect.
- Parameter rect: A CGRect that acts as the bounds to find the items within.
- Returns: An Array of NSIndexPath objects.
*/
open func indexPathsOfItemsInRect(rect: CGRect) -> [NSIndexPath] {
var paths = [NSIndexPath]()
for (attribute, indexPath) in layoutItems {
if rect.intersects(attribute.frame) {
paths.append(indexPath)
}
}
return paths
}
open override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
let item = dataSourceItems![indexPath.item]
if 0 < itemSize.width && 0 < itemSize.height {
attributes.frame = CGRect(x: offset.x, y: offset.y, width: itemSize.width - contentEdgeInsets.left - contentEdgeInsets.right, height: itemSize.height - contentEdgeInsets.top - contentEdgeInsets.bottom)
} else if .vertical == scrollDirection {
attributes.frame = CGRect(x: contentEdgeInsets.left, y: offset.y, width: collectionView!.bounds.width - contentEdgeInsets.left - contentEdgeInsets.right, height: item.height ?? collectionView!.bounds.height)
} else {
attributes.frame = CGRect(x: offset.x, y: contentEdgeInsets.top, width: item.width ?? collectionView!.bounds.width, height: collectionView!.bounds.height - contentEdgeInsets.top - contentEdgeInsets.bottom)
}
return attributes
}
open override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var layoutAttributes = [UICollectionViewLayoutAttributes]()
for (attribute, _) in layoutItems {
if rect.intersects(attribute.frame) {
layoutAttributes.append(attribute)
}
}
return layoutAttributes
}
open override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return .vertical == scrollDirection ? newBounds.width != collectionView!.bounds.width : newBounds.height != collectionView!.bounds.height
}
open override func prepare() {
guard let dataSource = collectionView?.dataSource as? CollectionViewDataSource else {
return
}
prepareLayoutForItems(dataSourceItems: dataSource.dataSourceItems)
}
open override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
return proposedContentOffset
}
fileprivate func prepareLayoutForItems(dataSourceItems: [CollectionViewDataSourceItem]) {
self.dataSourceItems = dataSourceItems
layoutItems.removeAll()
offset.x = contentEdgeInsets.left
offset.y = contentEdgeInsets.top
for i in 0..<dataSourceItems.count {
let item = dataSourceItems[i]
let indexPath = IndexPath(item: i, section: 0)
layoutItems.append((layoutAttributesForItem(at: indexPath)!, indexPath as NSIndexPath))
offset.x += interimSpace
offset.x += item.width ?? itemSize.width
offset.y += interimSpace
offset.y += item.height ?? itemSize.height
}
offset.x += contentEdgeInsets.right - interimSpace
offset.y += contentEdgeInsets.bottom - interimSpace
if 0 < itemSize.width && 0 < itemSize.height {
contentSize = CGSize(width: offset.x, height: offset.y)
} else if .vertical == scrollDirection {
contentSize = CGSize(width: collectionView!.bounds.width, height: offset.y)
} else {
contentSize = CGSize(width: offset.x, height: collectionView!.bounds.height)
}
}
}
| mit | 24f9bd2667eb3e13459ad404f966cd12 | 38.407407 | 219 | 0.744361 | 4.582915 | false | false | false | false |
tombuildsstuff/swiftcity | SwiftCity/Entities/SnapshotDependency.swift | 1 | 867 | public struct SnapshotDependency {
public let id: String
public let type: String
public let properties: Parameters
public let sourceBuildType: BuildTypeLocator
init?(dictionary: [String: AnyObject]) {
guard let id = dictionary["id"] as? String,
let type = dictionary["type"] as? String,
let propertiesDictionary = dictionary["properties"] as? [String: AnyObject],
let properties = Parameters(dictionary: propertiesDictionary),
let sourceBuildTypeDictionary = dictionary["source-buildType"] as? [String: AnyObject],
let sourceBuildType = BuildTypeLocator(dictionary: sourceBuildTypeDictionary) else {
return nil
}
self.id = id
self.type = type
self.properties = properties
self.sourceBuildType = sourceBuildType
}
}
| mit | 5606169110308a3c5d57b7bd60f2d33d | 35.125 | 99 | 0.652826 | 5.130178 | false | false | false | false |
debugsquad/metalic | metalic/View/Store/VStore.swift | 1 | 8586 | import UIKit
class VStore:UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
{
weak var controller:CStore!
weak var viewStore:VStore!
weak var viewSpinner:VSpinner!
weak var collectionView:UICollectionView!
private var arrayKeys:[String]
private let kHeaderSize:CGFloat = 75
private let kFooterSize:CGFloat = 130
private let kCollectionBottom:CGFloat = 20
private let kCellSize:CGFloat = 140
private let kInterLine:CGFloat = 1
init(controller:CStore)
{
arrayKeys = []
super.init(frame:CGRect.zero)
self.controller = controller
clipsToBounds = true
backgroundColor = UIColor.background
translatesAutoresizingMaskIntoConstraints = false
let barHeight:CGFloat = controller.parentController.viewParent.kBarHeight
let viewSpinner:VSpinner = VSpinner()
self.viewSpinner = viewSpinner
let flow:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
flow.footerReferenceSize = CGSize.zero
flow.minimumLineSpacing = kInterLine
flow.minimumInteritemSpacing = 0
flow.scrollDirection = UICollectionViewScrollDirection.vertical
flow.sectionInset = UIEdgeInsets(top:0, left:0, bottom:kCollectionBottom, right:0)
let collectionView:UICollectionView = UICollectionView(frame:CGRect.zero, collectionViewLayout:flow)
collectionView.clipsToBounds = true
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.backgroundColor = UIColor.clear
collectionView.showsVerticalScrollIndicator = false
collectionView.showsHorizontalScrollIndicator = false
collectionView.alwaysBounceVertical = true
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(
VStoreCell.self,
forCellWithReuseIdentifier:
VStoreCell.reusableIdentifier)
collectionView.register(
VStoreHeader.self,
forSupplementaryViewOfKind:UICollectionElementKindSectionHeader,
withReuseIdentifier:
VStoreHeader.reusableIdentifier)
collectionView.register(
VStoreFooter.self,
forSupplementaryViewOfKind:UICollectionElementKindSectionFooter,
withReuseIdentifier:
VStoreFooter.reusableIdentifier)
self.collectionView = collectionView
addSubview(collectionView)
addSubview(viewSpinner)
let views:[String:UIView] = [
"viewSpinner":viewSpinner,
"collectionView":collectionView]
let metrics:[String:CGFloat] = [
"barHeight":barHeight]
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-0-[viewSpinner]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-0-[collectionView]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-(barHeight)-[viewSpinner]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-(barHeight)-[collectionView]-0-|",
options:[],
metrics:metrics,
views:views))
storeLoaded()
NotificationCenter.default.addObserver(
self,
selector:#selector(notifiedStoreLoaded(sender:)),
name:Notification.storeLoaded,
object:nil)
}
required init?(coder:NSCoder)
{
fatalError()
}
override func layoutSubviews()
{
collectionView.collectionViewLayout.invalidateLayout()
super.layoutSubviews()
}
//MARK: notified
func notifiedStoreLoaded(sender notification:Notification)
{
DispatchQueue.main.async
{ [weak self] in
self?.storeLoaded()
}
}
//MARK: private
private func storeLoaded()
{
collectionView.reloadData()
arrayKeys = Array(MStore.sharedInstance.purchase.mapItems.keys)
if arrayKeys.count == 0 && MStore.sharedInstance.error == nil
{
collectionView.isHidden = true
viewSpinner.startAnimating()
}
else
{
collectionView.isHidden = false
viewSpinner.stopAnimating()
}
}
private func modelAtIndex(index:IndexPath) -> MStorePurchaseItem
{
let itemKey:String = arrayKeys[index.item]
let item:MStorePurchaseItem = MStore.sharedInstance.purchase.mapItems[itemKey]!
return item
}
//MARK: public
func showLoading()
{
viewSpinner.startAnimating()
}
//MARK: collection delegate
func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, referenceSizeForHeaderInSection section:Int) -> CGSize
{
let size:CGSize
if arrayKeys.count > 0 && MStore.sharedInstance.error == nil
{
size = CGSize(width:0, height:kHeaderSize)
}
else
{
size = CGSize.zero
}
return size
}
func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, referenceSizeForFooterInSection section:Int) -> CGSize
{
let size:CGSize
if MStore.sharedInstance.error == nil
{
size = CGSize.zero
}
else
{
size = CGSize(width:0, height:kFooterSize)
}
return size
}
func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAt indexPath:IndexPath) -> CGSize
{
let width:CGFloat = collectionView.bounds.maxX
let size:CGSize = CGSize(width:width, height:kCellSize)
return size
}
func numberOfSections(in collectionView:UICollectionView) -> Int
{
return 1
}
func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section:Int) -> Int
{
let count:Int
if MStore.sharedInstance.error == nil
{
count = MStore.sharedInstance.purchase.mapItems.count
}
else
{
count = 0
}
return count
}
func collectionView(_ collectionView:UICollectionView, viewForSupplementaryElementOfKind kind:String, at indexPath:IndexPath) -> UICollectionReusableView
{
let reusableView:UICollectionReusableView
if kind == UICollectionElementKindSectionHeader
{
reusableView = collectionView.dequeueReusableSupplementaryView(
ofKind:kind,
withReuseIdentifier:VStoreHeader.reusableIdentifier,
for:indexPath)
}
else
{
let errorString:String? = MStore.sharedInstance.error
let footer:VStoreFooter = collectionView.dequeueReusableSupplementaryView(
ofKind:kind,
withReuseIdentifier:VStoreFooter.reusableIdentifier,
for:indexPath) as! VStoreFooter
footer.showError(errorString:errorString)
reusableView = footer
}
return reusableView
}
func collectionView(_ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell
{
let item:MStorePurchaseItem = modelAtIndex(index:indexPath)
let cell:VStoreCell = collectionView.dequeueReusableCell(
withReuseIdentifier:
VStoreCell.reusableIdentifier,
for:indexPath) as! VStoreCell
cell.config(model:item)
return cell
}
func collectionView(_ collectionView:UICollectionView, shouldSelectItemAt indexPath:IndexPath) -> Bool
{
return false
}
func collectionView(_ collectionView:UICollectionView, shouldHighlightItemAt indexPath:IndexPath) -> Bool
{
return false
}
}
| mit | f248d8d4eceb04063ea5eafb08368eae | 30.682657 | 165 | 0.625204 | 6.168103 | false | false | false | false |
hollance/swift-algorithm-club | Introsort/Introsort.playground/Sources/InsertionSort.swift | 6 | 781 | import Foundation
public func insertionSort<T>(for array: inout [T], range: Range<Int>, by areInIncreasingOrder: (T, T) -> Bool) {
guard !range.isEmpty else { return }
let start = range.lowerBound
var sortedEnd = start
array.formIndex(after: &sortedEnd)
while sortedEnd != range.upperBound {
let x = array[sortedEnd]
var i = sortedEnd
repeat {
let predecessor = array[array.index(before: i)]
guard areInIncreasingOrder(x, predecessor) else { break }
array[i] = predecessor
array.formIndex(before: &i)
} while i != start
if i != sortedEnd {
array[i] = x
}
array.formIndex(after: &sortedEnd)
}
}
| mit | e39017276439bfa8fccd1c341a857ae2 | 26.892857 | 112 | 0.555698 | 4.38764 | false | false | false | false |
bjvanlinschoten/Pala | Pala/Pala/EventsViewController.swift | 1 | 6866 | //
// EventsViewController.swift
// Pala
//
// Created by Boris van Linschoten on 07-06-15.
// Copyright (c) 2015 bjvanlinschoten. All rights reserved.
//
import UIKit
class EventsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
// Properties
var wallViewController: WallCollectionViewController?
var wallUserArray: [Person]?
var wall: Wall?
var currentUser: User?
var refreshControl: UIRefreshControl!
@IBOutlet var eventsTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false
self.wall = Wall()
// Pull to refresh
self.refreshControl = UIRefreshControl()
self.refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
self.refreshControl.addTarget(self, action: "refreshEventsTable", forControlEvents: UIControlEvents.ValueChanged)
self.eventsTable.addSubview(self.refreshControl)
// Navigation bar appearance
self.navigationController?.navigationBar.barTintColor = UIColor(hexString: "FF7400")
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
self.title = "Menu"
// Get data for table and reload
self.currentUser?.getUserEvents() { () -> Void in
self.eventsTable.reloadData()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Refresh events
func refreshEventsTable() {
self.currentUser?.getUserEvents() { () -> Void in
self.eventsTable.reloadData()
self.refreshControl.endRefreshing()
}
}
// Gender selecton
@IBAction func genderSelectChange(sender: UISegmentedControl) {
if self.wall!.selectedEvent != nil {
MBProgressHUD.showHUDAddedTo(self.wallViewController?.view, animated: true)
self.wall!.selectedGender = sender.selectedSegmentIndex
self.wallViewController?.wall = self.wall!
self.wallViewController?.appearsFromEventSelect()
self.closeLeft()
} else {
self.wall!.selectedGender = sender.selectedSegmentIndex
}
}
// MARK: TableView Delegate methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 1
} else {
if let user = self.currentUser {
if let events = user.events {
return events.count
}
}
return 0
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0 {
// Make header cell
let cell = tableView.dequeueReusableCellWithIdentifier("headerCell", forIndexPath: indexPath) as! HeaderCell
let id = self.currentUser?.parseUser["facebookId"] as! NSString
// Set profile picture
let picURL: NSURL! = NSURL(string: "https://graph.facebook.com/\(id)/picture?width=600&height=600")
cell.profilePicture.sd_setImageWithURL(picURL)
cell.profilePicture.layer.masksToBounds = false
cell.profilePicture.layer.shadowOpacity = 0.3
cell.profilePicture.layer.shadowRadius = 1.0
cell.profilePicture.layer.shadowOffset = CGSize(width: 2, height: 2)
// Set label with name and age
if let age = self.currentUser?.getUserAge() as NSInteger! {
if let name = self.currentUser?.parseUser.valueForKey("name") as? String {
cell.nameLabel.text = "\(name) (\(age))"
}
}
// Get initial gender value
self.wall!.selectedGender = cell.genderSelect.selectedSegmentIndex
// Cell not selectable
cell.selectionStyle = UITableViewCellSelectionStyle.None
return cell
} else {
let cell = tableView.dequeueReusableCellWithIdentifier("eventCell", forIndexPath: indexPath) as! EventsTableViewCell
// Event for this cell
let event = self.currentUser!.events?[indexPath.row] as! NSDictionary
let eventId = event["id"] as! String
// Set event picutre
let picURL: NSURL! = NSURL(string: "https://graph.facebook.com/\(eventId)/picture?width=600&height=600")
cell.eventImageView.sd_setImageWithURL(picURL)
cell.eventImageView.layer.masksToBounds = true
cell.eventImageView.layer.cornerRadius = 4
// Set appearance of cell
cell.eventView.layer.masksToBounds = false
cell.eventView.layer.shadowOpacity = 0.3
cell.eventView.layer.shadowRadius = 1.0
cell.eventView.layer.shadowOffset = CGSize(width: 2, height: 2)
// Set label with event title
cell.eventLabel.text = event["name"] as? String
return cell
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.section == 1 {
// Loading
MBProgressHUD.showHUDAddedTo(self.wallViewController?.view, animated: true)
// Selected event
let selectedEvent = self.currentUser?.events?[indexPath.row] as! NSDictionary
// Pass information to wall and go there
self.wall!.currentUser = self.currentUser
self.wall!.selectedEvent = selectedEvent
self.wallViewController!.wall = self.wall
self.wallViewController!.appearsFromEventSelect()
self.closeLeft()
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return "Menu"
} else {
return "Events"
}
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.section == 0 {
return 280
} else {
return 75
}
}
}
| mit | 5727388e34fb2dca85df680d19d566c9 | 35.328042 | 128 | 0.60268 | 5.488409 | false | false | false | false |
airbnb/lottie-ios | Sources/Private/CoreAnimation/Layers/ShapeLayer.swift | 2 | 13938 | // Created by Cal Stephens on 12/14/21.
// Copyright © 2021 Airbnb Inc. All rights reserved.
import QuartzCore
// MARK: - ShapeLayer
/// The CALayer type responsible for rendering `ShapeLayerModel`s
final class ShapeLayer: BaseCompositionLayer {
// MARK: Lifecycle
init(shapeLayer: ShapeLayerModel, context: LayerContext) throws {
self.shapeLayer = shapeLayer
super.init(layerModel: shapeLayer)
try setUpGroups(context: context)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Called by CoreAnimation to create a shadow copy of this layer
/// More details: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init
override init(layer: Any) {
guard let typedLayer = layer as? Self else {
fatalError("\(Self.self).init(layer:) incorrectly called with \(type(of: layer))")
}
shapeLayer = typedLayer.shapeLayer
super.init(layer: typedLayer)
}
// MARK: Private
private let shapeLayer: ShapeLayerModel
private func setUpGroups(context: LayerContext) throws {
// If the layer has a `Repeater`, the `Group`s are duplicated and offset
// based on the copy count of the repeater.
if let repeater = shapeLayer.items.first(where: { $0 is Repeater }) as? Repeater {
try setUpRepeater(repeater, context: context)
} else {
try setupGroups(from: shapeLayer.items, parentGroup: nil, parentGroupPath: [], context: context)
}
}
private func setUpRepeater(_ repeater: Repeater, context: LayerContext) throws {
let items = shapeLayer.items.filter { !($0 is Repeater) }
let copyCount = Int(try repeater.copies.exactlyOneKeyframe(context: context, description: "repeater copies").value)
for index in 0..<copyCount {
for groupLayer in try makeGroupLayers(from: items, parentGroup: nil, parentGroupPath: [], context: context) {
let repeatedLayer = RepeaterLayer(repeater: repeater, childLayer: groupLayer, index: index)
addSublayer(repeatedLayer)
}
}
}
}
// MARK: - GroupLayer
/// The CALayer type responsible for rendering `Group`s
final class GroupLayer: BaseAnimationLayer {
// MARK: Lifecycle
init(group: Group, items: [ShapeItemLayer.Item], groupPath: [String], context: LayerContext) throws {
self.group = group
self.items = items
self.groupPath = groupPath
super.init()
try setupLayerHierarchy(context: context)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Called by CoreAnimation to create a shadow copy of this layer
/// More details: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init
override init(layer: Any) {
guard let typedLayer = layer as? Self else {
fatalError("\(Self.self).init(layer:) incorrectly called with \(type(of: layer))")
}
group = typedLayer.group
items = typedLayer.items
groupPath = typedLayer.groupPath
super.init(layer: typedLayer)
}
// MARK: Internal
override func setupAnimations(context: LayerAnimationContext) throws {
try super.setupAnimations(context: context)
if let (shapeTransform, context) = nonGroupItems.first(ShapeTransform.self, context: context) {
try addTransformAnimations(for: shapeTransform, context: context)
try addOpacityAnimation(for: shapeTransform, context: context)
}
}
// MARK: Private
private let group: Group
/// `ShapeItemLayer.Item`s rendered by this `Group`
/// - In the original `ShapeLayer` data model, these items could have originated from a different group
private let items: [ShapeItemLayer.Item]
/// The keypath that represents this group, with respect to the parent `ShapeLayer`
/// - Due to the way `GroupLayer`s are setup, the original `ShapeItem`
/// hierarchy from the `ShapeLayer` data model may no longer exactly
/// match the hierarchy of `GroupLayer` / `ShapeItemLayer`s constructed
/// at runtime. Since animation keypaths need to match the original
/// structure of the `ShapeLayer` data model, we track that info here.
private let groupPath: [String]
/// `ShapeItem`s (other than nested `Group`s) that are rendered by this layer
private lazy var nonGroupItems = items.filter { !($0.item is Group) }
private func setupLayerHierarchy(context: LayerContext) throws {
// Groups can contain other groups, so we may have to continue
// recursively creating more `GroupLayer`s
try setupGroups(from: group.items, parentGroup: group, parentGroupPath: groupPath, context: context)
// Create `ShapeItemLayer`s for each subgroup of shapes that should be rendered as a single unit
// - These groups are listed from front-to-back, so we have to add the sublayers in reverse order
for shapeRenderGroup in nonGroupItems.shapeRenderGroups.reversed() {
// When there are multiple path-drawing items, they're supposed to be rendered
// in a single `CAShapeLayer` (instead of rendering them in separate layers) so
// `CAShapeLayerFillRule.evenOdd` can be applied correctly if the paths overlap.
// Since a `CAShapeLayer` only supports animating a single `CGPath` from a single `KeyframeGroup<BezierPath>`,
// this requires combining all of the path-drawing items into a single set of keyframes.
if
shapeRenderGroup.pathItems.count > 1,
// We currently only support this codepath for `Shape` items that directly contain bezier path keyframes.
// We could also support this for other path types like rectangles, ellipses, and polygons with more work.
shapeRenderGroup.pathItems.allSatisfy({ $0.item is Shape }),
// `Trim`s are currently only applied correctly using individual `ShapeItemLayer`s,
// because each path has to be trimmed separately.
!shapeRenderGroup.otherItems.contains(where: { $0.item is Trim })
{
let allPathKeyframes = shapeRenderGroup.pathItems.compactMap { ($0.item as? Shape)?.path }
let combinedShape = CombinedShapeItem(
shapes: Keyframes.combined(allPathKeyframes),
name: group.name)
let sublayer = try ShapeItemLayer(
shape: ShapeItemLayer.Item(item: combinedShape, groupPath: shapeRenderGroup.pathItems[0].groupPath),
otherItems: shapeRenderGroup.otherItems,
context: context)
addSublayer(sublayer)
}
// Otherwise, if each `ShapeItem` that draws a `GGPath` animates independently,
// we have to create a separate `ShapeItemLayer` for each one. This may render
// incorrectly if there are multiple paths that overlap with each other.
else {
for pathDrawingItem in shapeRenderGroup.pathItems {
let sublayer = try ShapeItemLayer(
shape: pathDrawingItem,
otherItems: shapeRenderGroup.otherItems,
context: context)
addSublayer(sublayer)
}
}
}
}
}
extension CALayer {
/// Sets up `GroupLayer`s for each `Group` in the given list of `ShapeItem`s
/// - Each `Group` item becomes its own `GroupLayer` sublayer.
/// - Other `ShapeItem` are applied to all sublayers
fileprivate func setupGroups(
from items: [ShapeItem],
parentGroup: Group?,
parentGroupPath: [String],
context: LayerContext)
throws
{
let groupLayers = try makeGroupLayers(
from: items,
parentGroup: parentGroup,
parentGroupPath: parentGroupPath,
context: context)
for groupLayer in groupLayers {
addSublayer(groupLayer)
}
}
/// Creates a `GroupLayer` for each `Group` in the given list of `ShapeItem`s
/// - Each `Group` item becomes its own `GroupLayer` sublayer.
/// - Other `ShapeItem` are applied to all sublayers
fileprivate func makeGroupLayers(
from items: [ShapeItem],
parentGroup: Group?,
parentGroupPath: [String],
context: LayerContext)
throws -> [GroupLayer]
{
var (groupItems, otherItems) = items
.filter { !$0.hidden }
.grouped(by: { $0 is Group })
// If this shape doesn't have any groups but just has top-level shape items,
// we can create a placeholder group with those items. (Otherwise the shape items
// would be silently ignored, since we expect all shape layers to have a top-level group).
if groupItems.isEmpty, parentGroup == nil {
groupItems = [Group(items: otherItems, name: "")]
otherItems = []
}
// `ShapeItem`s either draw a path, or modify how a path is rendered.
// - If this group doesn't have any items that draw a path, then its
// items are applied to all of this group's children.
let inheritedItemsForChildGroups: [ShapeItemLayer.Item]
if !otherItems.contains(where: { $0.drawsCGPath }) {
inheritedItemsForChildGroups = otherItems.map {
ShapeItemLayer.Item(item: $0, groupPath: parentGroupPath)
}
} else {
inheritedItemsForChildGroups = []
}
// Groups are listed from front to back,
// but `CALayer.sublayers` are listed from back to front.
let groupsInZAxisOrder = groupItems.reversed()
return try groupsInZAxisOrder.compactMap { group in
guard let group = group as? Group else { return nil }
var pathForChildren = parentGroupPath
if !group.name.isEmpty {
pathForChildren.append(group.name)
}
let childItems = group.items
.filter { !$0.hidden }
.map { ShapeItemLayer.Item(item: $0, groupPath: pathForChildren) }
return try GroupLayer(
group: group,
items: childItems + inheritedItemsForChildGroups,
groupPath: pathForChildren,
context: context)
}
}
}
extension ShapeItem {
/// Whether or not this `ShapeItem` is responsible for rendering a `CGPath`
var drawsCGPath: Bool {
switch type {
case .ellipse, .rectangle, .shape, .star:
return true
case .fill, .gradientFill, .group, .gradientStroke, .merge,
.repeater, .round, .stroke, .trim, .transform, .unknown:
return false
}
}
/// Whether or not this `ShapeItem` provides a fill for a set of shapes
var isFill: Bool {
switch type {
case .fill, .gradientFill:
return true
case .ellipse, .rectangle, .shape, .star, .group, .gradientStroke,
.merge, .repeater, .round, .stroke, .trim, .transform, .unknown:
return false
}
}
/// Whether or not this `ShapeItem` provides a stroke for a set of shapes
var isStroke: Bool {
switch type {
case .stroke, .gradientStroke:
return true
case .ellipse, .rectangle, .shape, .star, .group, .gradientFill,
.merge, .repeater, .round, .fill, .trim, .transform, .unknown:
return false
}
}
}
extension Collection {
/// Splits this collection into two groups, based on the given predicate
func grouped(by predicate: (Element) -> Bool) -> (trueElements: [Element], falseElements: [Element]) {
var trueElements = [Element]()
var falseElements = [Element]()
for element in self {
if predicate(element) {
trueElements.append(element)
} else {
falseElements.append(element)
}
}
return (trueElements, falseElements)
}
}
// MARK: - ShapeRenderGroup
/// A group of `ShapeItem`s that should be rendered together as a single unit
struct ShapeRenderGroup {
/// The items in this group that render `CGPath`s
var pathItems: [ShapeItemLayer.Item] = []
/// Shape items that modify the appearance of the shapes rendered by this group
var otherItems: [ShapeItemLayer.Item] = []
}
extension Array where Element == ShapeItemLayer.Item {
/// Splits this list of `ShapeItem`s into groups that should be rendered together as individual units
var shapeRenderGroups: [ShapeRenderGroup] {
var renderGroups = [ShapeRenderGroup()]
for item in self {
// `renderGroups` is non-empty, so is guaranteed to have a valid end index
let lastIndex = renderGroups.indices.last!
if item.item.drawsCGPath {
renderGroups[lastIndex].pathItems.append(item)
}
// `Fill` items are unique, because they specifically only apply to _previous_ shapes in a `Group`
// - For example, with [Rectangle, Fill(Red), Circle, Fill(Blue)], the Rectangle should be Red
// but the Circle should be Blue.
// - To handle this, we create a new `ShapeRenderGroup` when we encounter a `Fill` item
else if item.item.isFill {
renderGroups[lastIndex].otherItems.append(item)
renderGroups.append(ShapeRenderGroup())
}
// Other items in the list are applied to all subgroups
else {
for index in renderGroups.indices {
renderGroups[index].otherItems.append(item)
}
}
}
// `Fill` and `Stroke` items have an `alpha` property that can be animated separately,
// but each layer only has a single `opacity` property, so we have to create
// separate layers / render groups for each of these if necessary.
return renderGroups.flatMap { group -> [ShapeRenderGroup] in
let (strokesAndFills, otherItems) = group.otherItems.grouped(by: { $0.item.isFill || $0.item.isStroke })
// However, if all of the strokes / fills have the exact same opacity animation configuration,
// then we can continue using a single layer / render group.
let allAlphaAnimationsAreIdentical = strokesAndFills.allSatisfy { item in
(item.item as? OpacityAnimationModel)?.opacity
== (strokesAndFills.first?.item as? OpacityAnimationModel)?.opacity
}
if allAlphaAnimationsAreIdentical {
return [group]
}
// Create a new group for each stroke / fill
return strokesAndFills.map { strokeOrFill in
ShapeRenderGroup(
pathItems: group.pathItems,
otherItems: [strokeOrFill] + otherItems)
}
}
}
}
| apache-2.0 | 9f8b9e576c7a9f61a32b52c811e68843 | 35.773087 | 119 | 0.682715 | 4.227176 | false | false | false | false |
tonyli508/ObjectStorage | ObjectStorage/ObjectStorage/CoreData/CoreDataHelper.swift | 1 | 5165 | //
// CoreDataHelper.swift
// ObjectStorage
//
// Created by Li Jiantang on 26/03/2015.
// Copyright (c) 2015 Carma. All rights reserved.
//
import CoreData
class CoreDataHelper: NSObject{
var store: CoreDataStore!
init(cdstore: CoreDataStore) {
super.init()
self.store = cdstore
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CoreDataHelper.contextDidSaveContext(_:)), name: NSManagedObjectContextDidSaveNotification, object: self.backgroundContext)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CoreDataHelper.contextDidSaveContext(_:)), name: NSManagedObjectContextDidSaveNotification, object: self.managedObjectContext)
}
deinit{
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// #pragma mark - Core Data stack
// Returns the managed object context for the application.
// Normally, you can use it to do anything.
// But for bulk data update, acording to Florian Kugler's blog about core data performance, [Concurrent Core Data Stacks – Performance Shootout](http://floriankugler.com/blog/2013/4/29/concurrent-core-data-stack-performance-shootout) and [Backstage with Nested Managed Object Contexts](http://floriankugler.com/blog/2013/5/11/backstage-with-nested-managed-object-contexts). We should better write data in background context. and read data from main queue context.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
// main thread context
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.store.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// Returns the background object context for the application.
// You can use it to process bulk data update in background.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
lazy var backgroundContext: 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.store.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var backgroundContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.PrivateQueueConcurrencyType)
backgroundContext.persistentStoreCoordinator = coordinator
return backgroundContext
}()
// save NSManagedObjectContext
func saveContext (context: NSManagedObjectContext) {
if context.hasChanges {
do {
try context.save()
} catch {
print("Save encounter unresolved error: \(error)")
/// if in debug mode, crash to notify the developer to debug this error
#if DEBUG
abort()
#endif
}
}
}
func saveContext() {
if let context = self.backgroundContext {
self.saveContext(context)
}
}
// call back function by saveContext, support multi-thread
func contextDidSaveContext(notification: NSNotification) {
let sender = notification.object as! NSManagedObjectContext
if sender === self.managedObjectContext {
self.backgroundContext?.performBlock {
self.backgroundContext?.mergeChangesFromContextDidSaveNotification(notification)
}
} else if sender === self.backgroundContext {
self.managedObjectContext?.performBlock {
self.managedObjectContext?.mergeChangesFromContextDidSaveNotification(notification)
}
} else {
dispatch_async(dispatch_get_main_queue()) { [unowned self] in
self.managedObjectContext?.performBlock {
self.managedObjectContext?.mergeChangesFromContextDidSaveNotification(notification)
}
}
dispatch_async(dispatch_get_main_queue()) { [unowned self] in
self.backgroundContext?.performBlock {
self.backgroundContext?.mergeChangesFromContextDidSaveNotification(notification)
}
}
}
}
}
| mit | 5c303426884868c09602b57af07c49a5 | 45.936364 | 467 | 0.680806 | 5.927669 | false | false | false | false |
ACChe/eidolon | Kiosk/ListingsCollectionViewCell.swift | 1 | 6935 | import Foundation
import Artsy_UILabels
import ReactiveCocoa
class ListingsCollectionViewCell: UICollectionViewCell {
typealias DownloadImageClosure = (url: NSURL?, imageView: UIImageView) -> ()
typealias CancelDownloadImageClosure = (imageView: UIImageView) -> ()
dynamic let lotNumberLabel = ListingsCollectionViewCell._sansSerifLabel()
dynamic let artworkImageView = ListingsCollectionViewCell._artworkImageView()
dynamic let artistNameLabel = ListingsCollectionViewCell._largeLabel()
dynamic let artworkTitleLabel = ListingsCollectionViewCell._italicsLabel()
dynamic let estimateLabel = ListingsCollectionViewCell._normalLabel()
dynamic let currentBidLabel = ListingsCollectionViewCell._boldLabel()
dynamic let numberOfBidsLabel = ListingsCollectionViewCell._rightAlignedNormalLabel()
dynamic let bidButton = ListingsCollectionViewCell._bidButton()
dynamic let moreInfoLabel = ListingsCollectionViewCell._infoLabel()
var downloadImage: DownloadImageClosure?
var cancelDownloadImage: CancelDownloadImageClosure?
lazy var moreInfoSignal: RACSignal = {
// "Jump start" both the more info button signal and the image gesture signal with nil values,
// then skip the first "jump started" value.
RACSignal.combineLatest([self.infoGestureSignal.startWith(nil), self.imageGestureSigal.startWith(nil)]).mapReplace(nil).skip(1)
}()
private lazy var imageGestureSigal: RACSignal = {
let recognizer = UITapGestureRecognizer()
self.artworkImageView.addGestureRecognizer(recognizer)
self.artworkImageView.userInteractionEnabled = true
return recognizer.rac_gestureSignal()
}()
private lazy var infoGestureSignal: RACSignal = {
let recognizer = UITapGestureRecognizer()
self.moreInfoLabel.addGestureRecognizer(recognizer)
self.moreInfoLabel.userInteractionEnabled = true
return recognizer.rac_gestureSignal()
}()
lazy var viewModelSignal: RACSignal = {
return RACObserve(self, "viewModel").ignore(nil)
}()
dynamic var viewModel: SaleArtworkViewModel!
dynamic var bidWasPressedSignal: RACSignal = RACSubject()
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override func prepareForReuse() {
super.prepareForReuse()
cancelDownloadImage?(imageView: artworkImageView)
}
func setup() {
// Necessary to use Autolayout
contentView.translatesAutoresizingMaskIntoConstraints = false
// Bind subviews
// Start with things not expected to ever change.
RAC(self, "lotNumberLabel.text") <~ viewModelSignal.map { (viewModel) -> AnyObject! in
return (viewModel as! SaleArtworkViewModel).lotNumberSignal
}.switchToLatest()
viewModelSignal.subscribeNext { [weak self] (viewModel) -> Void in
if let imageView = self?.artworkImageView {
let url = (viewModel as? SaleArtworkViewModel)?.thumbnailURL
self?.downloadImage?(url: url, imageView: imageView)
}
}
RAC(self, "artistNameLabel.text") <~ viewModelSignal.map({ (viewModel) -> AnyObject! in
return (viewModel as! SaleArtworkViewModel).artistName
}).mapNilToEmptyString()
RAC(self, "artworkTitleLabel.attributedText") <~ viewModelSignal.map({ (viewModel) -> AnyObject! in
return (viewModel as! SaleArtworkViewModel).titleAndDateAttributedString
}).mapNilToEmptyAttributedString()
RAC(self, "estimateLabel.text") <~ viewModelSignal.map({ (viewModel) -> AnyObject! in
return (viewModel as! SaleArtworkViewModel).estimateString
}).mapNilToEmptyString()
// Now do properties that _do_ change.
RAC(self, "currentBidLabel.text") <~ viewModelSignal.map({ (viewModel) -> AnyObject! in
return (viewModel as! SaleArtworkViewModel).currentBidSignal(prefix: "Current Bid: ", missingPrefix: "Starting Bid: ")
}).switchToLatest().mapNilToEmptyString()
RAC(self, "numberOfBidsLabel.text") <~ viewModelSignal.map { (viewModel) -> AnyObject! in
return (viewModel as! SaleArtworkViewModel).numberOfBidsSignal
}.switchToLatest().mapNilToEmptyString()
RAC(self.bidButton, "enabled") <~ viewModelSignal.map { (viewModel) -> AnyObject! in
return (viewModel as! SaleArtworkViewModel).forSaleSignal
}.switchToLatest().doNext { [weak bidButton] (forSale) -> Void in
// Button titles aren't KVO-able
let forSale = forSale as! Bool
let title = forSale ? "BID" : "SOLD"
bidButton?.setTitle(title, forState: .Normal)
}
bidButton.rac_signalForControlEvents(.TouchUpInside).subscribeNext { [weak self] (_) -> Void in
(self?.bidWasPressedSignal as! RACSubject).sendNext(nil)
}
}
}
private extension ListingsCollectionViewCell {
// Mark: UIView-property-methods – need an _ prefix to appease the compiler ¯\_(ツ)_/¯
class func _artworkImageView() -> UIImageView {
let imageView = UIImageView()
imageView.backgroundColor = .artsyLightGrey()
return imageView
}
class func _rightAlignedNormalLabel() -> UILabel {
let label = _normalLabel()
label.textAlignment = .Right
label.numberOfLines = 1
return label
}
class func _normalLabel() -> UILabel {
let label = ARSerifLabel()
label.font = label.font.fontWithSize(16)
label.numberOfLines = 1
return label
}
class func _sansSerifLabel() -> UILabel {
let label = ARSansSerifLabel()
label.font = label.font.fontWithSize(12)
label.numberOfLines = 1
return label
}
class func _italicsLabel() -> UILabel {
let label = ARItalicsSerifLabel()
label.font = label.font.fontWithSize(16)
label.numberOfLines = 1
return label
}
class func _largeLabel() -> UILabel {
let label = _normalLabel()
label.font = label.font.fontWithSize(20)
return label
}
class func _bidButton() -> ActionButton {
let button = ActionButton()
button.setTitle("BID", forState: .Normal)
return button
}
class func _boldLabel() -> UILabel {
let label = _normalLabel()
label.font = UIFont.serifBoldFontWithSize(label.font.pointSize)
label.numberOfLines = 1
return label
}
class func _infoLabel() -> UILabel {
let label = ARSansSerifLabelWithChevron()
label.tintColor = .blackColor()
label.text = "MORE INFO"
return label
}
}
| mit | d02a2a781e070febb0ca7b3e126cb42b | 36.863388 | 135 | 0.660557 | 5.221552 | false | false | false | false |
JeffESchmitz/RideNiceRide | RideNiceRide/ViewControllers/SlideMenu/MainViewController.swift | 1 | 4064 | //
// MainViewController.swift
// RideNiceRide
//
// Created by Jeff Schmitz on 11/9/16.
// Copyright © 2016 Jeff Schmitz. All rights reserved.
//
import UIKit
import SlideMenuControllerSwift
import Willow
import ISHPullUp
import ReachabilitySwift
class MainViewController: ISHPullUpViewController, PullUpViewDelegate {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
commonInit()
}
fileprivate func commonInit() {
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
// swiftlint:disable force_cast
let contentVC = storyBoard.instantiateViewController(withIdentifier: "content") as! ContentViewController
let bottomVC = storyBoard.instantiateViewController(withIdentifier: "bottom") as! BottomViewController
// swiftlint:enable force_cast
contentViewController = contentVC
bottomViewController = bottomVC
contentVC.pullUpViewDelegate = self
contentVC.panoramaViewDelegate = bottomVC
bottomVC.pullUpController = self
bottomVC.manageFavoriteDelegate = contentVC
contentDelegate = contentVC
sizingDelegate = bottomVC
stateDelegate = bottomVC
}
// Mark: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = "Map"
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.setNavigationBarItem()
let refresh = UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(refreshButtonHandler))
self.navigationItem.rightBarButtonItem = refresh
ReachabilityManager.shared.addListener(listener: self)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
ReachabilityManager.shared.removeListener(listener: self)
}
// MARK: - PullUpViewDelegate
func setPullUpViewHeight(bottomHeight: CGFloat, animated: Bool) {
self.setBottomHeight(bottomHeight, animated: animated)
}
func refreshButtonHandler() {
log.warn("Inside \(#function)")
(self.contentViewController as? ContentViewController)?.reloadStationsOnMapView()
}
}
// MARK: - SlideMenuControllerDelegate
extension MainViewController: SlideMenuControllerDelegate {
func leftWillOpen() {
log.event("SlideMenuControllerDelegate: leftWillOpen")
}
func leftDidOpen() {
log.event("SlideMenuControllerDelegate: leftDidOpen")
}
func leftWillClose() {
log.event("SlideMenuControllerDelegate: leftWillClose")
}
func leftDidClose() {
log.event("SlideMenuControllerDelegate: leftDidClose")
}
func rightWillOpen() {
log.event("SlideMenuControllerDelegate: rightWillOpen")
}
func rightDidOpen() {
log.event("SlideMenuControllerDelegate: rightDidOpen")
}
func rightWillClose() {
log.event("SlideMenuControllerDelegate: rightWillClose")
}
func rightDidClose() {
log.event("SlideMenuControllerDelegate: rightDidClose")
}
}
// MARK: - NetworkStatusListener
extension MainViewController: NetworkStatusListener {
func networkStatusDidChange(status: Reachability.NetworkStatus) {
switch status {
case .notReachable:
debugPrint("MainViewController: Network became unreachable")
self.navigationItem.rightBarButtonItem?.isEnabled = false
case .reachableViaWiFi:
debugPrint("MainViewController: Network reachable through WiFi")
self.navigationItem.rightBarButtonItem?.isEnabled = true
case .reachableViaWWAN:
debugPrint("MainViewController: Network reachable through Cellular Data")
self.navigationItem.rightBarButtonItem?.isEnabled = true
}
// Update any UI elements here (disable buttons, labels etc.)
}
}
| mit | 283c27e2a5e72a266d1f087d329a038d | 29.548872 | 119 | 0.747231 | 4.960928 | false | false | false | false |
weareyipyip/SwiftStylable | Sources/SwiftStylable/Classes/View/Components/ExtendedButton.swift | 1 | 26213 | //
// ExtendedButton.swift
// YipYipSwift
//
// Created by Marcel Bloemendaal on 08/01/15.
// Copyright (c) 2015 Marcel Bloemendaal. All rights reserved.
//
import Foundation
import UIKit
@IBDesignable open class ExtendedButton: UIButton {
private var _normalBackgroundColor:UIColor?
private var _highlightedBackgroundColor:UIColor?
private var _selectedBackgroundColor:UIColor?
private var _disabledBackgroundColor:UIColor?
private var _normalBorderColor:UIColor?
private var _highlightedBorderColor:UIColor?
private var _selectedBorderColor:UIColor?
private var _disabledBorderColor:UIColor?
private var _normalTitle:String?
private var _highlightedTitle:String?
private var _selectedTitle:String?
private var _disabledTitle:String?
private var _customHorizontalTitleAlignment:UIControl.ContentHorizontalAlignment = .center
private var _customVerticalTitleAlignment:UIControl.ContentVerticalAlignment = .center
private var _customHorizontalImageAlignment:UIControl.ContentHorizontalAlignment = .center
private var _customVerticalImageAlignment:UIControl.ContentVerticalAlignment = .center
private var _defaultHorizontalContentAlignment = UIControl.ContentHorizontalAlignment.center
private var _defaultVerticalContentAlignment = UIControl.ContentVerticalAlignment.center
// -----------------------------------------------------------------------------------------------------------------------
//
// MARK: - Initializers
//
// -----------------------------------------------------------------------------------------------------------------------
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self._init()
}
public required override init(frame: CGRect) {
super.init(frame: frame)
self._init()
}
// -----------------------------------------------------------------------------------------------------------------------
//
// MARK: Properties
//
// -----------------------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------
// MARK: -- Layout
// -----------------------------------------------------------
@IBInspectable override open var contentHorizontalAlignment: UIControl.ContentHorizontalAlignment {
get {
return super.contentHorizontalAlignment
}
set {
self._defaultHorizontalContentAlignment = newValue
if !self.customItemPlacement {
super.contentHorizontalAlignment = newValue
}
}
}
@IBInspectable override open var contentVerticalAlignment: UIControl.ContentVerticalAlignment {
get {
return super.contentVerticalAlignment
}
set {
self._defaultVerticalContentAlignment = newValue
if !self.customItemPlacement {
super.contentVerticalAlignment = newValue
}
}
}
@IBInspectable open var customItemPlacement:Bool = false {
didSet {
if self.customItemPlacement {
super.contentHorizontalAlignment = .center
super.contentVerticalAlignment = .center
} else {
self.contentHorizontalAlignment = self._defaultHorizontalContentAlignment
self.contentVerticalAlignment = self._defaultVerticalContentAlignment
}
}
}
@IBInspectable open var titlePlacementIndex:Int = 4 {
didSet {
if self.titlePlacementIndex > -1 && self.titlePlacementIndex < 9 {
switch self.titlePlacementIndex % 3 {
case 0:
self._customHorizontalTitleAlignment = .left
case 2:
self._customHorizontalTitleAlignment = .right
default:
self._customHorizontalTitleAlignment = .center
}
switch self.titlePlacementIndex / 3 {
case 0:
self._customVerticalTitleAlignment = .top
case 2:
self._customVerticalTitleAlignment = .bottom
default:
self._customVerticalTitleAlignment = .center
}
self.setNeedsLayout()
} else {
self._customHorizontalTitleAlignment = .center
self._customVerticalTitleAlignment = .center
}
}
}
@IBInspectable open var imagePlacementIndex:Int = 4 {
didSet {
if self.imagePlacementIndex > -1 && self.imagePlacementIndex < 9 {
switch self.imagePlacementIndex % 3 {
case 0:
self._customHorizontalImageAlignment = .left
case 2:
self._customHorizontalImageAlignment = .right
default:
self._customHorizontalImageAlignment = .center
}
switch self.imagePlacementIndex / 3 {
case 0:
self._customVerticalImageAlignment = .top
case 2:
self._customVerticalImageAlignment = .bottom
default:
self._customVerticalImageAlignment = .center
}
self.setNeedsLayout()
} else {
self._customHorizontalImageAlignment = .center
self._customVerticalImageAlignment = .center
}
}
}
// -----------------------------------------------------------
// MARK: -- States
// -----------------------------------------------------------
override open var isHighlighted:Bool {
didSet {
if #available(iOS 15.0, *) {
self.setNeedsUpdateConfiguration()
} else {
self.updateColors(updateImageTintColor: self.tintImageWithTitleColor)
}
}
}
override open var isSelected:Bool {
didSet {
if #available(iOS 15.0, *) {
self.setNeedsUpdateConfiguration()
} else {
self.updateColors(updateImageTintColor: self.tintImageWithTitleColor)
}
}
}
override open var isEnabled:Bool {
get {
return super.isEnabled
}
set(value) {
super.isEnabled = value
if #available(iOS 15.0, *) {
self.setNeedsUpdateConfiguration()
} else {
self.updateColors(updateImageTintColor: self.tintImageWithTitleColor)
}
}
}
@IBInspectable open var tintImageWithTitleColor:Bool = false {
didSet {
if self.tintImageWithTitleColor != oldValue {
self.updateImageRenderingModeForState(.normal)
self.updateImageRenderingModeForState(.highlighted)
self.updateImageRenderingModeForState(.selected)
self.updateImageRenderingModeForState(.disabled)
}
if #available(iOS 15.0, *) {
self.setNeedsUpdateConfiguration()
} else {
self.updateColors(updateImageTintColor: true)
}
}
}
@IBInspectable open var fullUppercaseText:Bool = false {
didSet {
if self.fullUppercaseText != oldValue {
super.setTitle(self.fullUppercaseText ? self._normalTitle?.uppercased() : self._normalTitle, for: .normal)
super.setTitle(self.fullUppercaseText ? self._highlightedTitle?.uppercased() : self._highlightedTitle, for: .highlighted)
super.setTitle(self.fullUppercaseText ? self._selectedTitle?.uppercased() : self._selectedTitle, for: .selected)
super.setTitle(self.fullUppercaseText ? self._disabledTitle?.uppercased() : self._disabledTitle, for: .disabled)
}
}
}
// -----------------------------------------------------------------------------------------------------------------------
//
// MARK: Methods
//
// -----------------------------------------------------------------------------------------------------------------------
open override func awakeFromNib() {
super.awakeFromNib()
}
// -----------------------------------------------------------
// UIButton overrides
// -----------------------------------------------------------
// -----------------------------------------------------------
// Extra state color properties
// -----------------------------------------------------------
open func setBackgroundColor(_ color:UIColor?, for state:UIControl.State)
{
switch (state)
{
case UIControl.State.normal:
_normalBackgroundColor = color
case UIControl.State.highlighted:
_highlightedBackgroundColor = color
case UIControl.State.selected:
_selectedBackgroundColor = color
case UIControl.State.disabled:
_disabledBackgroundColor = color
default:
break;
}
if #available(iOS 15.0, *) {
self.setNeedsUpdateConfiguration()
} else {
self.updateColors(updateImageTintColor: false)
}
}
open func backgroundColor(for state:UIControl.State)->UIColor? {
var color:UIColor?
switch (state)
{
case UIControl.State.normal:
color = self._normalBackgroundColor
case UIControl.State.highlighted:
color = self._highlightedBackgroundColor
case UIControl.State.selected:
color = self._selectedBackgroundColor
case UIControl.State.disabled:
color = self._disabledBackgroundColor
default:
color = nil
}
return color
}
open func setBorderColor(_ color:UIColor?, for state:UIControl.State)
{
switch (state)
{
case UIControl.State.normal:
_normalBorderColor = color
break
case UIControl.State.highlighted:
_highlightedBorderColor = color
break
case UIControl.State.selected:
_selectedBorderColor = color
break
case UIControl.State.disabled:
_disabledBorderColor = color
break
default:
break
}
if #available(iOS 15.0, *) {
self.setNeedsUpdateConfiguration()
} else {
self.updateColors(updateImageTintColor: false)
}
}
open func borderColor(for state:UIControl.State)->UIColor? {
var color:UIColor?
switch (state)
{
case UIControl.State.normal:
color = self._normalBorderColor
case UIControl.State.highlighted:
color = self._highlightedBorderColor
case UIControl.State.selected:
color = self._selectedBorderColor
case UIControl.State.disabled:
color = self._disabledBorderColor
default:
color = nil
}
return color
}
open override func setTitleColor(_ color: UIColor?, for state: UIControl.State) {
super.setTitleColor(color, for: state)
if #available(iOS 15.0, *) {
self.setNeedsUpdateConfiguration()
} else {
self.updateColors(updateImageTintColor: self.tintImageWithTitleColor && self.state == state)
}
}
open override func setImage(_ image: UIImage?, for state: UIControl.State) {
super.setImage(image, for: state)
self.updateImageRenderingModeForState(state)
if #available(iOS 15.0, *) {
self.setNeedsUpdateConfiguration()
} else {
self.updateColors(updateImageTintColor: self.tintImageWithTitleColor)
}
}
open override func setTitle(_ title: String?, for state: UIControl.State) {
switch state {
case UIControl.State.normal:
self._normalTitle = title
super.setTitle(self.fullUppercaseText ? title?.uppercased() : title, for: state)
case UIControl.State.highlighted:
self._highlightedTitle = title
super.setTitle(self.fullUppercaseText ? title?.uppercased() : title, for: state)
case UIControl.State.selected:
self._selectedTitle = title
super.setTitle(self.fullUppercaseText ? title?.uppercased() : title, for: state)
case UIControl.State.disabled:
self._disabledTitle = title
super.setTitle(self.fullUppercaseText ? title?.uppercased() : title, for: state)
default:
super.setTitle(title, for: state)
}
}
open override func title(for state: UIControl.State)->String? {
switch state {
case UIControl.State.normal:
return self._normalTitle
case UIControl.State.highlighted:
return self._highlightedTitle
case UIControl.State.selected:
return self._selectedTitle
case UIControl.State.disabled:
return self._disabledTitle
default:
return super.title(for: state)
}
}
// -----------------------------------------------------------
// MARK: -- Layout methods
// -----------------------------------------------------------
open override func titleRect(forContentRect contentRect: CGRect) -> CGRect {
if self.customItemPlacement {
let titleSize = super.titleRect(forContentRect: CGRect(x: 0.0, y: 0.0, width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)).size
var x:CGFloat = 0.0
var y:CGFloat = 0.0
let width:CGFloat = min(titleSize.width, contentRect.width)
let height:CGFloat = min(titleSize.height, contentRect.height)
switch self._customHorizontalTitleAlignment {
case .left:
x = contentRect.minX + self.titleEdgeInsets.left
case .right:
x = contentRect.maxX - width - self.titleEdgeInsets.right
default:
// Center
x = ((contentRect.minX + self.titleEdgeInsets.left) + (contentRect.maxX - self.titleEdgeInsets.right)) * 0.5 - width * 0.5
}
switch self._customVerticalTitleAlignment {
case .top:
y = contentRect.minY + self.titleEdgeInsets.top
case .bottom:
y = contentRect.maxY - height - self.titleEdgeInsets.bottom
default:
// Center
y = ((contentRect.minY + self.titleEdgeInsets.top) + (contentRect.maxY - self.titleEdgeInsets.bottom)) * 0.5 - height * 0.5
}
return CGRect(x: x,
y: y,
width: width,
height: height)
} else {
return super.titleRect(forContentRect: contentRect)
}
}
open override func imageRect(forContentRect contentRect: CGRect) -> CGRect {
if self.customItemPlacement {
let imageSize = super.imageRect(forContentRect: CGRect(x: 0.0, y: 0.0, width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)).size
var x:CGFloat = 0.0
var y:CGFloat = 0.0
let width:CGFloat = min(imageSize.width, contentRect.width)
let height:CGFloat = min(imageSize.height, contentRect.height)
switch self._customHorizontalImageAlignment {
case .left:
x = contentRect.minX + self.imageEdgeInsets.left
case .right:
x = contentRect.maxX - width - self.imageEdgeInsets.right
default:
// Center
x = ((contentRect.minX + self.imageEdgeInsets.left) + (contentRect.maxX - self.imageEdgeInsets.right)) * 0.5 - width * 0.5
}
switch self._customVerticalImageAlignment {
case .top:
y = contentRect.minY + self.imageEdgeInsets.top
case .bottom:
y = contentRect.maxY - height - self.imageEdgeInsets.bottom
default:
// Center
y = ((contentRect.minY + self.imageEdgeInsets.top) + (contentRect.maxY - self.imageEdgeInsets.bottom)) * 0.5 - height * 0.5
}
return CGRect(x: x,
y: y,
width: width,
height: height)
} else {
return super.imageRect(forContentRect: contentRect)
}
}
// -----------------------------------------------------------------------------------------------------------------------
//
// MARK: Private methods
//
// -----------------------------------------------------------------------------------------------------------------------
private func _init() {
self._normalTitle = super.title(for: .normal)
self._highlightedTitle = super.title(for: .highlighted)
self._selectedTitle = super.title(for: .selected)
self._disabledTitle = super.title(for: .disabled)
self._defaultHorizontalContentAlignment = self.contentHorizontalAlignment
self._defaultVerticalContentAlignment = self.contentVerticalAlignment
if #available(iOS 15.0, *) {
self.configuration = UIButton.Configuration.plain()
}
}
open override func updateConfiguration() {
if #available(iOS 15.0, *) {
super.updateConfiguration()
switch self.state {
case .normal:
// Apperance
self.backgroundColor = self._normalBackgroundColor
self.layer.borderColor = (self._normalBorderColor ?? UIColor.clear).cgColor
// Title
self.configuration?.title = self._normalTitle
self.configuration?.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { attributes in
var newAttributes = attributes
newAttributes.foregroundColor = self.titleColor(for: .normal)
newAttributes.font = self.titleLabel?.font
return newAttributes
}
// Image
if self.tintImageWithTitleColor, self.imageView != nil {
self.configuration?.imageColorTransformer = UIConfigurationColorTransformer { _ in
return self.titleColor(for: .selected) ?? self.titleColor(for: .normal) ?? self.configuration?.baseForegroundColor ?? UIColor.white
}
}
case .highlighted:
// Apperance
self.backgroundColor = self._highlightedBackgroundColor ?? self._normalBackgroundColor
self.layer.borderColor = self._highlightedBorderColor?.cgColor ?? (self._normalBorderColor ?? UIColor.clear).cgColor
// Title
self.configuration?.title = self._highlightedTitle ?? self._normalTitle
self.configuration?.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { attributes in
var newAttributes = attributes
newAttributes.foregroundColor = self.titleColor(for: .highlighted)
newAttributes.font = self.titleLabel?.font
return newAttributes
}
// Image
if self.tintImageWithTitleColor, self.imageView != nil {
self.configuration?.imageColorTransformer = UIConfigurationColorTransformer { _ in
return self.titleColor(for: .highlighted) ?? self.titleColor(for: .normal) ?? self.configuration?.baseForegroundColor ?? UIColor.white
}
}
case .selected:
// Apperance
self.backgroundColor = self._selectedBackgroundColor ?? self._normalBackgroundColor
self.layer.borderColor = self._selectedBorderColor?.cgColor ?? (self._normalBorderColor ?? UIColor.clear).cgColor
// Title
self.configuration?.title = self._selectedTitle ?? self._normalTitle
self.configuration?.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { attributes in
var newAttributes = attributes
newAttributes.foregroundColor = self.titleColor(for: .selected)
newAttributes.font = self.titleLabel?.font
return newAttributes
}
// Image
if self.tintImageWithTitleColor, self.imageView != nil {
self.configuration?.imageColorTransformer = UIConfigurationColorTransformer { _ in
return self.titleColor(for: .selected) ?? self.titleColor(for: .normal) ?? self.configuration?.baseForegroundColor ?? UIColor.white
}
}
case .disabled:
// Apperance
self.backgroundColor = self._disabledBackgroundColor ?? self._normalBackgroundColor
self.layer.borderColor = self._disabledBorderColor?.cgColor ?? (self._normalBorderColor ?? UIColor.clear).cgColor
// Title
self.configuration?.title = self._disabledTitle ?? self._normalTitle
self.configuration?.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { attributes in
var newAttributes = attributes
newAttributes.foregroundColor = self.titleColor(for: .disabled)
newAttributes.font = self.titleLabel?.font
return newAttributes
}
// Image
if self.tintImageWithTitleColor, let imageView = self.imageView, imageView.image != nil {
self.configuration?.imageColorTransformer = UIConfigurationColorTransformer { _ in
return self.titleColor(for: .disabled) ?? self.titleColor(for: .normal) ?? self.configuration?.baseForegroundColor ?? UIColor.white
}
}
default:
// Do nothing
break;
}
}
}
private func updateColors(updateImageTintColor:Bool)
{
if #available(iOS 15.0, *) {
return
}
if self.isEnabled
{
if (self.isHighlighted)
{
self.backgroundColor = self._highlightedBackgroundColor ?? self._normalBackgroundColor
self.layer.borderColor = self._highlightedBorderColor?.cgColor ?? (self._normalBorderColor ?? UIColor.clear).cgColor
if updateImageTintColor, let imageView = self.imageView, imageView.image != nil {
imageView.tintColor = self.titleColor(for: .highlighted)
}
}
else if (self.isSelected)
{
self.backgroundColor = self._selectedBackgroundColor ?? self._normalBackgroundColor
self.layer.borderColor = self._selectedBorderColor?.cgColor ?? (self._normalBorderColor ?? UIColor.clear).cgColor
if updateImageTintColor, let imageView = self.imageView, imageView.image != nil {
imageView.tintColor = self.titleColor(for: .selected)
}
}
else
{
self.backgroundColor = self._normalBackgroundColor
self.layer.borderColor = (self._normalBorderColor ?? UIColor.clear).cgColor
if updateImageTintColor, let imageView = self.imageView, imageView.image != nil {
imageView.tintColor = self.titleColor(for: UIControl.State())
}
}
}
else
{
self.backgroundColor = self._disabledBackgroundColor ?? self._normalBackgroundColor
self.layer.borderColor = self._disabledBorderColor?.cgColor ?? (self._normalBorderColor ?? UIColor.clear).cgColor
if updateImageTintColor, let imageView = self.imageView, imageView.image != nil {
imageView.tintColor = self.titleColor(for: .disabled)
}
}
}
private func updateImageRenderingModeForState(_ state:UIControl.State) {
let renderingMode = self.tintImageWithTitleColor ? UIImage.RenderingMode.alwaysTemplate : UIImage.RenderingMode.alwaysOriginal
if let image = self.image(for: state), image.renderingMode != renderingMode {
super.setImage(image.withRenderingMode(renderingMode), for: state)
}
}
}
| mit | b7073e31be30e419e3dd90dea211bc2e | 38.123881 | 169 | 0.523633 | 6.097465 | false | true | false | false |
JayJayy/Messenger | Messenger/Messenger/Messenger.swift | 1 | 1013 | //
// Messenger.swift
// Budget
//
// Created by Johannes Starke on 27.10.16.
// Copyright © 2016 Johannes Starke. All rights reserved.
//
import Foundation
public class Messenger {
public static let shared: Messenger = Messenger()
private let store: WeakStore<Receiver>
internal init() {
store = WeakStore<Receiver>()
}
public func publish<TMessage: Message>(message: TMessage) {
let storeName = "\(TMessage.self)"
let items = store.items(from: storeName)
print("Messenger: Publish \(storeName) to \(items.count) receiver")
for item in items {
item.notify(with: message)
}
}
public func subscribe<TMessage: Message>(me token: AnyObject, to messageType: TMessage.Type, onReceive delegate: @escaping (_ message: TMessage) -> ()) {
let storeName = "\(TMessage.self)"
self.store.store(item: Receiver.build(for: token, with: delegate), in: storeName)
}
}
| mit | 1562aeee95cf3b8943c840ecd1e56a27 | 27.111111 | 157 | 0.616601 | 4.19917 | false | false | false | false |
nifty-swift/Nifty | Sources/Tensor.swift | 2 | 16597 | /***************************************************************************************************
* Tensor.swift
*
* This file defines the Tensor data structure, a multidimensional array.
*
* Author: Philip Erickson
* Creation Date: 12 Dec 2016
*
* 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.
*
* Copyright 2016 Philip Erickson
**************************************************************************************************/
import Foundation
/// Data structure for a multidimensional, row-major order array.
public struct Tensor<Element>: TensorProtocol
{
public let count: Int
public var size: [Int]
public var data: [Element]
public var name: String?
public var showName: Bool
public var format: NumberFormatter
//----------------------------------------------------------------------------------------------
// MARK: INITIALIZE
//----------------------------------------------------------------------------------------------
public init(_ size: [Int], _ data: [Element], name: String? = nil, showName: Bool? = nil)
{
let n = size.reduce(1, *)
precondition(n > 0, "Tensor must have at least 1 element")
precondition((size.filter({$0 <= 0})).count == 0, "Tensor must have all dimensions > 0")
precondition(data.count == n, "Tensor dimensions must match data")
self.size = size
self.count = n
self.data = data
self.name = name
if let show = showName
{
self.showName = show
}
else
{
self.showName = name != nil
}
// default display settings
let fmt = NumberFormatter()
fmt.numberStyle = .decimal
fmt.usesSignificantDigits = true
fmt.paddingCharacter = " "
fmt.paddingPosition = .afterSuffix
fmt.formatWidth = 8
self.format = fmt
}
public init(_ size: [Int], value: Element, name: String? = nil, showName: Bool? = nil)
{
let n = size.reduce(1, *)
precondition(n > 0, "Tensor must contain at least one element")
let data = Array<Element>(repeating: value, count: n)
self.init(size, data, name: name, showName: showName)
}
public init<T>(_ t: T, name: String? = nil, showName: Bool? = nil) where T : TensorProtocol, Element == T.Element
{
self.init(t.size, t.data, name: name, showName: showName)
}
public init(_ rawDescription: String, name: String? = nil, showName: Bool? = nil)
{
// FIXME: implement
fatalError("Not yet implemented")
}
//----------------------------------------------------------------------------------------------
// MARK: SUBSCRIPT
//----------------------------------------------------------------------------------------------
/// Access a single element of the tensor with a subscript.
///
/// If only one subscript is given, it is interpretted as a row-major order linear index.
/// Otherwise, the given subscripts are treated as indexes into each dimension.
///
/// - Parameters:
/// - s: subscripts
/// - Returns: single value at index
public subscript(_ s: [Int]) -> Element
{
get
{
assert(s.count > 0)
if s.count == 1
{
return self.getValue(index: s[0])
}
else
{
return self.getValue(subscripts: s)
}
}
set(newValue)
{
assert(s.count > 0)
if s.count == 1
{
self.setValue(index: s[0], value: newValue)
}
else
{
self.setValue(subscripts: s, value: newValue)
}
}
}
public subscript(_ s: Int...) -> Element
{
get { return self[s] }
set(newValue) { self[s] = newValue }
}
/// Access a slice of the tensor with a subscript range.
///
/// If only one range is given, it is interpretted as a row-major order linear index. Otherwise,
/// the given subscripts are treated as indexes into each dimension.
///
/// - Parameters:
/// - s: subscripts
/// - Returns: new tensor composed of slice
public subscript(_ s: SliceIndex...) -> Tensor<Element>
{
get
{
assert(s.count > 0)
if s.count == 1
{
return self.getSlice(index: s[0])
}
else
{
return self.getSlice(subscripts: s)
}
}
set(newValue)
{
assert(s.count > 0)
if s.count == 1
{
self.setSlice(index: s[0], value: newValue)
}
else
{
self.setSlice(subscripts: s, value: newValue)
}
}
}
private func getValue(index: Int) -> Element
{
precondition(index >= 0 && index < self.count, "Tensor subscript out of bounds")
return self.data[index]
}
private mutating func setValue(index: Int, value: Element)
{
precondition(index >= 0 && index < self.count, "Tensor subscript out of bounds")
self.data[index] = value
}
private func getValue(subscripts: [Int]) -> Element
{
let index = sub2ind(subscripts, size: self.size)
precondition(index >= 0, "Tensor subscript out of bounds")
return self.data[index]
}
private mutating func setValue(subscripts: [Int], value: Element)
{
let index = sub2ind(subscripts, size: self.size)
precondition(index >= 0, "Tensor subscript out of bounds")
self.data[index] = value
}
private func getSlice(index: SliceIndex) -> Tensor<Element>
{
let range = _convertToCountableClosedRange(index)
// inherit name, add slice info
var sliceName = self.name
if sliceName != nil { sliceName = "\(_parenthesizeExpression(sliceName!))[\(index)]" }
let d = Array(self.data[range])
return Tensor([1, d.count], d, name: sliceName, showName: self.showName)
}
private mutating func setSlice(index: SliceIndex, value: Tensor<Element>)
{
// FIXME: there's no shape checking here! E.g. a [1,1,4] slice could
// be assigned a [1,2,2] Tensor. How should that be handled?
let range = _convertToCountableClosedRange(index)
self.data[range] = ArraySlice(value.data)
}
private func getSlice(subscripts: [SliceIndex]) -> Tensor<Element>
{
let ranges = _convertToCountableClosedRanges(subscripts)
precondition(ranges.count == self.size.count, "Subscript must match tensor dimension")
// determine size of resulting tensor slice, and start/end subscripts to read
var newSize = [Int](repeating: 0, count: ranges.count)
var startSub = [Int](repeating: 0, count: ranges.count)
var endSub = [Int](repeating: 0, count: ranges.count)
for (i, range) in ranges.enumerated()
{
newSize[i] = range.count
startSub[i] = range.lowerBound
endSub[i] = range.upperBound
}
// start reading from tensor, rolling over each dimension
var newData = [Element]()
var curSub = startSub
while true
{
newData.append(self.getValue(subscripts: curSub))
guard let inc = _cascadeIncrementSubscript(curSub, min: startSub, max: endSub) else
{
break
}
curSub = inc
}
// inherit name, add slice info
var sliceName = self.name
if sliceName != nil
{
// closed countable ranges print with quotes around them, which clutters display
let subsDescrip = "\((subscripts.map({"\($0)"})))".replacingOccurrences(of: "\"", with: "")
sliceName = "\(_parenthesizeExpression(sliceName!))\(subsDescrip)"
}
return Tensor(newSize, newData, name: sliceName, showName: self.showName)
}
private mutating func setSlice(subscripts: [SliceIndex], value: Tensor<Element>)
{
let ranges = _convertToCountableClosedRanges(subscripts)
precondition(ranges.count == self.size.count, "Subscript must match tensor dimension")
// determine range of writes in each dimension
var startSub = [Int](repeating: 0, count: ranges.count)
var endSub = [Int](repeating: 0, count: ranges.count)
for (i,range) in ranges.enumerated()
{
startSub[i] = range.lowerBound
endSub[i] = range.upperBound
}
// ensure that new data size matches size of slice to write to
var sliceSize = [Int](repeating: 0, count: ranges.count)
for i in 0..<ranges.count
{
sliceSize[i] = endSub[i]-startSub[i]+1
}
precondition(sliceSize == value.size, "Provided data must match tensor slice size")
// start writing to matrix, rolling over each dimension
var newData = value.data
var curSub = startSub
for i in 0..<newData.count
{
self.setValue(subscripts: curSub, value: newData[i])
guard let inc = _cascadeIncrementSubscript(curSub, min: startSub, max: endSub) else
{
return
}
curSub = inc
}
}
//----------------------------------------------------------------------------------------------
// MARK: DISPLAY
//----------------------------------------------------------------------------------------------
/// String representation of tensor contents in an easily readable grid format.
///
/// - Note: The formatter associated with this tensor is used as a suggestion; elements may be
/// formatted differently to improve readability. Elements that can't be displayed under the
/// current formatting constraints will be displayed as '#'.
public var description: String
{
// create tensor title
var title = ""
if self.showName
{
title = (self.name ?? "\(self.size.map({"\($0)"}).joined(separator: "x")) tensor") + ":\n"
}
// handle 1D tensor
if self.size.count == 1
{
return "\(Vector(self, name: title, showName: self.showName))"
}
// handle 2D tensor
else if self.size.count == 2
{
return "\(Matrix(self, name: title, showName: self.showName))"
}
// break 3D+ tensors into 2D tensor chunks
else
{
// The approach here is to increment across only the third and higher dimensions. At
// each point, we can slice off the first and second dimensions and print those as a
// matrix. To do this though, we need to increment the lower dimensions faster, rather
// than the higher dimensions as row-major order does. This is because we'd expect to
// see the third dimension slices printed together, then the fourth, etc.
var str = title
// slice of third and higher dimensions
let hiDims = self.size[2..<self.size.count]
// reverse dimensions so cascade increment goes through low dimension fastest
let hiDimsRev = Array(hiDims.reversed())
let startRev = Array(repeating: 0, count: hiDimsRev.count)
let endRev = hiDimsRev.map({$0-1})
var curSubRev = Array<Int>(repeating: 0, count: hiDimsRev.count)
while true
{
// create a slice over entire dims 1 and 2 for the current spot in dims 3+
let curSliceLoSubs: [SliceIndex] = [0..<self.size[0], 0..<self.size[1]]
let curSliceHiSubs: [SliceIndex] = Array(curSubRev.reversed())
let curSliceSubs = curSliceLoSubs + curSliceHiSubs
let curSlice = self.getSlice(subscripts: curSliceSubs)
// create a header to identify current matrix location in tensor
let mName = "[..., ..., " + curSliceHiSubs.map({"\($0)"}).joined(separator: ", ") + "]"
// turn slice into matrix for easy printing
let m = Matrix(curSlice.size[0], curSlice.size[1], curSlice.data, name: mName, showName: true)
str += "\(m)\n\n"
// increment through higher dimensions until we've reached the end
guard let inc = _cascadeIncrementSubscript(curSubRev, min: startRev, max: endRev) else
{
return str
}
curSubRev = inc
}
}
}
/// String representation of tensor in raw format.
///
/// Elements of a row are comma separated. Rows are separated by newlines. Higher dimensional
/// slices are separated by a line consisting entirely of semicolons, where the number of
/// semicolons indicates the dimension that ended; e.g. ";" comes between matrices in a 3D
/// tensor, ";;" comes between 3D tensors in a 4D tensor, ";;;" between 4D tensors in 5D, etc.
public var rawDescription: String
{
// handle 1D tensor
if self.size.count == 1
{
return Vector(self, name: nil, showName: false).rawDescription
}
// handle 2D tensor
else if self.size.count == 2
{
return Matrix(self, name: nil, showName: false).rawDescription
}
// break 3D+ tensors into 2D tensor chunks
else
{
var str = [String]()
// slice of third and higher dimensions
let hiDims = self.size[2..<self.size.count]
// reverse dimensions so cascade increment goes through low dimension fastest
let hiDimsRev = Array(hiDims.reversed())
let startRev = Array(repeating: 0, count: hiDimsRev.count)
let endRev = hiDimsRev.map({$0-1})
var curSubRev = Array<Int>(repeating: 0, count: hiDimsRev.count)
while true
{
// create a slice over entire dims 1 and 2 for the current spot in dims 3+
let curSliceLoSubs: [SliceIndex] = [0..<self.size[0], 0..<self.size[1]]
let curSliceHiSubs: [SliceIndex] = Array(curSubRev.reversed())
let curSliceSubs = curSliceLoSubs + curSliceHiSubs
let curSlice = self.getSlice(subscripts: curSliceSubs)
// turn slice into matrix for easy printing
let m = Matrix(curSlice.size[0], curSlice.size[1], curSlice.data, name: nil, showName: false)
str.append("\(m.rawDescription)")
// increment through higher dimensions until we've reached the end
guard let inc = _cascadeIncrementSubscript(curSubRev, min: startRev, max: endRev) else
{
return str.joined(separator: "\n")
}
// find which dimension rolled over to determine how many semicolons to delimit with
var numSemicolons = -1
for d in 0..<curSubRev.count
{
if curSubRev[d] != inc[d]
{
numSemicolons = curSubRev.count-d
break
}
}
assert(numSemicolons > 0, "No semicolon needed implies function should have already returned")
let semicolons = String(repeating: ";", count: numSemicolons)
str.append(semicolons)
// move on to next slice
curSubRev = inc
}
}
}
}
| apache-2.0 | 98b9039819021c30a8653229701370d3 | 35.719027 | 117 | 0.533651 | 4.785755 | false | false | false | false |
rayfix/RAFIntMath | RAFIntMath/Binomial.swift | 1 | 983 | //
// Binomial.swift
//
// Created by Ray Fix on 6/21/14.
// Copyright (c) 2014 Pelfunc, Inc. All rights reserved.
//
import Foundation
public struct Binomial {
public var n:Int
public var choose:Int
// private
func _toDouble() -> Double {
var num = Factorial(n).factors
var den = Factorial(choose).factors * Factorial(n-choose).factors
reduce(&num, &den)
return Double(num) / Double(den)
}
public init(n:Int, choose:Int) {
self.n = n
self.choose = choose
}
}
public extension Double {
public init(_ v: Binomial) {
self = v._toDouble()
}
}
public func /(num:Binomial, den:Binomial) -> Rational {
var n = Factorial(num.n).factors * Factorial(den.choose).factors * Factorial(den.n - den.choose).factors
var d = Factorial(den.n).factors * Factorial(num.choose).factors * Factorial(num.n - num.choose).factors
reduce(&n, &d)
return Rational(Int(n),Int(d))
} | mit | 1ce3743cf0cee5cc15e13a70f45bae68 | 23.6 | 108 | 0.612411 | 3.354949 | false | false | false | false |
kstaring/swift | test/DebugInfo/linetable.swift | 6 | 1707 | // RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s
// RUN: %target-swift-frontend %s -S -g -o - | %FileCheck %s --check-prefix ASM-CHECK
// REQUIRES: CPU=i386_or_x86_64
import Swift
func markUsed<T>(_ t: T) {}
class MyClass
{
var x : Int64
init(input: Int64) { x = input }
func do_something(_ input: Int64) -> Int64
{
return x * input
}
}
func call_me(_ code: @escaping () -> Void)
{
code ()
}
func main(_ x: Int64) -> Void
// CHECK: define hidden void @_TF9linetable4main
{
var my_class = MyClass(input: 10)
// Linetable continuity. Don't go into the closure expression.
// ASM-CHECK: .loc [[FILEID:[0-9]]] [[@LINE+1]] 5
call_me (
// ASM-CHECK-NOT: .loc [[FILEID]] [[@LINE+1]] 5
// CHECK: @_TTSf2i_n___TFF9linetable4mainFVs5Int64T_U_FT_T_
{
var result = my_class.do_something(x)
markUsed(result)
// CHECK: call {{.*}} @swift_rt_swift_release {{.*}}
// CHECK: call {{.*}} @swift_rt_swift_release {{.*}}, !dbg ![[CLOSURE_END:.*]]
// CHECK-NEXT: bitcast
// CHECK-NEXT: llvm.lifetime.end
// CHECK-NEXT: ret void, !dbg ![[CLOSURE_END]]
// CHECK: ![[CLOSURE_END]] = !DILocation(line: [[@LINE+1]],
}
)
// The swift_releases at the end should not jump to the point where
// that memory was retained/allocated and also not to line 0.
// ASM-CHECK-NOT: .loc [[FILEID]] 0 0
// ASM-CHECK: .loc [[FILEID]] [[@LINE+2]] 1
// ASM-CHECK: ret
}
// ASM-CHECK: {{^_?_TTSf2i_n___TFF9linetable4mainFVs5Int64T_U_FT_T_:}}
// ASM-CHECK-NOT: retq
// The end-of-prologue should have a valid location (0 is ok, too).
// ASM-CHECK: .loc [[FILEID]] 0 {{[0-9]+}} prologue_end
// ASM-CHECK: .loc [[FILEID]] 34 {{[0-9]+}}
main(30)
| apache-2.0 | bfd0637f43980380c18422c4c592523f | 28.431034 | 85 | 0.599883 | 2.89322 | false | false | false | false |
THINKGlobalSchool/SpotConnect | SpotConnect/HelpViewController.swift | 1 | 1818 | //
// HelpViewController.swift
// SpotConnect
//
// Created by Jeff Tilson on 2015-05-14.
// Copyright (c) 2015 Jeff Tilson. All rights reserved.
//
import UIKit
import AVKit
import Foundation
import AVFoundation
class HelpViewController: UIViewController {
// MARK: - Outlets
@IBOutlet weak var signin: SpotHelpButton!
@IBOutlet weak var bookmark: SpotHelpButton!
@IBOutlet weak var photo: SpotHelpButton!
// MARK: - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
self.twoColorLayerGradient(SpotColors.LIGHTRED, colorTwo: SpotColors.DARKRED)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// Provide the corresponding video name in the button tag
signin.videoTitle = "signin_final"
signin.videoType = "mov"
bookmark.videoTitle = "bookmark_final"
bookmark.videoType = "mov"
photo.videoTitle = "photo_final"
photo.videoType = "mov"
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Make sure we were sent here with a help button
if let helpButton: SpotHelpButton = sender as? SpotHelpButton {
let destination = segue.destinationViewController as! AVPlayerViewController
let url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(helpButton.videoTitle, ofType: helpButton.videoType)!)
destination.player = AVPlayer(URL: url)
destination.videoGravity = AVLayerVideoGravityResizeAspectFill
}
}
// MARK: - Actions
@IBAction func helpButtonPressed(sender: SpotHelpButton) {
performSegueWithIdentifier("playVideo", sender: sender)
}
}
| gpl-2.0 | 98891c8995a6a9229d60b8e6aa9715df | 28.803279 | 137 | 0.665567 | 4.940217 | false | false | false | false |
calt/Moya | Tests/NetworkLoggerPluginSpec.swift | 2 | 7913 | import Quick
import Nimble
import Moya
import Result
import enum Alamofire.AFError
final class NetworkLoggerPluginSpec: QuickSpec {
override func spec() {
var log = ""
let plugin = NetworkLoggerPlugin(verbose: true, output: { (_, _, printing: Any...) in
//mapping the Any... from items to a string that can be compared
let stringArray: [String] = printing.map { $0 as? String }.flatMap { $0 }
let string: String = stringArray.reduce("") { $0 + $1 + " " }
log += string
})
let pluginWithCurl = NetworkLoggerPlugin(verbose: true, cURL: true, output: { (_, _, printing: Any...) in
//mapping the Any... from items to a string that can be compared
let stringArray: [String] = printing.map { $0 as? String }.flatMap { $0 }
let string: String = stringArray.reduce("") { $0 + $1 + " " }
log += string
})
let pluginWithRequestDataFormatter = NetworkLoggerPlugin(verbose: true, output: { (_, _, printing: Any...) in
//mapping the Any... from items to a string that can be compared
let stringArray: [String] = printing.map { $0 as? String }.flatMap { $0 }
let string: String = stringArray.reduce("") { $0 + $1 + " " }
log += string
}, responseDataFormatter: { _ in
return "formatted request body".data(using: .utf8)!
})
let pluginWithResponseDataFormatter = NetworkLoggerPlugin(verbose: true, output: { (_, _, printing: Any...) in
//mapping the Any... from items to a string that can be compared
let stringArray: [String] = printing.map { $0 as? String }.flatMap { $0 }
let string: String = stringArray.reduce("") { $0 + $1 + " " }
log += string
}, responseDataFormatter: { _ in
return "formatted body".data(using: .utf8)!
})
beforeEach {
log = ""
}
it("outputs all request fields with body") {
plugin.willSend(TestBodyRequest(), target: GitHub.zen)
expect(log).to( contain("Request: https://api.github.com/zen") )
expect(log).to( contain("Request Headers: [\"Content-Type\": \"application/json\"]") )
expect(log).to( contain("HTTP Request Method: GET") )
expect(log).to( contain("Request Body: cool body") )
}
it("outputs all request fields with stream") {
plugin.willSend(TestStreamRequest(), target: GitHub.zen)
expect(log).to( contain("Request: https://api.github.com/zen") )
expect(log).to( contain("Request Headers: [\"Content-Type\": \"application/json\"]") )
expect(log).to( contain("HTTP Request Method: GET") )
expect(log).to( contain("Request Body Stream:") )
}
it("will output invalid request when reguest is nil") {
plugin.willSend(TestNilRequest(), target: GitHub.zen)
expect(log).to( contain("Request: (invalid request)") )
}
it("outputs the response data") {
let response = Response(statusCode: 200, data: "cool body".data(using: .utf8)!, response: HTTPURLResponse(url: URL(string: url(GitHub.zen))!, mimeType: nil, expectedContentLength: 0, textEncodingName: nil))
let result: Result<Moya.Response, MoyaError> = .success(response)
plugin.didReceive(result, target: GitHub.zen)
expect(log).to( contain("Response:") )
expect(log).to( contain("{ URL: https://api.github.com/zen }") )
expect(log).to( contain("cool body") )
}
it("outputs the formatted response data") {
let response = Response(statusCode: 200, data: "cool body".data(using: .utf8)!, response: HTTPURLResponse(url: URL(string: url(GitHub.zen))!, mimeType: nil, expectedContentLength: 0, textEncodingName: nil))
let result: Result<Moya.Response, MoyaError> = .success(response)
pluginWithResponseDataFormatter.didReceive(result, target: GitHub.zen)
expect(log).to( contain("Response:") )
expect(log).to( contain("{ URL: https://api.github.com/zen }") )
expect(log).to( contain("formatted body") )
}
it("outputs the formatted request data") {
let response = Response(statusCode: 200, data: "cool body".data(using: .utf8)!, response: HTTPURLResponse(url: URL(string: url(GitHub.zen))!, mimeType: nil, expectedContentLength: 0, textEncodingName: nil))
let result: Result<Moya.Response, MoyaError> = .success(response)
pluginWithRequestDataFormatter.didReceive(result, target: GitHub.zen)
expect(log).to( contain("Response:") )
expect(log).to( contain("{ URL: https://api.github.com/zen }") )
expect(log).to( contain("formatted request body") )
}
it("outputs an empty response message") {
let emptyResponseError = AFError.responseSerializationFailed(reason: .inputDataNil)
let result: Result<Moya.Response, MoyaError> = .failure(.underlying(emptyResponseError, nil))
plugin.didReceive(result, target: GitHub.zen)
expect(log).to( contain("Response: Received empty network response for zen.") )
}
it("outputs cURL representation of request") {
pluginWithCurl.willSend(TestCurlBodyRequest(), target: GitHub.zen)
expect(log).to( contain("$ curl -i") )
expect(log).to( contain("-H \"Content-Type: application/json\"") )
expect(log).to( contain("-d \"cool body\"") )
expect(log).to( contain("\"https://api.github.com/zen\"") )
}
}
}
private class TestStreamRequest: RequestType {
var request: URLRequest? {
var r = URLRequest(url: URL(string: url(GitHub.zen))!)
r.allHTTPHeaderFields = ["Content-Type": "application/json"]
r.httpBodyStream = InputStream(data: "cool body".data(using: .utf8)!)
return r
}
func authenticate(user: String, password: String, persistence: URLCredential.Persistence) -> Self {
return self
}
func authenticate(usingCredential credential: URLCredential) -> Self {
return self
}
}
private class TestBodyRequest: RequestType {
var request: URLRequest? {
var r = URLRequest(url: URL(string: url(GitHub.zen))!)
r.allHTTPHeaderFields = ["Content-Type": "application/json"]
r.httpBody = "cool body".data(using: .utf8)
return r
}
func authenticate(user: String, password: String, persistence: URLCredential.Persistence) -> Self {
return self
}
func authenticate(usingCredential credential: URLCredential) -> Self {
return self
}
}
private class TestCurlBodyRequest: RequestType, CustomDebugStringConvertible {
var request: URLRequest? {
var r = URLRequest(url: URL(string: url(GitHub.zen))!)
r.allHTTPHeaderFields = ["Content-Type": "application/json"]
r.httpBody = "cool body".data(using: .utf8)
return r
}
func authenticate(user: String, password: String, persistence: URLCredential.Persistence) -> Self {
return self
}
func authenticate(usingCredential credential: URLCredential) -> Self {
return self
}
var debugDescription: String {
return ["$ curl -i", "-H \"Content-Type: application/json\"", "-d \"cool body\"", "\"https://api.github.com/zen\""].joined(separator: " \\\n\t")
}
}
private class TestNilRequest: RequestType {
var request: URLRequest? {
return nil
}
func authenticate(user: String, password: String, persistence: URLCredential.Persistence) -> Self {
return self
}
func authenticate(usingCredential credential: URLCredential) -> Self {
return self
}
}
| mit | 261357f305440cd0b3c4780e0eb32bca | 38.964646 | 218 | 0.608492 | 4.42067 | false | false | false | false |
AlDrago/SwiftyJSON | Tests/RawTests.swift | 1 | 3309 | // RawTests.swift
//
// Copyright (c) 2014 Pinglin Tang
//
// 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 XCTest
import SwiftyJSON3
class RawTests: XCTestCase {
func testRawData() {
let json: JSON = ["somekey" : "some string value"]
let expectedRawData = "{\"somekey\":\"some string value\"}".data(using: String.Encoding.utf8)
do {
let data: Data = try json.rawData()
XCTAssertEqual(expectedRawData, data)
} catch _ {
XCTFail()
}
}
func testInvalidJSONForRawData() {
let json: JSON = "...<nonsense>xyz</nonsense>"
do {
_ = try json.rawData()
} catch let error as NSError {
XCTAssertEqual(error.code, ErrorInvalidJSON)
}
}
func testArray() {
let json:JSON = [1, "2", 3.12, NSNull(), true, ["name": "Jack"]]
let data: Data?
do {
data = try json.rawData()
} catch _ {
data = nil
}
let string = json.rawString()
XCTAssertTrue (data != nil)
XCTAssertTrue (string!.lengthOfBytes(using: String.Encoding.utf8) > 0)
print(string!)
}
func testDictionary() {
let json:JSON = ["number":111111.23456789, "name":"Jack", "list":[1,2,3,4], "bool":false, "null":NSNull()]
let data: Data?
do {
data = try json.rawData()
} catch _ {
data = nil
}
let string = json.rawString()
XCTAssertTrue (data != nil)
XCTAssertTrue (string!.lengthOfBytes(using: String.Encoding.utf8) > 0)
print(string!)
}
func testString() {
let json:JSON = "I'm a json"
print(json.rawString())
XCTAssertTrue(json.rawString() == "I'm a json")
}
func testNumber() {
let json:JSON = 123456789.123
print(json.rawString())
XCTAssertTrue(json.rawString() == "123456789.123")
}
func testBool() {
let json:JSON = true
print(json.rawString())
XCTAssertTrue(json.rawString() == "true")
}
func testNull() {
let json:JSON = nil
print(json.rawString())
XCTAssertTrue(json.rawString() == "null")
}
}
| mit | 986a864aecb5fb0d964f88700e1784f5 | 32.424242 | 114 | 0.60411 | 4.297403 | false | true | false | false |
RushingTwist/SwiftExamples | Swifttttt/Swifttttt/TodoDemo/TableViewDataSource1.swift | 1 | 883 | //
// TableViewDataSource.swift
// Swifttttt
//
// Created by 王福林 on 2018/10/8.
// Copyright © 2018年 lynn. All rights reserved.
//
import UIKit
class TableViewDataSource1: NSObject, UITableViewDataSource {
var todos: [String]
weak var owner: ToDoViewController? = nil
init(todos:[String], owner: ToDoViewController?) {
self.todos = todos
self.owner = owner
}
//MARK: UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return todos.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: UITableViewCell.reuseID, for: indexPath)
cell.textLabel?.text = todos[indexPath.row]
return cell
}
}
| apache-2.0 | f3563c4530169eb8798f722083bc9461 | 25.484848 | 105 | 0.663616 | 4.648936 | false | false | false | false |
jnfisher/JFGameOfLife | JFGameOfLife/JFGameOfLife/GameViewController.swift | 1 | 2791 | //
// GameViewController.swift
// JFGameOfLife
//
// Created by John Fisher on 2/11/15.
// Copyright (c) 2015 John Fisher. All rights reserved.
//
import UIKit
import SpriteKit
import JFSparseMatrix
import JFGameOfLifeEngine
extension SKNode {
class func unarchiveFromFile(_ file : NSString) -> SKNode? {
if let url = Bundle.main.url(forResource: file as String, withExtension: "sks") {
let sceneData = try? Data(contentsOf: url, options: .mappedIfSafe)
if sceneData != nil {
let archiver = NSKeyedUnarchiver(forReadingWith: sceneData!)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObject(forKey: NSKeyedArchiveRootObjectKey) as! GameScene
archiver.finishDecoding()
return scene
}
}
return nil
}
}
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .aspectFit
// scene.anchorPoint = CGPoint(x: 0.25, y: 0.25)
if let board = RLEReader().buildBoard("sidecargun") {
let cols = (board.matrix.maxCol - board.matrix.minCol)
let rows = (board.matrix.maxRow - board.matrix.minRow)
scene.size = CGSize(width: rows, height: cols)
scene.engine.swap(board)
}
else {
scene.engine.swap(GameBoard(matrix: Matrix(), aliveRuleSet: [], deadRuleSet: []))
}
skView.presentScene(scene)
}
}
override var shouldAutorotate : Bool {
return true
}
// override func supportedInterfaceOrientations() -> Int {
// if UIDevice.current.userInterfaceIdiom == .phone {
// return Int(UIInterfaceOrientationMask.allButUpsideDown.rawValue)
// } else {
// return Int(UIInterfaceOrientationMask.all.rawValue)
// }
// }
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override var prefersStatusBarHidden : Bool {
return true
}
}
| mit | 2ff1feebdb13f12316a60ebdbf0d22ee | 31.835294 | 100 | 0.58617 | 5.037906 | false | false | false | false |
benlangmuir/swift | test/decl/protocol/special/coding/class_codable_default_initializer.swift | 27 | 1765 | // RUN: %target-typecheck-verify-swift -verify-ignore-unknown
// A class with no initializers (which has non-initialized properties so a
// default constructor can be synthesized) should produce an error.
class NoInitializers { // expected-error {{class 'NoInitializers' has no initializers}}
var x: Double // expected-note {{stored property 'x' without initial value prevents synthesized initializers}}
func foo() {
// The class should not receive a default constructor.
let _ = NoInitializers.init() // expected-error {{'NoInitializers' cannot be constructed because it has no accessible initializers}}
}
}
// A similar class with Codable properties adopting Codable should get a
// synthesized init(from:), and thus not warn.
class CodableNoExplicitInitializers : Codable {
var x: Double
func foo() {
// The class should receive a synthesized init(from:) and encode(to:)
let _ = CodableNoExplicitInitializers.init(from:)
let _ = CodableNoExplicitInitializers.encode(to:)
// It should not, however, receive a default constructor.
let _ = CodableNoExplicitInitializers.init() // expected-error {{missing argument for parameter 'from' in call}}
}
}
// A class with all initialized properties should receive a default constructor.
class DefaultConstructed {
var x: Double = .pi
func foo() {
let _ = DefaultConstructed.init()
}
}
// A class with all initialized, Codable properties adopting Codable should get
// the default constructor, along with a synthesized init(from:).
class CodableDefaultConstructed : Codable {
var x: Double = .pi
func foo() {
let _ = CodableDefaultConstructed.init()
let _ = CodableDefaultConstructed.init(from:)
let _ = CodableDefaultConstructed.encode(to:)
}
}
| apache-2.0 | c7bbdc2950ec6673039876190c0a4c2d | 35.770833 | 136 | 0.730312 | 4.336609 | false | false | false | false |
kesun421/firefox-ios | XCUITests/HomePageSettingsUITest.swift | 1 | 3957 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import XCTest
let websiteUrl1 = "www.mozilla.org"
let websiteUrl2 = "developer.mozilla.org"
let invalidUrl = "1-2-3"
class HomePageSettingsUITests: BaseTestCase {
private func enterWebPageAsHomepage(text: String) {
app.textFields["HomePageSettingTextField"].tap()
app.textFields["HomePageSettingTextField"].typeText(text)
let value = app.textFields["HomePageSettingTextField"].value
XCTAssertEqual(value as? String, text, "The webpage typed does not match with the one saved")
}
func testTyping() {
navigator.goto(HomePageSettings)
// Enter a webpage
enterWebPageAsHomepage(text: websiteUrl1)
// Check if it is saved going back and then again to home settings menu
navigator.goto(HomePageSettings)
let valueAfter = app.textFields["HomePageSettingTextField"].value
XCTAssertEqual(valueAfter as? String, websiteUrl1)
// Check that it is actually set by opening a different website and going to Home
navigator.openURL(urlString: websiteUrl2)
navigator.goto(BrowserTabMenu)
//Now check open home page should load the previously saved home page
let homePageMenuItem = app.tables["Context Menu"].cells["Open Homepage"]
waitforExistence(homePageMenuItem)
homePageMenuItem.tap()
waitForValueContains(app.textFields["url"], value: websiteUrl1)
}
func testTypingBadURL() {
navigator.goto(HomePageSettings)
// Enter an invalid Url
enterWebPageAsHomepage(text: invalidUrl)
navigator.goto(SettingsScreen)
// Check that it is not saved
navigator.goto(HomePageSettings)
let valueAfter = app.textFields["HomePageSettingTextField"].value
XCTAssertEqual("Enter a webpage", valueAfter as! String)
// There is no option to go to Home, instead the website open has the option to be set as HomePageSettings
navigator.openURL(urlString: websiteUrl1)
navigator.goto(BrowserTabMenu)
let homePageMenuItem = app.tables["Context Menu"].cells["Open Homepage"]
XCTAssertFalse(homePageMenuItem.exists)
}
func testClipboard() {
// Go to a website and copy the url
navigator.openURL(urlString: websiteUrl1)
app.textFields["url"].press(forDuration: 5)
app.buttons["Copy Address"].tap()
// Go to HomePage settings and paste it using the option Used Copied Link
navigator.goto(HomePageSettings)
XCTAssertTrue(app.cells["Use Copied Link"].isEnabled)
app.cells["Use Copied Link"].tap()
// Check that the webpage has been correclty copied into the correct field
let value = app.textFields["HomePageSettingTextField"].value
XCTAssertEqual(value as? String, "https://\(websiteUrl1)/en-US/",
"The webpage typed does not match with the one saved")
}
func testDisabledClipboard() {
// Type an incorrect URL and copy it
navigator.goto(URLBarOpen)
app.textFields["address"].typeText(invalidUrl)
app.textFields["address"].press(forDuration: 5)
app.menuItems["Select All"].tap()
app.menuItems["Copy"].tap()
app.buttons["goBack"].tap()
// Go to HomePage settings and check that it is not possible to copy it into the set webpage field
navigator.nowAt(BrowserTab)
navigator.goto(HomePageSettings)
waitforExistence(app.staticTexts["Use Copied Link"])
// Check that nothing is copied in the Set webpage field
app.cells["Use Copied Link"].tap()
let value = app.textFields["HomePageSettingTextField"].value
XCTAssertEqual("Enter a webpage", value as! String)
}
}
| mpl-2.0 | 048594be757e1b0e15a72db1501a353f | 41.095745 | 114 | 0.680566 | 4.660777 | false | true | false | false |
fuku2014/spritekit-original-game | src/scenes/play/sprites/Car.swift | 1 | 2985 | //
// Car.swift
// あるきスマホ
//
// Created by admin on 2015/09/22.
// Copyright (c) 2015年 m.fukuzawa. All rights reserved.
//
import UIKit
import SpriteKit
class Car: SKSpriteNode {
var moveSpeed = 0.0
var angularSpeed = 0.0
init() {
let atlas = SKTextureAtlas(named: "car")
let texture1 = atlas.textureNamed("car-01")
let texture2 = atlas.textureNamed("car-02")
texture1.filteringMode = .Nearest
texture2.filteringMode = .Nearest
let anim = SKAction.animateWithTextures([texture1, texture2], timePerFrame: 0.2)
let run = SKAction.repeatActionForever(anim)
super.init(texture: nil, color: UIColor.clearColor(), size: texture1.size())
self.setScale(1 / 6)
self.runAction(run)
self.zPosition = 10
// 衝突判定用
self.physicsBody = SKPhysicsBody(rectangleOfSize : self.size)
self.physicsBody?.dynamic = true
self.physicsBody?.affectedByGravity = false
self.physicsBody?.categoryBitMask = 0x1 << 0
self.physicsBody?.contactTestBitMask = 0x1 << 1 | 0x1 << 0
self.physicsBody?.collisionBitMask = 0
self.physicsBody?.usesPreciseCollisionDetection = true
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func move(timeSinceLastUpdate : CFTimeInterval) {
let road = self.parent as! Road
// 車の移動方向
let angularAmount = self.angularSpeed * timeSinceLastUpdate
self.zRotation = self.zRotation + CGFloat(angularAmount)
// 車の移動スピード
let moveAmount = self.moveSpeed * timeSinceLastUpdate
let theta = self.zRotation
let moveAmountX = CGFloat(cos(theta)) * CGFloat(moveAmount)
let moveAmountY = CGFloat(sin(theta)) * CGFloat(moveAmount)
let positionBefore = self.position
var positionAfter = CGPointMake(positionBefore.x + moveAmountX, positionBefore.y + moveAmountY)
let topEnd = road.groundTexture.size().height * road.textureYScale + road.loadTexture.size().height * road.textureYScale
let bottomEnd = road.groundTexture.size().height * road.textureYScale
// 画面の左端に行った場合
if positionAfter.x <= 0 {
positionAfter = CGPointMake(road.size.width, positionAfter.y)
}
// 道路の上下端に行った場合
if positionAfter.y + self.size.height / 2 >= topEnd || positionAfter.y - self.size.height / 2 <= bottomEnd {
self.zRotation = self.zRotation + 180
positionAfter = positionBefore
}
self.position = positionAfter
}
}
| apache-2.0 | 53c70e3f0adea8a0dbd90cc879aff65e | 33.369048 | 131 | 0.588847 | 4.361027 | false | false | false | false |
milseman/swift | test/Generics/same_type_constraints.swift | 6 | 8694 | // RUN: %target-typecheck-verify-swift -swift-version 4
protocol Fooable {
associatedtype Foo
var foo: Foo { get }
}
protocol Barrable {
associatedtype Bar: Fooable
var bar: Bar { get }
}
struct X {}
struct Y: Fooable {
typealias Foo = X
var foo: X { return X() }
}
struct Z: Barrable {
typealias Bar = Y
var bar: Y { return Y() }
}
protocol TestSameTypeRequirement {
func foo<F1: Fooable>(_ f: F1) where F1.Foo == X
}
struct SatisfySameTypeRequirement : TestSameTypeRequirement {
func foo<F2: Fooable>(_ f: F2) where F2.Foo == X {}
}
protocol TestSameTypeAssocTypeRequirement {
associatedtype Assoc
func foo<F1: Fooable>(_ f: F1) where F1.Foo == Assoc
}
struct SatisfySameTypeAssocTypeRequirement : TestSameTypeAssocTypeRequirement {
typealias Assoc = X
func foo<F2: Fooable>(_ f: F2) where F2.Foo == X {}
}
struct SatisfySameTypeAssocTypeRequirementDependent<T>
: TestSameTypeAssocTypeRequirement
{
typealias Assoc = T
func foo<F3: Fooable>(_ f: F3) where F3.Foo == T {}
}
// Pulled in from old standard library to keep the following test
// (LazySequenceOf) valid.
public struct GeneratorOf<T> : IteratorProtocol, Sequence {
/// Construct an instance whose `next()` method calls `nextElement`.
public init(_ nextElement: @escaping () -> T?) {
self._next = nextElement
}
/// Construct an instance whose `next()` method pulls its results
/// from `base`.
public init<I : IteratorProtocol>(_ base: I) where I.Element == T {
var base = base
self._next = { base.next() }
}
/// Advance to the next element and return it, or `nil` if no next
/// element exists.
///
/// Precondition: `next()` has not been applied to a copy of `self`
/// since the copy was made, and no preceding call to `self.next()`
/// has returned `nil`.
public mutating func next() -> T? {
return _next()
}
/// `GeneratorOf<T>` is also a `Sequence`, so it `generate`\ s
/// a copy of itself
public func makeIterator() -> GeneratorOf {
return self
}
let _next: () -> T?
}
// rdar://problem/19009056
public struct LazySequenceOf<S : Sequence, A> : Sequence where S.Iterator.Element == A {
public func makeIterator() -> GeneratorOf<A> {
return GeneratorOf<A>({ return nil })
}
public subscript(i : A) -> A { return i }
}
public func iterate<A>(_ f : @escaping (A) -> A) -> (_ x : A) -> LazySequenceOf<Iterate<A>, A>? {
return { x in nil }
}
public final class Iterate<A> : Sequence {
typealias IteratorProtocol = IterateGenerator<A>
public func makeIterator() -> IterateGenerator<A> {
return IterateGenerator<A>()
}
}
public final class IterateGenerator<A> : IteratorProtocol {
public func next() -> A? {
return nil
}
}
// rdar://problem/18475138
public protocol Observable : class {
associatedtype Output
func addObserver(_ obj : @escaping (Output) -> Void)
}
public protocol Bindable : class {
associatedtype Input
func foo()
}
class SideEffect<In> : Bindable {
typealias Input = In
func foo() { }
}
struct Composed<Left: Bindable, Right: Observable> where Left.Input == Right.Output {}
infix operator <- : AssignmentPrecedence
func <- <
Right
>(lhs: @escaping (Right.Output) -> Void, rhs: Right) -> Composed<SideEffect<Right>, Right>?
{
return nil
}
// rdar://problem/17855378
struct Pair<T, U> {
typealias Type_ = (T, U)
}
protocol Seq {
associatedtype Element
func zip<OtherSeq: Seq, ResultSeq: Seq> (_ otherSeq: OtherSeq) -> ResultSeq
where ResultSeq.Element == Pair<Element, OtherSeq.Element>.Type_
}
// rdar://problem/18435371
extension Dictionary {
func multiSubscript<S : Sequence>(_ seq: S) -> [Value?] where S.Iterator.Element == Key {
var result = [Value?]()
for seqElt in seq {
result.append(self[seqElt])
}
return result
}
}
// rdar://problem/19245317
protocol P {
associatedtype T: P
}
struct S<A: P> {
init<Q: P>(_ q: Q) where Q.T == A {}
}
// rdar://problem/19371678
protocol Food { }
class Grass : Food { }
protocol Animal {
associatedtype EdibleFood:Food
func eat(_ f:EdibleFood)
}
class Cow : Animal {
func eat(_ f: Grass) { }
}
struct SpecificAnimal<F:Food> : Animal {
typealias EdibleFood=F
let _eat:(_ f:F) -> ()
init<A:Animal>(_ selfie:A) where A.EdibleFood == F {
_eat = { selfie.eat($0) }
}
func eat(_ f:F) {
_eat(f)
}
}
// rdar://problem/18803556
struct Something<T> {
var items: [T] = []
}
extension Something {
init<S : Sequence>(_ s: S) where S.Iterator.Element == T {
for item in s {
items.append(item)
}
}
}
// rdar://problem/18120419
func TTGenWrap<T, I : IteratorProtocol>(_ iterator: I) where I.Element == (T,T)
{
var iterator = iterator
_ = iterator.next()
}
func IntIntGenWrap<I : IteratorProtocol>(_ iterator: I) where I.Element == (Int,Int)
{
var iterator = iterator
_ = iterator.next()
}
func GGWrap<I1 : IteratorProtocol, I2 : IteratorProtocol>(_ i1: I1, _ i2: I2) where I1.Element == I2.Element
{
var i1 = i1
var i2 = i2
_ = i1.next()
_ = i2.next()
}
func testSameTypeTuple(_ a: Array<(Int,Int)>, s: ArraySlice<(Int,Int)>) {
GGWrap(a.makeIterator(), s.makeIterator())
TTGenWrap(a.makeIterator())
IntIntGenWrap(s.makeIterator())
}
// rdar://problem/20256475
protocol FooProtocol {
associatedtype Element
func getElement() -> Element
}
protocol Bar {
associatedtype Foo : FooProtocol
func getFoo() -> Foo
mutating func extend<C : FooProtocol>(_ elements: C)
where C.Element == Foo.Element
}
// rdar://problem/21620908
protocol P1 { }
protocol P2Base { }
protocol P2 : P2Base {
associatedtype Q : P1
func getQ() -> Q
}
struct XP1<T : P2Base> : P1 {
func wibble() { }
}
func sameTypeParameterizedConcrete<C : P2>(_ c: C) where C.Q == XP1<C> {
c.getQ().wibble()
}
// rdar://problem/21621421
protocol P3 {
associatedtype AssocP3 : P1
}
protocol P4 {
associatedtype AssocP4 : P3
}
struct X1 : P1 { }
struct X3 : P3 {
typealias AssocP3 = X1
}
func foo<C : P4>(_ c: C) where C.AssocP4 == X3 {}
struct X4 : P4 {
typealias AssocP4 = X3
}
func testFoo(_ x3: X4) {
foo(x3)
}
// rdar://problem/21625478
struct X6<T> { }
protocol P6 { }
protocol P7 {
associatedtype AssocP7
}
protocol P8 {
associatedtype AssocP8 : P7
associatedtype AssocOther
}
func testP8<C : P8>(_ c: C) where C.AssocOther == X6<C.AssocP8.AssocP7> {}
// setGenericSignature() was getting called twice here
struct Ghost<T> {}
protocol Timewarp {
associatedtype Wormhole
}
struct Teleporter<A, B> where A : Timewarp, A.Wormhole == Ghost<B> {}
struct Beam {}
struct EventHorizon : Timewarp {
typealias Wormhole = Ghost<Beam>
}
func activate<T>(_ t: T) {}
activate(Teleporter<EventHorizon, Beam>())
// rdar://problem/29288428
class C {}
protocol P9 {
associatedtype A
}
struct X7<T: P9> where T.A : C { }
extension X7 where T.A == Int { } // expected-error {{'T.A' requires that 'Int' inherit from 'C'}}
struct X8<T: C> { }
extension X8 where T == Int { } // expected-error {{'T' requires that 'Int' inherit from 'C'}}
protocol P10 {
associatedtype A
associatedtype B
associatedtype C
associatedtype D
associatedtype E
}
protocol P11: P10 where A == B { }
func intracomponent<T: P11>(_: T) // expected-note{{previous same-type constraint 'T.A' == 'T.B' implied here}}
where T.A == T.B { } // expected-warning{{redundant same-type constraint 'T.A' == 'T.B'}}
func intercomponentSameComponents<T: P10>(_: T)
where T.A == T.B, // expected-warning{{redundant same-type constraint 'T.A' == 'T.B'}}
T.B == T.A { } // expected-note{{previous same-type constraint 'T.A' == 'T.B' written here}}
// FIXME: directionality of constraint above is weird
func intercomponentMoreThanSpanningTree<T: P10>(_: T)
where T.A == T.B,
T.B == T.C,
T.D == T.E, // expected-note{{previous same-type constraint 'T.D' == 'T.E' written here}}
T.D == T.B,
T.E == T.B // expected-warning{{redundant same-type constraint 'T.B' == 'T.E'}}
{ }
func trivialRedundancy<T: P10>(_: T) where T.A == T.A { } // expected-warning{{redundant same-type constraint 'T.A' == 'T.A'}}
struct X11<T: P10> where T.A == T.B { }
func intracomponentInferred<T>(_: X11<T>) // expected-note{{previous same-type constraint 'T.A' == 'T.B' inferred from type here}}
where T.A == T.B { } // expected-warning{{redundant same-type constraint 'T.A' == 'T.B'}}
// Suppress redundant same-type constraint warnings from result types.
struct StructTakingP1<T: P1> { }
func resultTypeSuppress<T: P1>() -> StructTakingP1<T> {
return StructTakingP1()
}
| apache-2.0 | 40b00e6bc82bccc04b97f26709d916aa | 22.245989 | 130 | 0.643892 | 3.284473 | false | false | false | false |
lucaswoj/sugar.swift | units/SugarUnitValue.swift | 1 | 4242 | //
// SugarUnitValue.swift
// Sugar
//
// Created by Lucas Wojciechowski on 10/21/14.
// Copyright (c) 2014 Scree Apps. All rights reserved.
//
import Foundation
class SugarUnitValue<Type:SugarUnitType>:SugarSerializable,Comparable {
let value:Double
let unit:SugarUnit<Type>
class func fromString(string:NSString) -> SugarUnitValue<Type>? {
var regexError:NSError? = nil
let regex = NSRegularExpression(pattern: "^\\s*([0-9]+)\\s*([a-zA-Z]+)\\s*$", options: NSRegularExpressionOptions.allZeros, error:®exError)
if regexError != nil { return nil }
let match = regex!.firstMatchInString(string, options:NSMatchingOptions.allZeros, range: NSMakeRange(0, string.length))
if match == nil { return nil }
let value = string.substringWithRange(match!.rangeAtIndex(1)).asDouble
let unit = string.substringWithRange(match!.rangeAtIndex(2))
return SugarUnitValue<Type>(value: value, unit: unit)
}
convenience init(value:Double, unit:String) {
self.init(
value: value,
unit: SugarUnit<Type>.get(unit)!
)
}
convenience init(standardValue:Double) {
self.init(value: standardValue, unit: SugarUnit<Type>.standard)
}
required init(value:Double, unit:SugarUnit<Type>) {
self.value = value
self.unit = unit
}
required init(coder: NSCoder) {
let unit = coder.decodeObjectForKey("unit") as SugarUnit<Type>
let value = coder.decodeDoubleForKey("value")
self.unit = unit
self.value = value
}
class func unserialize(serialized: SugarSerialized) -> Self {
return self(value: serialized.get("value")!, unit: (serialized.get("unit")! as SugarUnit<Type>))
}
func serialize() -> SugarSerialized {
return SugarSerialized().set(value, key: "value").set(unit, key: "unit")
}
func encodeWithCoder(coder: NSCoder) {
coder.encodeObject(self.unit, forKey: "unit")
coder.encodeDouble(self.value, forKey: "value")
}
var asStandardUnit:SugarUnitValue<Type> {
return asUnit(SugarUnit<Type>.standard)
}
var standardValue:Double {
return asStandardUnit.value
}
func asUnit(newUnitName:String) -> SugarUnitValue<Type> {
return asUnit(SugarUnit<Type>.get(newUnitName)!)
}
func asUnit(newUnit:SugarUnit<Type>) -> SugarUnitValue<Type> {
if (newUnit.name == unit.name) {
return self
} else {
let standardValue = unit.isStandard ? value : (value - unit.offset) / unit.multiplier
let newValue = newUnit.isStandard ? standardValue : standardValue * newUnit.multiplier + newUnit.offset
return SugarUnitValue(value: newValue, unit: newUnit)
}
}
func valueAsUnit(unit:String) -> Double {
return asUnit(unit).value
}
func valueAsUnit(unit:SugarUnit<Type>) -> Double {
return asUnit(unit).value
}
func asString(significantDigits:Int? = nil, fractionDigits:Int? = nil, unit:String? = nil) -> String {
let formatter = NSNumberFormatter()
formatter.locale = NSLocale.currentLocale()
formatter.usesGroupingSeparator = true
if significantDigits != nil {
formatter.usesSignificantDigits = true
formatter.maximumSignificantDigits = significantDigits!
formatter.minimumSignificantDigits = significantDigits!
} else if fractionDigits != nil {
formatter.minimumFractionDigits = fractionDigits!
formatter.maximumFractionDigits = fractionDigits!
}
return formatter.stringFromNumber(self.value)! + " " + self.unit.abbreviation
}
}
func - <T:SugarUnitType>(left: SugarUnitValue<T>, right: SugarUnitValue<T>) -> SugarUnitValue<T> {
return SugarUnitValue(value: left.value - right.valueAsUnit(left.unit), unit: left.unit.name)
}
func == <T:SugarUnitType>(left: SugarUnitValue<T>, right: SugarUnitValue<T>) -> Bool {
return left.value == right.valueAsUnit(left.unit)
}
func < <T:SugarUnitType>(left: SugarUnitValue<T>, right: SugarUnitValue<T>) -> Bool {
return left.value < right.valueAsUnit(left.unit)
} | mit | 9ee5c5f74ad06ba4495043ece93138be | 31.638462 | 150 | 0.652994 | 4.2167 | false | false | false | false |
dobleuber/my-swift-exercises | Project29/Project29/GameViewController.swift | 1 | 2946 | //
// GameViewController.swift
// Project29
//
// Created by Wbert Castro on 15/08/17.
// Copyright © 2017 Wbert Castro. All rights reserved.
//
import UIKit
import SpriteKit
import GameplayKit
class GameViewController: UIViewController {
var currentGame: GameScene!
@IBOutlet weak var angleSlider: UISlider!
@IBOutlet weak var angleLabel: UILabel!
@IBOutlet weak var velocitySlider: UISlider!
@IBOutlet weak var velocityLabel: UILabel!
@IBOutlet weak var launchButton: UIButton!
@IBOutlet weak var playerNumber: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
angleChanged(angleSlider)
velocityChanged(velocitySlider)
if let view = self.view as! SKView? {
// Load the SKScene from 'GameScene.sks'
if let scene = SKScene(fileNamed: "GameScene") {
// Set the scale mode to scale to fit the window
scene.scaleMode = .aspectFill
// Present the scene
view.presentScene(scene)
currentGame = scene as! GameScene
currentGame.viewController = self
}
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
}
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override var prefersStatusBarHidden: Bool {
return true
}
@IBAction func angleChanged(_ sender: UISlider) {
angleLabel.text = "Angle: \(Int(angleSlider.value))°"
}
@IBAction func velocityChanged(_ sender: UISlider) {
velocityLabel.text = "Velocity: \(Int(velocitySlider.value))"
}
@IBAction func launch(_ sender: Any) {
angleSlider.isHidden = true
angleLabel.isHidden = true
velocitySlider.isHidden = true
velocityLabel.isHidden = true
launchButton.isHidden = true
currentGame.launch(angle: Int(angleSlider.value), velocity: Int(velocitySlider.value))
}
func activatePlayer(number: Int) {
if number == 1 {
playerNumber.text = "<<< PLAYER ONE"
} else {
playerNumber.text = "PLAYER TWO >>>"
}
angleSlider.isHidden = false
angleLabel.isHidden = false
velocitySlider.isHidden = false
velocityLabel.isHidden = false
launchButton.isHidden = false
}
}
| mit | 5f3fd6e5b6b6272efd2bc333a4366a07 | 27.307692 | 94 | 0.592391 | 5.183099 | false | false | false | false |
langyanduan/YamlKit | Sources/YAMLSerialization.swift | 1 | 8855 | //
// YAMLSerialization.swift
// YamlKit
//
// Created by wufan on 2017/5/21.
// Copyright © 2017年 atoi. All rights reserved.
//
import Foundation
import libyaml
public class YAMLSerialization {
enum `Error`: Swift.Error {
case parser
}
enum `Type` {
case dictionary
case array
case object
}
public struct ReadingOptions: OptionSet {
public let rawValue: UInt
public init(rawValue: UInt) {
self.rawValue = rawValue
}
}
public struct WritingOptions: OptionSet {
public let rawValue: UInt
public init(rawValue: UInt) {
self.rawValue = rawValue
}
public static let tag = WritingOptions(rawValue: 1)
public static let implicit = WritingOptions(rawValue: 2)
}
}
extension YAMLSerialization {
class func object(nodes: [yaml_node_t], node: yaml_node_t) throws -> Any {
func node_(_ index: Int32) -> yaml_node_t {
return nodes[Int(index) - 1]
}
func object_(_ index: Int32) throws -> Any {
return try object(nodes: nodes, node: node_(index))
}
func string_(_ index: Int32) -> String {
return String(cString: node_(index).data.scalar.value)
}
func scalar_(_ node: yaml_node_t) -> Any {
let text = String(cString: node.data.scalar.value)
switch node.data.scalar.style {
case YAML_PLAIN_SCALAR_STYLE:
let scanner = Scanner(string: text)
do {
var value: Int = 0
if scanner.scanInt(&value) && scanner.scanLocation == text.characters.count {
return value
}
}
do {
var value: Double = 0
if scanner.scanDouble(&value) && scanner.scanLocation == text.characters.count {
return value
}
}
switch text {
case "true", "True", "TRUE", "yes", "Yes", "YES", "on", "On", "ON":
return true
case "false", "False", "FALSE", "no", "No", "NO", "off", "Off", "OFF":
return false
case "~", "null":
return NSNull()
default:
break
}
default:
break
}
return text
}
switch node.type {
case YAML_SCALAR_NODE:
return scalar_(node)
case YAML_MAPPING_NODE:
let pairs = node.data.mapping.pairs
var dict = [String: Any]()
for pair in UnsafeBufferPointer(start: pairs.start, count: pairs.top - pairs.start) {
dict[string_(pair.key)] = try object_(pair.value)
}
return dict
case YAML_SEQUENCE_NODE:
let items = node.data.sequence.items
var array = [Any]()
for item in UnsafeBufferPointer(start: items.start, count: items.top - items.start) {
array.append(try object_(item))
}
return array
default:
throw Error.parser
}
}
}
extension YAMLSerialization {
class func dump(object: Any ,to document: UnsafeMutablePointer<yaml_document_t>) throws -> Int32 {
var nodeId: Int32 = 0
switch object {
case let dict as Dictionary<String, Any>:
let mappingId = yaml_document_add_mapping(document, nil, YAML_ANY_MAPPING_STYLE)
for (key, value) in dict {
let keyId = try dump(object: key, to: document)
let valueId = try dump(object: value, to: document)
yaml_document_append_mapping_pair(document, mappingId, keyId, valueId)
}
nodeId = mappingId
case let array as Array<Any>:
let sequenceId = yaml_document_add_sequence(document, nil, YAML_ANY_SEQUENCE_STYLE)
for item in array {
let itemId = try dump(object: item, to: document)
yaml_document_append_sequence_item(document, sequenceId, itemId)
}
nodeId = sequenceId
// case let string as String:
// break
// case let bool as Bool:
// break
// case let float as Float:
// break
default:
let value = "\(object)"
let scalarId = value.withCString {
return yaml_document_add_scalar(document, nil, unsafeBitCast($0, to: UnsafeMutablePointer<UInt8>.self), Int32(value.utf8.count), YAML_ANY_SCALAR_STYLE)
}
nodeId = scalarId
}
return nodeId
}
}
extension YAMLSerialization {
public class func yamlObject(with data: Data, options opt: YAMLSerialization.ReadingOptions = []) throws -> Any {
var parser = yaml_parser_t()
var event = yaml_event_t()
var document = yaml_document_t()
yaml_parser_initialize(&parser)
defer { yaml_parser_delete(&parser) }
yaml_parser_set_encoding(&parser, YAML_UTF8_ENCODING)
yaml_parser_set_input_string(&parser, data.withUnsafeBytes { $0 }, data.count)
guard yaml_parser_load(&parser, &document) == 1 else {
throw Error.parser
}
defer { yaml_document_delete(&document) }
let node = yaml_document_get_root_node(&document)!
let nodes = document.nodes
return try object(nodes: Array(UnsafeBufferPointer(start: nodes.start, count: nodes.top - nodes.start)), node: node.pointee)
// var stack: [Any] = []
//
// var lastType: Type?
// var done = false
// while !done {
// if yaml_parser_parse(&parser, &event) == 0 {
// throw Error.parser
// }
// defer { yaml_event_delete(&event) }
//
// done = event.type == YAML_DOCUMENT_END_EVENT
// switch event.type {
// case YAML_SCALAR_EVENT:
// switch lastType {
// case .some(.dictionary): // dictionary's key
// break
// case .some(.object): // dictionary's value
// break
// case .some(.array):
// break
// default:
// break
// }
// break
// case YAML_SEQUENCE_START_EVENT:
// stack.append([Any]())
// break
// case YAML_MAPPING_START_EVENT:
// stack.append([String: Any]())
// break
// case YAML_SEQUENCE_END_EVENT, YAML_MAPPING_END_EVENT:
// if stack.count == 1 {
// assert(done)
// break
// }
// assert(stack.count > 1)
//
// let obj = stack.popLast()!
//
// case YAML_NO_EVENT: fallthrough
// case YAML_ALIAS_EVENT: fallthrough
// case YAML_STREAM_START_EVENT: fallthrough
// case YAML_STREAM_END_EVENT: fallthrough
// case YAML_DOCUMENT_START_EVENT: fallthrough
// case YAML_DOCUMENT_END_EVENT: fallthrough
// default:
// break
// }
//
// assert(!done || (done && stack.count == 1))
// }
//
// return stack.first!
}
public class func data(withJSONObject obj: Any, options opt: YAMLSerialization.WritingOptions = []) throws -> Data {
// Create and initialize a document to hold this.
var document = yaml_document_t()
yaml_document_initialize(&document, nil, nil, nil, 1, 1)
try dump(object: obj, to: &document)
var data = NSMutableData()
var emitter = yaml_emitter_t()
yaml_emitter_initialize(&emitter);
yaml_emitter_set_indent(&emitter, 2)
yaml_emitter_set_output(&emitter, { (point, bytes, len) -> Int32 in
guard let point = point, let bytes = bytes else {
return 0
}
var data = point.assumingMemoryBound(to: NSMutableData.self).pointee
data.append(bytes, length: len)
return Int32(len)
}, &data)
yaml_emitter_dump(&emitter, &document);
yaml_emitter_delete(&emitter);
yaml_document_delete(&document);
return data as Data
}
public class func isInvalidYAMLObject(_ obj: Any) -> Bool {
return false
}
}
| mit | d9a46a466814fe16dfc1e0ac7995f879 | 33.988142 | 167 | 0.505084 | 4.497967 | false | false | false | false |
dmrschmidt/QRCode | QRCodeTests/QRCodeSpec.swift | 1 | 11378 | import Quick
import Nimble
@testable import QRCode
class QRCodeSpec: QuickSpec {
override func spec() {
describe("QRCode") {
var qrCode: QRCode!
let size = CGSize(width: 300, height: 300)
let inherentSize = CGSize(width: 23.0, height: 23.0)
describe("init(data:color:backgroundColor:size:inputCorrection:)") {
var data: Data!
beforeEach {
data = "awesome".data(using: .isoLatin1)
}
it("creates a valid instance") {
qrCode = QRCode(data: data)
expect(qrCode).toNot(beNil())
}
it("encapsulates the passed data as is") {
qrCode = QRCode(data: data)
expect(qrCode.data).to(equal(data))
}
it("can have optional params") {
qrCode = QRCode(data: data, color: UIColor.red, size: size)
expect(qrCode.color).to(equal(UIColor.red))
expect(qrCode.size).to(equal(size))
}
}
describe("init(string:color:backgroundColor:size:inputCorrection:)") {
var string: String!
beforeEach {
string = "awesome"
}
it("creates a valid instance") {
qrCode = QRCode(string: string)
expect(qrCode).toNot(beNil())
}
it("encapsulates the passed string as ISO Latin1 converted data") {
qrCode = QRCode(string: string)
expect(qrCode.data).to(equal(string.data(using: .isoLatin1)))
}
it("can have optional params") {
qrCode = QRCode(string: string, backgroundColor: UIColor.blue, size: size)
expect(qrCode.backgroundColor).to(equal(UIColor.blue))
expect(qrCode.size).to(equal(size))
}
}
describe("init(url:color:backgroundColor:size:inputCorrection:)") {
var url: URL!
beforeEach {
url = URL(string: "http://example.com/amazing")
}
it("creates a valid instance") {
qrCode = QRCode(url: url)
expect(qrCode).toNot(beNil())
}
it("encapsulates the passed url as ISO Latin1 converted string data") {
qrCode = QRCode(url: url)
expect(qrCode.data).to(equal(url.absoluteString.data(using: .isoLatin1)))
}
it("can have optional params") {
qrCode = QRCode(url: url, size: size)
expect(qrCode.size).to(equal(size))
}
}
describe("image()") {
context("with default or sufficient size") {
it("creates image of optimal size for screen (1pt / datapoint)") {
expect(try? QRCode(string: "hallo")!.image().scale).to(equal(UIScreen.main.scale))
expect(try? QRCode(string: "hallo")!.image().size).to(equal(inherentSize))
}
}
it("throws when width is too small for amount of data") {
let desiredSize = CGSize(width: 10.0, height: 23.0)
expect {
try QRCode(string: "hallo", size: desiredSize)?.image()
}.to(throwError(QRCode.GenerationError.desiredSizeTooSmall(desired: desiredSize, actual: inherentSize)))
}
it("throws when height is too small for amount of data") {
let desiredSize = CGSize(width: 23.0, height: 10.0)
expect {
try QRCode(string: "hallo", size: desiredSize)?.image()
}.to(throwError(QRCode.GenerationError.desiredSizeTooSmall(desired: desiredSize, actual: inherentSize)))
}
it("throws when data ins generally too large") {
expect {
try QRCode(string: tooLongString())?.image()
}.to(throwError(QRCode.GenerationError.inputDataTooLarge(size: 2954)))
}
}
describe("unsafeImage") {
context("with empty data") {
it("still returns proper image") {
expect(QRCode(data: Data()).unsafeImage).toNot(beNil())
}
}
context("with non-empty data") {
beforeEach {
qrCode = QRCode(string: "hallo")
}
it("creates image of optimal size for screen (1pt / datapoint)") {
expect(qrCode.unsafeImage!.scale).to(equal(UIScreen.main.scale))
expect(qrCode.unsafeImage!.size).to(equal(inherentSize))
}
context("scale") {
it("properly adjusts UIImage scale") {
expect(QRCode(string: "hallo", scale: 1.0)!.unsafeImage!.scale).to(equal(1.0))
expect(QRCode(string: "hallo", scale: 2.0)!.unsafeImage!.scale).to(equal(2.0))
expect(QRCode(string: "hallo", scale: 3.0)!.unsafeImage!.scale).to(equal(3.0))
}
it("properly maintains UIImage target size") {
expect(QRCode(string: "hallo", scale: 1.0)!.unsafeImage!.size).to(equal(inherentSize))
expect(QRCode(string: "hallo", scale: 2.0)!.unsafeImage!.size).to(equal(inherentSize))
expect(QRCode(string: "hallo", scale: 3.0)!.unsafeImage!.size).to(equal(inherentSize))
}
}
it("can resize the image to desired dimensions, respecting scale") {
qrCode.size = size
qrCode.scale = 3
expect(qrCode.unsafeImage!.size).to(equal(size))
}
it("returns nil when width is too small for amount of data") {
let desiredSize = CGSize(width: 10.0, height: 23.0)
expect(QRCode(string: "hallo", size: desiredSize)?.unsafeImage).to(beNil())
}
it("returns nil when height is too small for amount of data") {
let desiredSize = CGSize(width: 23.0, height: 10.0)
expect(QRCode(string: "hallo", size: desiredSize)?.unsafeImage).to(beNil())
}
it("returns nil when data ins generally too large") {
expect(QRCode(string: tooLongString())?.unsafeImage).to(beNil())
}
}
}
describe("Equatable") {
it("is equal when all attributes are equal") {
expect(QRCode(string: "hallo")).to(equal(QRCode(data: "hallo".data(using: .isoLatin1)!)))
}
it("is not equal when any one attribute is not equal") {
expect(QRCode(string: "hallo")).toNot(equal(QRCode(string: "hallo1")))
expect(QRCode(string: "hallo", color: UIColor.red)).toNot(equal(QRCode(string: "hallo", color: UIColor.blue)))
expect(QRCode(string: "hallo", backgroundColor: UIColor.green)).toNot(equal(QRCode(string: "hallo", backgroundColor: UIColor.brown)))
expect(QRCode(string: "hallo", size: CGSize(width: 100, height: 100))).toNot(equal(QRCode(string: "hallo", size: CGSize(width: 100, height: 200))))
expect(QRCode(string: "hallo", scale: 1)).toNot(equal(QRCode(string: "hallo", scale: 2)))
expect(QRCode(string: "hallo", inputCorrection: .low)).toNot(equal(QRCode(string: "hallo", inputCorrection: .high)))
}
}
describe("caching") {
it("returns a cached image on subsequent calls") {
let qrCode = QRCode(string: "hallo")!
expect(qrCode.unsafeImage).to(equal(qrCode.unsafeImage))
}
it("flushes the cache once data changes") {
var qrCode = QRCode(string: "hallo")!
let firstImage = qrCode.unsafeImage
qrCode.data = "hallo".data(using: .isoLatin1)!
expect(firstImage).to(equal(qrCode.unsafeImage))
qrCode.data = "different".data(using: .isoLatin1)!
try? expect(firstImage).toNot(equal(qrCode.image()))
}
it("flushes the cache once color changes") {
var qrCode = QRCode(string: "hallo")!
let firstImage = qrCode.unsafeImage
qrCode.color = UIColor.black
expect(firstImage).to(equal(qrCode.unsafeImage))
qrCode.color = UIColor.red
try? expect(firstImage).toNot(equal(qrCode.image()))
}
it("flushes the cache once backgroundColor changes") {
var qrCode = QRCode(string: "hallo")!
let firstImage = qrCode.unsafeImage
qrCode.backgroundColor = UIColor.white
expect(firstImage).to(equal(qrCode.unsafeImage))
qrCode.backgroundColor = UIColor.red
try? expect(firstImage).toNot(equal(qrCode.image()))
}
it("flushes the cache once size changes") {
var qrCode = QRCode(string: "hallo")!
let firstImage = qrCode.unsafeImage
qrCode.size = nil
expect(firstImage).to(equal(qrCode.unsafeImage))
qrCode.size = CGSize(width: 100, height: 100)
try? expect(firstImage).toNot(equal(qrCode.image()))
}
it("flushes the cache once scale changes") {
var qrCode = QRCode(string: "hallo")!
let firstImage = qrCode.unsafeImage
qrCode.scale = UIScreen.main.scale
expect(firstImage).to(equal(qrCode.unsafeImage))
qrCode.scale = 42
try? expect(firstImage).toNot(equal(qrCode.image()))
}
it("flushes the cache once inputCorrection changes") {
var qrCode = QRCode(string: "hallo")!
let firstImage = qrCode.unsafeImage
qrCode.inputCorrection = .low
expect(firstImage).to(equal(qrCode.unsafeImage))
qrCode.inputCorrection = .medium
try? expect(firstImage).toNot(equal(qrCode.image()))
}
}
}
}
}
func tooLongString() -> String {
let maximumQRCodeByteCount = 2953
let tooLongString = (0...maximumQRCodeByteCount).map { _ in "x" }.reduce("", { $0 + $1 })
return tooLongString
}
| mit | 2e1041bc8103645c1ed6a5a02f917914 | 43.619608 | 167 | 0.493057 | 4.91066 | false | false | false | false |
tjw/swift | stdlib/public/core/UnmanagedOpaqueString.swift | 2 | 11520 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
public protocol _OpaqueString: class {
var length: Int { get }
func character(at index: Int) -> UInt16
// FIXME: This is not an NSString method; I'd like to use
// `getCharacters(_:,range:)`, but it would be weird to define
// `_SwiftNSRange` without an Objective-C runtime.
func copyCodeUnits(
from range: Range<Int>,
into dest: UnsafeMutablePointer<UInt16>)
}
@usableFromInline
@_fixed_layout
internal struct _UnmanagedOpaqueString {
#if _runtime(_ObjC) // FIXME unify
@usableFromInline
unowned(unsafe) let object: _CocoaString
#else
@usableFromInline
unowned(unsafe) let object: _OpaqueString
#endif
@usableFromInline
let range: Range<Int>
@usableFromInline
let isSlice: Bool
#if _runtime(_ObjC) // FIXME unify
@inlinable
init(_ object: _CocoaString, range: Range<Int>, isSlice: Bool) {
self.object = object
self.range = range
self.isSlice = isSlice
}
@inline(never)
init(_ object: _CocoaString) {
let count = _stdlib_binary_CFStringGetLength(object)
self.init(object, count: count)
}
@inlinable
init(_ object: _CocoaString, count: Int) {
self.init(object, range: 0..<count, isSlice: false)
}
#else
@inlinable
init(_ object: _OpaqueString, range: Range<Int>, isSlice: Bool) {
self.object = object
self.range = range
self.isSlice = isSlice
}
@inline(never)
init(_ object: _OpaqueString) {
self.init(object, count: object.length)
}
@inlinable
init(_ object: _OpaqueString, count: Int) {
self.init(object, range: 0..<count, isSlice: false)
}
#endif
}
extension _UnmanagedOpaqueString : Sequence {
typealias Element = UTF16.CodeUnit
@inlinable
func makeIterator() -> Iterator {
return Iterator(self, startingAt: range.lowerBound)
}
@inlinable // FIXME(sil-serialize-all)
internal func makeIterator(startingAt position: Int) -> Iterator {
return Iterator(self, startingAt: position)
}
@usableFromInline
@_fixed_layout
struct Iterator : IteratorProtocol {
internal typealias Element = UTF16.CodeUnit
#if _runtime(_ObjC) // FIXME unify
@usableFromInline
internal let _object: _CocoaString
#else
@usableFromInline
internal let _object: _OpaqueString
#endif
@usableFromInline
internal var _range: Range<Int>
@usableFromInline
internal var _buffer = _FixedArray16<Element>()
@usableFromInline
internal var _bufferIndex: Int8 = 0
@inlinable
init(_ string: _UnmanagedOpaqueString, startingAt start: Int) {
self._object = string.object
self._range = start..<string.range.upperBound
}
@inlinable
@inline(__always)
mutating func next() -> Element? {
if _fastPath(_bufferIndex < _buffer.count) {
let result = _buffer[Int(_bufferIndex)]
_bufferIndex += 1
return result
}
if _slowPath(_range.isEmpty) { return nil }
return _nextOnSlowPath()
}
@usableFromInline
@inline(never)
mutating func _nextOnSlowPath() -> Element {
// Fill buffer
_sanityCheck(!_range.isEmpty)
let end = Swift.min(
_range.lowerBound + _buffer.capacity,
_range.upperBound)
let r: Range<Int> = _range.lowerBound..<end
let opaque = _UnmanagedOpaqueString(_object, range: r, isSlice: true)
_buffer.count = r.count
_buffer.withUnsafeMutableBufferPointer { b in
_sanityCheck(b.count == r.count)
opaque._copy(into: b)
}
_bufferIndex = 1
_range = r.upperBound ..< _range.upperBound
_fixLifetime(_object)
return _buffer[0]
}
}
}
extension _UnmanagedOpaqueString : RandomAccessCollection {
internal typealias IndexDistance = Int
internal typealias Indices = Range<Index>
internal typealias SubSequence = _UnmanagedOpaqueString
@_fixed_layout
@usableFromInline
struct Index : Strideable {
@usableFromInline
internal var _value: Int
@inlinable
@inline(__always)
init(_ value: Int) {
self._value = value
}
@inlinable
@inline(__always)
func distance(to other: Index) -> Int {
return other._value - self._value
}
@inlinable
@inline(__always)
func advanced(by n: Int) -> Index {
return Index(_value + n)
}
}
@inlinable
var startIndex: Index {
return Index(range.lowerBound)
}
@inlinable
var endIndex: Index {
return Index(range.upperBound)
}
@inlinable
var count: Int {
return range.count
}
@inlinable // FIXME(sil-serialize-all)
subscript(position: Index) -> UTF16.CodeUnit {
_sanityCheck(position._value >= range.lowerBound)
_sanityCheck(position._value < range.upperBound)
#if _runtime(_ObjC) // FIXME unify
return _cocoaStringSubscript(object, position._value)
#else
return object.character(at: position._value)
#endif
}
@inlinable // FIXME(sil-serialize-all)
subscript(bounds: Range<Index>) -> _UnmanagedOpaqueString {
_sanityCheck(bounds.lowerBound._value >= range.lowerBound)
_sanityCheck(bounds.upperBound._value <= range.upperBound)
let b: Range<Int> = bounds.lowerBound._value ..< bounds.upperBound._value
let newSlice = self.isSlice || b.count != range.count
return _UnmanagedOpaqueString(object, range: b, isSlice: newSlice)
}
}
extension _UnmanagedOpaqueString : _StringVariant {
internal typealias Encoding = Unicode.UTF16
internal typealias CodeUnit = Encoding.CodeUnit
@inlinable
var isASCII: Bool {
@inline(__always) get { return false }
}
@inlinable
@inline(__always)
func _boundsCheck(_ i: Index) {
_precondition(i._value >= range.lowerBound && i._value < range.upperBound,
"String index is out of bounds")
}
@inlinable
@inline(__always)
func _boundsCheck(_ range: Range<Index>) {
_precondition(
range.lowerBound._value >= self.range.lowerBound &&
range.upperBound._value <= self.range.upperBound,
"String index range is out of bounds")
}
@inlinable
@inline(__always)
func _boundsCheck(offset: Int) {
_precondition(offset >= 0 && offset < range.count,
"String index is out of bounds")
}
@inlinable
@inline(__always)
func _boundsCheck(offsetRange range: Range<Int>) {
_precondition(range.lowerBound >= 0 && range.upperBound <= count,
"String index range is out of bounds")
}
@inlinable // FIXME(sil-serialize-all)
subscript(offset: Int) -> UTF16.CodeUnit {
_sanityCheck(offset >= 0 && offset < count)
#if _runtime(_ObjC) // FIXME unify
return _cocoaStringSubscript(object, range.lowerBound + offset)
#else
return object.character(at: range.lowerBound + offset)
#endif
}
@inlinable // FIXME(sil-serialize-all)
subscript(offsetRange: Range<Int>) -> _UnmanagedOpaqueString {
_sanityCheck(offsetRange.lowerBound >= 0)
_sanityCheck(offsetRange.upperBound <= range.count)
let b: Range<Int> =
range.lowerBound + offsetRange.lowerBound ..<
range.lowerBound + offsetRange.upperBound
let newSlice = self.isSlice || b.count != range.count
return _UnmanagedOpaqueString(object, range: b, isSlice: newSlice)
}
@inlinable // FIXME(sil-serialize-all)
internal subscript(offsetRange: PartialRangeUpTo<Int>) -> SubSequence {
_sanityCheck(offsetRange.upperBound <= range.count)
let b: Range<Int> =
range.lowerBound ..<
range.lowerBound + offsetRange.upperBound
let newSlice = self.isSlice || b.count != range.count
return _UnmanagedOpaqueString(object, range: b, isSlice: newSlice)
}
@inlinable // FIXME(sil-serialize-all)
internal subscript(offsetRange: PartialRangeThrough<Int>) -> SubSequence {
_sanityCheck(offsetRange.upperBound <= range.count)
let b: Range<Int> =
range.lowerBound ..<
range.lowerBound + offsetRange.upperBound + 1
let newSlice = self.isSlice || b.count != range.count
return _UnmanagedOpaqueString(object, range: b, isSlice: newSlice)
}
@inlinable // FIXME(sil-serialize-all)
internal subscript(offsetRange: PartialRangeFrom<Int>) -> SubSequence {
_sanityCheck(offsetRange.lowerBound < range.count)
let b: Range<Int> =
range.lowerBound + offsetRange.lowerBound ..<
range.upperBound
let newSlice = self.isSlice || b.count != range.count
return _UnmanagedOpaqueString(object, range: b, isSlice: newSlice)
}
@inlinable // FIXME(sil-serialize-all)
internal func _copy(
into dest: UnsafeMutableBufferPointer<UTF16.CodeUnit>
) {
_sanityCheck(dest.count >= range.count)
guard range.count > 0 else { return }
#if _runtime(_ObjC) // FIXME unify
_cocoaStringCopyCharacters(
from: object,
range: range,
into: dest.baseAddress!)
#else
object.copyCodeUnits(from: range, into: dest.baseAddress!)
#endif
}
@inlinable // FIXME(sil-serialize-all)
internal func _copy<TargetCodeUnit>(
into dest: UnsafeMutableBufferPointer<TargetCodeUnit>
)
where TargetCodeUnit : FixedWidthInteger & UnsignedInteger {
guard TargetCodeUnit.bitWidth == 16 else {
_sanityCheckFailure("Narrowing copy from opaque strings is not implemented")
}
_sanityCheck(dest.count >= range.count)
guard range.count > 0 else { return }
let d = UnsafeMutableRawPointer(dest.baseAddress!)
.assumingMemoryBound(to: UTF16.CodeUnit.self)
#if _runtime(_ObjC) // FIXME unify
_cocoaStringCopyCharacters(from: object, range: range, into: d)
#else
object.copyCodeUnits(from: range, into: d)
#endif
}
@usableFromInline // FIXME(sil-serialize-all)
@_fixed_layout // FIXME(resilience)
internal struct UnicodeScalarIterator : IteratorProtocol {
var _base: _UnmanagedOpaqueString.Iterator
var _peek: UTF16.CodeUnit?
@usableFromInline // FIXME(sil-serialize-all)
init(_ base: _UnmanagedOpaqueString) {
self._base = base.makeIterator()
self._peek = _base.next()
}
@usableFromInline // FIXME(sil-serialize-all)
mutating func next() -> Unicode.Scalar? {
if _slowPath(_peek == nil) { return nil }
let u0 = _peek._unsafelyUnwrappedUnchecked
_peek = _base.next()
if _fastPath(UTF16._isScalar(u0)) {
return Unicode.Scalar(_unchecked: UInt32(u0))
}
if UTF16.isLeadSurrogate(u0) && _peek != nil {
let u1 = _peek._unsafelyUnwrappedUnchecked
if UTF16.isTrailSurrogate(u1) {
_peek = _base.next()
return UTF16._decodeSurrogates(u0, u1)
}
}
return Unicode.Scalar._replacementCharacter
}
}
@usableFromInline // FIXME(sil-serialize-all)
@inline(never)
func makeUnicodeScalarIterator() -> UnicodeScalarIterator {
return UnicodeScalarIterator(self)
}
}
#if _runtime(_ObjC)
extension _UnmanagedOpaqueString {
@usableFromInline
@inline(never)
internal func cocoaSlice() -> _CocoaString {
guard isSlice else { return object }
// FIXME: This usually copies storage; maybe add an NSString subclass
// for opaque slices?
return _cocoaStringSlice(object, range)
}
}
#endif
| apache-2.0 | ddc11453f79da8b1c7399757ce5a216e | 28.090909 | 82 | 0.668403 | 4.131994 | false | false | false | false |
samuelzhou/SceneKitTutorials | CameraAndLights/CameraAndLights/ViewController.swift | 1 | 3844 | //
// ViewController.swift
// CameraAndLights
//
// Created by Samuel Zhou on 8/31/14.
// Copyright (c) 2014 Samtina Studio. All rights reserved.
//
// This file contains the demo code for the Part 2 of SceneKit Tutorial
//
import UIKit
import SceneKit
class ViewController: UIViewController {
var myView : SCNView?
override func viewDidLoad() {
super.viewDidLoad()
myView = SCNView(frame: self.view.frame)
let myScene = SCNScene()
myView?.scene = myScene
// You can uncomment the following line when no custom light there.
myView?.autoenablesDefaultLighting = true
myView?.allowsCameraControl = true
myView?.showsStatistics = true
let myBox = SCNBox(width: 15, height: 10, length: 12, chamferRadius: 0)
let myBoxNode = SCNNode(geometry: myBox)
myBoxNode.position = SCNVector3(x: 0, y: 0, z: 0)
myScene.rootNode.addChildNode(myBoxNode)
//
// Demo a sample Camera in scene
//
let myCamera = SCNCamera()
myCamera.xFov = 40
myCamera.yFov = 40
let myCameraNode = SCNNode()
myCameraNode.camera = myCamera
myCameraNode.position = SCNVector3(x: -25, y: 20, z: 30)
myCameraNode.orientation = SCNQuaternion(x: -0.26, y: -0.32, z: 0, w: 0.91)
myScene.rootNode.addChildNode(myCameraNode)
//
// Demo Omni Light by uncommenting the following snippet
//
/*
let myOmniLight = SCNLight()
let myOmniLightNode = SCNNode()
myOmniLight.type = SCNLightTypeOmni
myOmniLight.color = UIColor.yellowColor()
myOmniLightNode.light = myOmniLight
myOmniLightNode.position = SCNVector3(x: -30, y: 30, z: 60)
myScene.rootNode.addChildNode(myOmniLightNode)
*/
//
// Demo Ambient Light by uncommenting the following snippet
//
/*
let myAmbientLight = SCNLight()
myAmbientLight.type = SCNLightTypeAmbient
myAmbientLight.color = UIColor.yellowColor()
let myAmbientLightNode = SCNNode()
myAmbientLightNode.light = myAmbientLight
myScene.rootNode.addChildNode(myAmbientLightNode)
*/
//
// Demo Direct Light by uncommenting the following snippet
//
/*
let myDirectLight = SCNLight()
myDirectLight.type = SCNLightTypeDirectional
myDirectLight.color = UIColor.yellowColor()
let myDirectLightNode = SCNNode()
myDirectLightNode.light = myDirectLight
myDirectLightNode.orientation = SCNQuaternion(x: 0, y: 0, z: 1, w: 0)
myScene.rootNode.addChildNode(myDirectLightNode)
*/
//
// Demo Spot Light by uncommenting the following snippet
//
/*
let mySpotLight = SCNLight()
mySpotLight.type = SCNLightTypeSpot
mySpotLight.color = UIColor.yellowColor()
let mySpotLightNode = SCNNode()
mySpotLightNode.light = mySpotLight
mySpotLightNode.position = SCNVector3(x: 0, y: 0, z: 20)
mySpotLightNode.orientation = SCNQuaternion(x: 0, y: 0, z: 1, w: 0.5)
myScene.rootNode.addChildNode(mySpotLightNode)
*/
self.view.addSubview(myView!)
}
override func touchesEnded(touches: NSSet!, withEvent event: UIEvent!) {
//
// In this delegate, you can get the positions and orientations of camera
// when setting allowsCameraControl to true.
//
let quaternion = myView?.pointOfView.orientation
let position = myView?.pointOfView.position
println("Orientation: (\(quaternion?.x),\(quaternion?.y),\(quaternion?.z),\(quaternion?.w)) Position: (\(position?.x),\(position?.y),\(position?.z)")
}
}
| gpl-2.0 | c2a0ca7cc62b5da1b2267f53e9dc59c6 | 33.630631 | 157 | 0.620968 | 4.418391 | false | false | false | false |
roshkadev/Form | Form/Classes/Form/Form.swift | 1 | 16776 | //
// Form.swift
// Pods
//
// Created by Roshka on 4/21/17.
//
//
// - Show and hide field(s) DONE
// - Add new field (Switch) DONE
// - Add new field (Slider) DONE
// - Add new field (Stepper) DONE
// - Support device text size DONE
// - Support rotation DONE
// - Stop scroll on edges of fields DONE
// - Add new field (SegmentedSwitch) DONE
// - Add new Picker type (keyboard and table view based actionsheet)
// - Add new field Location (apple maps)
// - Add new field Image (gallery and camera)
// - Add new field File (via Activity VC, photo or video, iCloud Drive, Dropbox, Google Drive
// - Add new field Contact
// - Add Switch radio groups
// - Add Check radio groups
// - Add option to hide and also to disable fields
// - Add Input security groupings
// - Add custom field example
// - Add currency option for Inputs
// - Add tags for text view and text field
// - Multiple fields on the same row
// - Input formatters:
// - Currency
// - Phone numbers
// - Credit cards
// -
// - Required/non-required fields, asterisks to denote
// - Labels options:
// - leading aligned inside field (align input areas)
// - floating
// - above field
// - Input option to include leading/trailing icon
// - Include in README examples of forms such as contact on iOS, hotel, booking, signup, etc.
// - Add option to field to show help text.
// - Field hint popover box
// - UI tests
// - Unit tests
// - Smart navigation to go to next Field (even if not a first responder), ignore hidden fields.
// - Ignore hidden fields when validating a form
// - Add label types (above, inset, floating)
// - Add new field (TextArea) with dynamic height and placeholder
// - Add new field (Check) with dynamic height and placeholder
// - Date picker, add common date formatters
// Other's Features
// - All rows can automatically contain a label (outside, inside, floating)
// - All rows can be disabled
// - Navigation via (< and > arrows, skip disabled or non-first responder fields)
// - Show/hide rows
// - Validation reaction (add red, inline message)
// -
// - Date picker (embedded or keyboard), short style, long style
// - Check on/off
// - Switch row (radio, check, switch)
// - Slider row (value label to the right)
// - Stepper row (value label to the left)
// - Segmented row
// - Action sheet row (list of options)
// - Alert row (list of options)
// - Push row (shows table view supporting sections, multiple selection) on a new screen with list of options
// - Location row (Apple Maps), look into Google Maps option too using Google Maps pod
// - Image row (one image)
// - Picker row (embedded or keyboard)
// - Input row (text, decimal, integer, url, name, phone, password, email, twitter, account?, zip code, currency, scientific, spell out, weight, energy), restrictions (equal to other row)
//
// - Instagram Signup (100%)
// - Add event iOS form (from Calender app)
import UIKit
public class Form: NSObject {
/// The containing view controller.
var viewController: UIViewController
/// The view of the containing view (normally the containing view controller's view).
var containingView: UIView
/// A scroll view to allow the form to scroll vertically.
var scrollView = FormScrollView()
/// The vertical stack view contains one arranged subview for each row.
var verticalStackView = UIStackView()
/// The form's rows (a row contains one or more fields).
var rows = [Row]()
/// The form's fields.
var fields: [Field] {
return rows.flatMap { $0.fields }
}
var activeField: Field?
var enableNavigation = true
var isPagedScrollingEnabled = false
var nextView: UIView!
var nextButton: UIButton!
var nextViewVerticalConstraint: NSLayoutConstraint!
var currentField: Field?
let nextButtonWidth: CGFloat = 30
public var padding = Space.default
@discardableResult
public init(in viewController: UIViewController, padding: Space = .none, constructor: ((Form) -> Void)? = nil) {
self.viewController = viewController
self.padding = padding
containingView = viewController.view
super.init()
scrollView.form = self
scrollView.delegate = self
scrollView.translatesAutoresizingMaskIntoConstraints = false
containingView.addSubview(scrollView)
containingView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(\(padding.left))-[scrollView]-(\(padding.right))-|", options: [], metrics: nil, views: [ "scrollView": scrollView ]))
containingView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-(\(padding.top))-[scrollView]-(\(padding.bottom))-|", options: [], metrics: nil, views: [ "scrollView": scrollView ]))
verticalStackView.axis = .vertical
verticalStackView.alignment = .fill
verticalStackView.spacing = 0
verticalStackView.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(verticalStackView)
scrollView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[verticalStackView]|", options: [], metrics: nil, views: [ "verticalStackView": verticalStackView ]))
containingView.addConstraint(NSLayoutConstraint(item: verticalStackView, attribute: .left, relatedBy: .equal, toItem: containingView, attribute: .left, multiplier: 1, constant: 0))
containingView.addConstraint(NSLayoutConstraint(item: containingView, attribute: .right, relatedBy: .equal, toItem: verticalStackView, attribute: .right, multiplier: 1, constant: 0))
scrollView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[verticalStackView]|", options: [], metrics: nil, views: [ "verticalStackView": verticalStackView ]))
// let spaceView = UIView()
// spaceView.translatesAutoresizingMaskIntoConstraints = false
// spaceView.backgroundColor = UIColor.green
// spaceView.setContentHuggingPriority(UILayoutPriorityDefaultLow, for: .vertical)
// verticalStackView.addArrangedSubview(spaceView)
// Add the fields to the form.
constructor?(self)
// Register for keyboard notifications to allow form fields to avoid the keyboard.
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow), name: .UIKeyboardDidShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: .UIKeyboardWillHide, object: nil)
// Register for dynamic type changes.
NotificationCenter.default.addObserver(self, selector: #selector(didChangeContentSizeCategory), name: .UIContentSizeCategoryDidChange, object: nil)
// nextView = UIView()
// nextView.backgroundColor = .green
// nextView.translatesAutoresizingMaskIntoConstraints = false
// containingView.addSubview(nextView)
// nextButton = UIButton()
// nextButton.translatesAutoresizingMaskIntoConstraints = false
// nextButton.setTitle("▶️", for: .normal)
// nextButton.addTarget(self, action: #selector(nextButtonAction), for: .touchUpInside)
// nextView.addSubview(nextButton)
// containingView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[nextView(\(nextButtonWidth))]|", options: [], metrics: nil, views: [ "nextView": nextView ]))
// containingView.addConstraint(NSLayoutConstraint(item: nextView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0, constant: 50))
// nextViewVerticalConstraint = NSLayoutConstraint(item: nextView, attribute: .bottom, relatedBy: .equal, toItem: containingView, attribute: .bottom, multiplier: 1, constant: 0)
// containingView.addConstraint(nextViewVerticalConstraint!)
//
// nextView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[nextButton]|", options: [], metrics: nil, views: [ "nextButton": nextButton ]))
// nextView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[nextButton]|", options: [], metrics: nil, views: [ "nextButton": nextButton ]))
}
public var parameters: [String: Any]? {
return fields.reduce([String: Any](), { partialResult, field in
guard let key = field.key else { return partialResult }
guard let value = field.value else { return partialResult }
var updatedResult = partialResult
updatedResult[key] = value
return updatedResult
})
}
public var isValid: Bool {
return fields.reduce(true) { partialResult, input in
let isInputValid = input.isValidForSubmit()
return partialResult && isInputValid
}
}
deinit {
print("Form deinitialized")
}
}
extension Form: UIScrollViewDelegate {
public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
guard isPagedScrollingEnabled else { return }
print("original target: ", targetContentOffset.pointee)
var targetOffset = targetContentOffset.pointee
targetOffset.x = scrollView.center.x
let scrollHeight = scrollView.bounds.height - scrollView.contentInset.bottom
targetOffset.y += scrollHeight
print("target: ", targetOffset)
print("scrollView: ", scrollView.bounds.height)
print("scrollView bottom: ", scrollView.contentInset.bottom)
let field = fields.filter {
return $0.view.frame.contains(targetOffset)
}.first
if let field = field {
let finalTargetOffset = field.view.frame.origin.y - scrollHeight + field.view.frame.height
print("Found: ", finalTargetOffset)
targetContentOffset.pointee.y = finalTargetOffset
}
// let targetCellIndexPath = self.indexPathForRowAtPoint(targetContentOffsetCorrected)
//
// let targetCellRect = self.rectForRowAtIndexPath(targetCellIndexPath!)
//
// var targetCellYCenter = targetCellRect.origin.y
//
// let isJumpingDown = (targetContentOffsetCorrected.y % cellHeight) > (cellHeight / 2)
//
// if isJumpingDown == true {
// let nextPlace = Int(targetContentOffsetCorrected.y) / Int(cellHeight)
// targetCellYCenter = (CGFloat(nextPlace) * cellHeight) + cellHeight
// }
//
// targetContentOffset.memory.y = targetCellYCenter - contentInsetY
}
}
extension Form {
/// Add a field to the form (the field is implicitly wrapped in a new row).
@discardableResult
public func add(field: Field) -> Self {
Row(in: self).add(field: field)
// Take the current dynamic font.
field.didChangeContentSizeCategory()
return self
}
/// Add a row to the form.
@discardableResult
public func add(row: Row) -> Self {
verticalStackView.addArrangedSubview(row.horizontalStackView)
rows.append(row)
return self
}
/// Add a view to the form.
@discardableResult
public func add(view: UIView) -> Self {
Row(in: self).add(view: view)
return self
}
@discardableResult
public func navigation(_ navigation: Bool) -> Self {
enableNavigation = navigation
fields.flatMap { $0 as? Input }.forEach {
if $0.textField.keyboardType == .numberPad || $0.textField.keyboardType == .decimalPad || $0.textField.keyboardType == .phonePad {
// $0.textField.inputAccessoryView = NextInputAccessoryView()
} else {
$0.textField.returnKeyType = .next
}
}
fields.flatMap { $0 as? Picker }.forEach {
// $0.textField?.inputAccessoryView = NextInputAccessoryView()
}
return self
}
@discardableResult
public func pagedScrolling(_ pagedScrolling: Bool) -> Self {
isPagedScrollingEnabled = pagedScrolling
return self
}
internal func assign(activeField: Field) {
self.activeField = activeField
}
// internal func moveNextButton(to field: Field?) {
// if let constraint = nextViewVerticalConstraint {
// containingView.removeConstraint(constraint)
// }
//
// guard let toField = field else {
// nextView.isHidden = true
// return
// }
//
// nextView.isHidden = false
// toField.rightContainerLayoutConstraint.constant = 100
// toField.rightScrollLayoutConstraint.constant = 100
//
// nextViewVerticalConstraint = NSLayoutConstraint(item: nextView, attribute: .bottom, relatedBy: .equal, toItem: toField.view, attribute: .bottom, multiplier: 1, constant: 0)
// containingView.addConstraint(nextViewVerticalConstraint!)
// currentField = toField
// }
internal func moveFocusFrom(field fromField: Field, toField: Field) {
if toField.canBecomeFirstResponder {
toField.becomeFirstResponder()
} else {
fromField.resignFirstResponder()
}
}
/// Assign the next field as first responder.
internal func didTapNextFrom(field fromField: Field) {
let index = fields.filter { $0.view.isHidden == false }.index { $0.view == fromField.view }
if let nextIndex = index?.advanced(by: 1), fields.indices.contains(nextIndex) {
let nextField = fields[fields.startIndex.distance(to: nextIndex)]
moveFocusFrom(field: fromField, toField: nextField)
} else {
// Wrap around to bring focus to the first field in the form.
if fields.indices.contains(fields.startIndex) {
let nextField = fields[fields.startIndex]
moveFocusFrom(field: fromField, toField: nextField)
}
}
}
func nextButtonAction(button: UIButton) {
if let field = currentField {
didTapNextFrom(field: field)
}
}
}
extension Form {
// #MARK: - Notifications
func keyboardWillShow(notification: Notification) {
if let info = notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue {
let keyboardHeight = info.cgRectValue.size.height
let contentInset = UIEdgeInsetsMake(0, 0, keyboardHeight, 0)
scrollView.contentInset = contentInset
scrollView.scrollIndicatorInsets = contentInset
}
}
func keyboardDidShow(notification: Notification) {
if let info = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue, let activeView = activeField?.view, let bottomPadding = activeField?.padding.bottom {
let keyboardHeight = info.cgRectValue.size.height
let statusBarHeight: CGFloat = 0 //UIApplication.shared.statusBarFrame.height
let navBarHeight = viewController.navigationController?.navigationBar.frame.height ?? 0
var availableRect = containingView.frame
availableRect.origin.y = statusBarHeight + navBarHeight
availableRect.size.height -= keyboardHeight - statusBarHeight - navBarHeight
if availableRect.contains(activeView.frame) == false {
print(scrollView.frame, scrollView.contentSize, activeView.frame)
scrollView.setContentOffset(CGPoint(x: 0, y: scrollView.contentOffset.y + bottomPadding), animated: true)
}
}
}
func keyboardWillHide(notification: Notification) {
scrollView.contentInset = .zero
scrollView.scrollIndicatorInsets = .zero
}
func didChangeContentSizeCategory(notification: Notification) {
fields.forEach { $0.label?.assignPreferredFont() }
}
}
extension UIView {
func shake() {
let animation = CAKeyframeAnimation(keyPath: "transform.translation.x")
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.duration = 0.6
animation.values = [-20.0, 20.0, -20.0, 20.0, -10.0, 10.0, -5.0, 5.0, 0.0 ]
layer.add(animation, forKey: "shake")
}
}
| mit | a32b24e4f72b4494e2bbb16ad0afd411 | 39.610169 | 210 | 0.657823 | 4.79337 | false | false | false | false |
jairoeli/Habit | Zero/Sources/Utils/YearProgress.swift | 1 | 1421 | //
// YearProgress.swift
// Zero
//
// Created by Jairo Eli de Leon on 10/9/17.
// Copyright © 2017 Jairo Eli de León. All rights reserved.
//
import Foundation
import UIKit
class CalculateProgress: NSObject {
class func result() -> String {
let calendar = NSCalendar.current
let currentDate = Date()
guard let passedDays = calendar.ordinality(of: .day, in: .year, for: currentDate) else { return "" }
let year = calendar.component(.year, from: currentDate)
var daysInYear = 0
if year % 4 == 0 && year % 400 != 0 || year % 400 == 0 {
daysInYear = 366
} else {
daysInYear = 365
}
let progress = Float(passedDays) / Float(daysInYear) * 100
var string = ""
for i in 0 ..< 20 {
if i < Int(progress / 5) {
string += "▓"
} else {
string += "░"
}
}
return string
}
class func percent() -> String {
let calendar = NSCalendar.current
let currentDate = Date()
guard let passedDays = calendar.ordinality(of: .day, in: .year, for: currentDate) else { return "" }
let year = calendar.component(.year, from: currentDate)
var daysInYear = 0
if year % 4 == 0 && year % 400 != 0 || year % 400 == 0 {
daysInYear = 366
} else {
daysInYear = 365
}
let progress = Float(passedDays) / Float(daysInYear) * 100
let string = "\(Int(progress))%"
return string
}
}
| mit | 9c8d31519e1b75c213010d660e7b0f59 | 22.983051 | 104 | 0.587986 | 3.743386 | false | false | false | false |
joelconnects/FlipTheBlinds | FlipTheBlinds/IBFromViewController.swift | 1 | 3251 | //
// IBFromViewController.swift
// FlipTheBlinds
//
// Created by Joel Bell on 1/2/17.
// Copyright © 2017 Joel Bell. All rights reserved.
//
import UIKit
// MARK: Main
class IBFromViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
configImageView()
configButton()
}
@objc func buttonTapped(_ sender: UIButton) {
self.performSegue(withIdentifier: "modalSegue", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "modalSegue", let destinationViewController = segue.destination as? IBToViewController {
// POD: Set transitioningDelegate
destinationViewController.transitioningDelegate = self
}
}
}
// MARK: Configure View
extension IBFromViewController {
private func configImageView() {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
imageView.image = #imageLiteral(resourceName: "treeGlobeImage")
view.addSubview(imageView)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
imageView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
imageView.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true
}
private func configButton() {
let screenWidth = UIScreen.main.bounds.size.width
let screenHeight = UIScreen.main.bounds.size.height
let buttonSize: CGFloat = 60
let buttonYconstant: CGFloat = 50
let buttonXorigin = (screenWidth / 2) - (buttonSize / 2)
let buttonYorigin = screenHeight - buttonSize - buttonYconstant
let button = UIButton(type: .custom)
button.alpha = 0.7
button.backgroundColor = UIColor.black
button.setTitleColor(UIColor.white, for: UIControl.State())
button.setTitle("GO", for: UIControl.State())
button.frame = CGRect(x: buttonXorigin, y: buttonYorigin, width: buttonSize, height: buttonSize)
button.layer.cornerRadius = 0.5 * button.bounds.size.width
button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
view.addSubview(button)
}
}
// POD: Modal Extension
extension IBFromViewController: UIViewControllerTransitioningDelegate {
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return FTBAnimationController(displayType: .present, direction: .up, speed: .moderate)
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return FTBAnimationController(displayType: .dismiss, direction: .down, speed: .moderate)
}
}
| mit | 852615e48e3e1e463308942cce312366 | 29.660377 | 170 | 0.654769 | 5.434783 | false | false | false | false |
See-Ku/SK4Toolkit | SK4Toolkit/core/SK4ImageCache.swift | 1 | 4746 | //
// SK4ImageCache.swift
// SK4Toolkit
//
// Created by See.Ku on 2016/03/27.
// Copyright (c) 2016 AxeRoad. All rights reserved.
//
import UIKit
/// シンプルなイメージキャッシュクラス
public class SK4ImageCache {
/// キャッシュファイルを保存するディレクトリ
public let dir: String
/// キャッシュファイルの接頭辞
public let prefix: String
/// キャッシュファイルの接尾辞
public let suffix: String
let cache = NSCache()
/// 初期化
public init(dir: String, prefix: String, suffix: String, cacheLimit: Int) {
self.dir = dir
self.prefix = prefix
self.suffix = suffix
cache.evictsObjectsWithDiscardedContent = true
cache.countLimit = cacheLimit
}
/// キャッシュの最大数を指定して初期化
public convenience init(cacheLimit: Int = 100) {
let dir = sk4GetCachesDirectory()
let prefix = "###"
let suffix = ".png"
self.init(dir: dir, prefix: prefix, suffix: suffix, cacheLimit: cacheLimit)
}
// /////////////////////////////////////////////////////////////
// MARK: - イメージを生成&キャッシュファイル使用
var makingList = Set<String>()
/// キャッシュファイルから読み込み。存在しない場合はイメージを作成 ※イメージを生成する処理はグローバルキューで実行
public func manageCacheFile(name: String, imageMaker: (()->UIImage?)) -> UIImage? {
// キャッシュファイルに保存されているか?
if let image = loadCacheFile(name) {
return image
}
// すでにイメージを作成中か?
if makingList.contains(name) {
return nil
}
// 新しくイメージを作成
makingList.insert(name)
sk4AsyncGlobal() {
let image = imageMaker()
sk4AsyncMain() {
self.saveCacheFile(name, image: image)
self.makingList.remove(name)
}
}
return nil
}
/// イメージをキャッシュファイルから読み込み
public func loadCacheFile(name: String) -> UIImage? {
let path = makeCachePath(name)
return loadImage(path)
}
/// イメージをキャッシュファイルに保存
public func saveCacheFile(name: String, image: UIImage?) {
let path = makeCachePath(name)
setImage(path, image: image)
if let image = image {
// イメージをキャッシュファイルに保存
if let data = UIImagePNGRepresentation(image) {
data.writeToFile(path, atomically: true)
} else {
sk4DebugLog("UIImagePNGRepresentation error: \(name)")
}
} else {
// キャッシュされたファイルを削除
sk4DeleteFile(path)
}
}
// /////////////////////////////////////////////////////////////
// MARK: - イメージをファイルから読み込み&メモリにキャッシュ
/// パスを指定してイメージを読み込み
public func loadImage(path: String, mode: UIImageRenderingMode = .Automatic) -> UIImage? {
// キャッシュされているか?
if let image = getImage(path) {
return image
}
// 必要ならイメージを読み込み&レンダリングモードに対応
var image = UIImage(contentsOfFile: path)
if mode != .Automatic {
image = image?.imageWithRenderingMode(mode)
}
// 展開後のイメージをキャッシュ
setImage(path, image: image)
return image
}
/// バンドルされたイメージを読み込み
public func loadBundleImage(name: String, ofType: String = "png", mode: UIImageRenderingMode = .Automatic) -> UIImage? {
let bundle = NSBundle.mainBundle()
if let path = bundle.pathForResource(name, ofType: ofType) {
return loadImage(path, mode: mode)
}
return nil
}
// /////////////////////////////////////////////////////////////
// MARK: - イメージを直接登録/取得
/// イメージをキャッシュに登録
public func setImage(name: String, image: UIImage?) {
if let image = image {
cache.setObject(image, forKey: name)
} else {
cache.removeObjectForKey(name)
}
}
/// イメージをキャッシュから取得
public func getImage(name: String) -> UIImage? {
return cache.objectForKey(name) as? UIImage
}
// /////////////////////////////////////////////////////////////
// MARK: - その他
/// キャッシュされたイメージをすべて削除
public func removeCacheAll() {
cache.removeAllObjects()
}
/// イメージのキャッシュファイルをすべて削除
public func deleteCacheFileAll() {
let ar = sk4FileListAtPath(dir)
for fn in ar {
if fn.hasPrefix(prefix) && fn.hasSuffix(suffix) {
sk4DeleteFile(dir + fn)
}
}
}
/// キャッシュファイルのパスを生成
public func makeCachePath(name: String) -> String {
return dir + prefix + name + suffix
}
}
// eof
| mit | 64ea0b9c3dfb11888650eeb42cb1d95c | 20.714286 | 121 | 0.638947 | 2.783883 | false | false | false | false |
neonichu/Azkaban | Sources/azkaban/main.swift | 1 | 3264 | import Chores
import Commander
extension String {
private func split(char: Character) -> [String] {
return self.characters.split { $0 == char }.map(String.init)
}
var lines: [String] {
return split("\n")
}
var words: [String] {
return split(" ")
}
}
// from: http://stackoverflow.com/a/28341290
func iterateEnum<T: Hashable>(_: T.Type) -> AnyGenerator<T> {
var i = -1
return AnyGenerator {
i += 1
let next = withUnsafePointer(&i) { UnsafePointer<T>($0).memory }
return next.hashValue == i ? next : nil
}
}
Group {
$0.command("available", Option("type", "", description: "Filter the list by type"),
description: "List available plugins") { type in
waitForPackages { packages in
let packages = try packages.filter { package in
if package.isInstalled { return false }
if type == "" { return true }
if let type = ATZPackageType(rawValue: type) {
return try packageType(package) == type
}
throw Errors.UnknownPackageType(type)
}.map { $0.name as String }
print(packages.joinWithSeparator("\n"))
}
}
$0.command("available_types", description: "List available package types") {
iterateEnum(ATZPackageType).forEach { print($0.rawValue) }
}
$0.command("install", Argument("name"),
Option("packages", "", description: "Use a local JSON file as package list"),
description: "Install a plugin") { (name: String, packages: String) in
if let url = NSURL(string: name), lastComponent = url.lastPathComponent where name.hasPrefix("http") {
waitFor { queue {
let plugin = ATZPlugin(dictionary: [ "name": lastComponent, "url": name ])
let result = plugin.installAndReport()
exit(result ? 0 : 1)
} }
}
let packageClosure = { (packages: [ATZPackage]) in
let packages = packages.filter { $0.name == name }
packages.forEach { $0.installAndReport() }
}
if packages != "" {
packageClosure(try parsePackagesAtPath(packages))
} else {
waitForPackages(packageClosure)
}
}
$0.command("list", description: "List installed plugins") {
waitForPackages { packages in
let packages = packages.filter { $0.isInstalled }.map { $0.name as String }
print(packages.joinWithSeparator("\n"))
}
}
$0.command("reset", description: "Resets loading preferences for currently active Xcode") {
let result = >["xcodebuild", "-version"]
if let version = result.stdout.lines.first?.words.last {
let result = >["defaults", "delete", "com.apple.dt.Xcode", "DVTPlugInManagerNonApplePlugIns-Xcode-\(version)"]
if result.result != 0 {
print(result.stderr)
}
} else {
print(result.stderr)
exit(1)
}
}
$0.command("uninstall", description: "Uninstall a plugin") { (name: String) in
waitForPackages { packages in
let packages = packages.filter { $0.isInstalled && $0.name == name }
packages.forEach { $0.removeAndReport() }
}
}
$0.command("update", description: "Update all installed plugins") {
waitForPackages { packages in
let packages = packages.filter { $0.isInstalled }
packages.forEach { $0.updateAndReport() }
}
}
}.run("0.4.0")
| mit | 0a6c71360be772f10a0a2dd1e6425933 | 29.504673 | 116 | 0.627451 | 3.908982 | false | false | false | false |
kkserver/kk-ios-app | KKApp/KKApp/KKApplication.swift | 1 | 9665 | //
// KKApplication.swift
// KKApp
//
// Created by zhanghailong on 2016/11/26.
// Copyright © 2016年 kkserver.cn. All rights reserved.
//
import UIKit
import KKObserver
public extension Bundle {
public func path(uri:String)->String {
if uri.hasPrefix("document://") {
return NSHomeDirectory().appending(uri.substring(from: uri.index(uri.startIndex, offsetBy: 11)))
}
else if uri.hasPrefix("app://") {
return Bundle.main.resourcePath!.appending(uri.substring(from: uri.index(uri.startIndex, offsetBy: 6)))
}
else if uri.hasPrefix("cache://") {
return NSHomeDirectory().appendingFormat("/Library/Caches%@", uri.substring(from: uri.index(uri.startIndex, offsetBy: 8)))
}
else if uri.hasPrefix("/") {
return uri
}
else {
return bundlePath.appendingFormat("/%@", uri)
}
}
}
public class KKApplication: KKObserver,XMLParserDelegate {
private weak var _parent:KKApplication?
private var _firstChild:KKApplication?
private var _lastChild:KKApplication?
private var _nextSibling:KKApplication?
private weak var _prevSibling:KKApplication?
private let _bundle:Bundle
deinit {
print("[KK]","[App]", name!, "dealloc")
}
public var root:KKApplication {
get {
if _parent != nil {
return _parent!.root
}
return self
}
}
public override var parent:KKObserver? {
get {
return _parent;
}
}
public var firstChild:KKApplication? {
get {
return _firstChild;
}
}
public var lastChild:KKApplication? {
get {
return _lastChild;
}
}
public var nextSibling:KKApplication? {
get {
return _nextSibling;
}
}
public var prevSibling:KKApplication? {
get {
return _prevSibling;
}
}
public var bundle:Bundle {
get {
return _bundle;
}
}
public required init(bundle:Bundle) {
_bundle = bundle
super.init();
}
public required init(bundle:Bundle,name:String) {
_bundle = bundle
super.init();
let url = bundle.url(forResource: name, withExtension: "xml");
if(url != nil) {
set(["app","url"],url)
let parser = XMLParser.init(contentsOf: url!)
if(parser != nil) {
parser!.delegate = self
parser!.parse()
}
}
}
public func append(_ element:KKApplication) -> Void {
let e = element
e.remove()
if _lastChild != nil {
_lastChild!._nextSibling = e
e._prevSibling = _lastChild
_lastChild = e
} else {
_firstChild = e
_lastChild = e
}
e._parent = self
onAddChildren(element)
}
public func appendTo(_ element:KKApplication) -> Void {
element.append(self)
}
public func remove() -> Void {
let p = _parent
let e = self
if _prevSibling != nil {
_prevSibling!._nextSibling = _nextSibling
if _nextSibling != nil {
_nextSibling!._prevSibling = _prevSibling
} else if _parent != nil {
_parent!._lastChild = _prevSibling
}
} else if _parent != nil {
_parent!._firstChild = _nextSibling
if _nextSibling != nil {
_nextSibling!._prevSibling = nil
} else {
_parent!._lastChild = _nextSibling
}
}
_parent = nil
_nextSibling = nil
_prevSibling = nil
if p != nil {
p?.onRemoveChildren(e)
}
}
public func removeAllChildren() -> Void {
var p = _firstChild
while p != nil {
let n = p!.nextSibling
p!.remove()
p = n
}
}
public func before(_ element:KKApplication) -> Void {
let e = element
e.remove()
if _parent != nil {
e._parent = _parent
if _prevSibling != nil {
_prevSibling!._nextSibling = e
e._prevSibling = _prevSibling
e._nextSibling = self
_prevSibling = e
} else {
_parent?._firstChild = e
e._nextSibling = self
_prevSibling = e
}
_parent!.onAddChildren(e)
}
}
public func beforeTo(_ element:KKApplication) -> Void {
element.before(self)
}
public func after(_ element:KKApplication) -> Void {
let e = element
e.remove()
if _parent != nil {
e._parent = _parent
if _nextSibling != nil {
e._nextSibling = _nextSibling
e._prevSibling = self
_nextSibling!._prevSibling = e
_nextSibling = e
} else {
_parent?._lastChild = e
e._prevSibling = self
_nextSibling = e
}
_parent!.onAddChildren(e)
}
}
public func afterTo(_ element:KKApplication) -> Void {
element.after(self)
}
public func onRemoveChildren(_ element:KKApplication) -> Void {
element.onRemoveFromParent(self)
}
public func onAddChildren(_ element:KKApplication) -> Void {
element.onAddToParent(self)
}
public func onAddToParent(_ element:KKApplication) -> Void {
}
public func onRemoveFromParent(_ element:KKApplication) -> Void {
}
public var name:String? {
get {
return KKObject.stringValue(get(["app","name"]), nil);
}
}
public var title:String? {
get {
return KKObject.stringValue(get(["app","title"]), nil);
}
}
public var url:URL? {
get {
return get(["app","url"]) as! URL?
}
}
public func clone() -> KKApplication {
let app = type(of: self).init(bundle: bundle)
app.set(["app"], get(["app"]))
var p = firstChild
while(p != nil) {
app.append(p!.clone())
p = p!.nextSibling
}
return app
}
private var _element:KKApplication?
internal func onStartDocument() ->Void {
}
internal func onEndDocument() ->Void {
}
public func parserDidStartDocument(_ parser: XMLParser) {
_element = nil
onStartDocument()
}
public func parserDidEndDocument(_ parser: XMLParser) {
_element = nil
onEndDocument()
}
public func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
let path = attributeDict["path"];
var e:KKApplication?
if(_element == nil) {
_element = self
e = _element
}
else {
e = KKApplication.init(bundle: path == nil ? _element!.bundle : Bundle.init(path: _element!.bundle.bundlePath+"/"+path!)!)
e!.appendTo(_element!)
}
for (key,value) in attributeDict {
e!.set(["app",key],value)
}
e!.set(["app","name"],elementName)
print("[KK]",e!.value ?? "")
_element = e
}
public func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
_element = _element!.parent as! KKApplication?
}
public func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
NSLog("[KK][KKApplication] %@", parseError.localizedDescription)
print(parseError)
}
public func parser(_ parser: XMLParser, validationErrorOccurred validationError: Error) {
NSLog("[KK][KKApplication] %@", validationError.localizedDescription)
print(validationError)
}
public func obtain() -> KKApplication {
let v = self.clone()
v.afterTo(self)
return v
}
public func open(_ name:String) -> KKApplication? {
var p = firstChild
while p != nil {
if p!.name == name {
return p!.obtain()
}
p = p!.nextSibling
}
return nil
}
public func recycle() -> Void {
if !booleanValue(["recycle"],false) {
set(["recycle"],true)
print("[KK]","[App]", name!, "recycle")
remove()
}
}
private static var _main:KKApplication?
public static var main:KKApplication {
get {
if(_main == nil) {
_main = KKApplication.init(bundle: Bundle.main, name: "app")
}
return _main!
}
}
}
| mit | 03223bdf4ccfc7f03e25c0dc334b85b7 | 23.522843 | 186 | 0.484268 | 4.972723 | false | false | false | false |
Alterplay/APKenBurnsView | Pod/Classes/Private/AnimationHelpers/UIImageView+ImageAnimation.swift | 1 | 1372 | //
// Created by Nickolay Sheika on 6/11/16.
//
import Foundation
import UIKit
import CoreFoundation
extension UIImageView {
// MARK: - Public
func animateWithImageAnimation(animation: ImageAnimation, completion: (() -> ())? = nil) {
let imageStartTransform = transformForImageState(imageState: animation.startState)
let imageEndTransform = transformForImageState(imageState: animation.endState)
UIView.animateKeyframes(withDuration: animation.duration, delay: 0.0, options: .calculationModeCubic, animations: {
UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 0.0) {
self.transform = imageStartTransform
}
UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 1.0) {
self.transform = imageEndTransform
}
}, completion: {
finished in
completion?()
})
}
// MARK: - Helpers
private func transformForImageState(imageState: ImageState) -> CGAffineTransform {
let scaleTransform = CGAffineTransform(scaleX: imageState.scale, y: imageState.scale)
let translationTransform = CGAffineTransform(translationX: imageState.position.x, y: imageState.position.y)
let transform = scaleTransform.concatenating(translationTransform)
return transform
}
}
| mit | 1363682bbf8545aef53024ad85fdd6e5 | 34.179487 | 123 | 0.680758 | 4.989091 | false | false | false | false |
michaelarmstrong/SuperRecord | SuperRecordDemo/SuperRecordDemo/UIMenuTableViewController.swift | 2 | 2665 | //
// UIMenuTableViewController.swift
// SuperRecordDemo
//
// Created by Piergiuseppe Longo on 26/10/15.
// Copyright © 2015 SuperRecord. All rights reserved.
//
import UIKit
class UIMenuTableViewController: UITableViewController {
let menuVoices = [
"Find All",
"Find all pokemon sort by Name",
"Find all pokemon with name containing 'charm'",
"Find all pokemon of type 'Water'",
"CollectionView all pokemon",
]
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return menuVoices.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("PokemonCell")
if (nil == cell){
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "PokemonCell")
}
cell?.textLabel?.text = menuVoices[indexPath.row]
cell?.textLabel?.numberOfLines = 0
return cell!
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var viewController: UIViewController!
switch (indexPath.row){
case 0:
viewController = PokedexTableViewController()
break
case 1:
let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
viewController = PokedexTableViewController(sortDescriptors: [sortDescriptor])
break
case 2:
let predicate = NSPredicate.predicateBuilder("name", value: "Charm", predicateOperator: .Contains)!
viewController = PokedexTableViewController(predicate: predicate)
break
case 3:
let fireType = Type.findFirstOrCreateWithAttribute("name", value: "Water")
let predicate = NSPredicate.predicateBuilder("types", value: fireType, predicateOperator: .Contains)!
viewController = PokedexTableViewController(predicate: predicate)
break
case 4:
viewController = PokemonCollectionViewController()
break
default:
print("Not implemented method");
abort()
}
self.navigationController?.pushViewController(viewController, animated: true)
}
}
| mit | 9c2c1d600862f675abe4274ce425044c | 31.888889 | 118 | 0.638138 | 5.608421 | false | false | false | false |
nagyistoce/SwiftHN | SwiftHN/Utils/Preferences.swift | 1 | 1299 | //
// Preferences.swift
// SwiftHN
//
// Created by Thomas Ricouard on 25/06/14.
// Copyright (c) 2014 Thomas Ricouard. All rights reserved.
//
import Foundation
import UIKit
import HackerSwifter
let _preferencesSharedInstance = Preferences()
class Preferences {
let pUserDefault = NSUserDefaults.standardUserDefaults()
let pFirstTimeLaunchString = "isFirstTimeLaunch"
let pReadLater = "readLater"
var firstTimeLaunch: Bool {
get {
return self.pUserDefault.boolForKey(pFirstTimeLaunchString)
}
set {
self.pUserDefault.setBool(newValue, forKey: pFirstTimeLaunchString)
}
}
func addToReadLater(post: Post) {
var array: [AnyObject]! = self.pUserDefault.arrayForKey(pReadLater)
if (array == nil) {
array = []
}
array.append(post.postId!)
self.pUserDefault.setObject(array, forKey: pReadLater)
}
func isInReadingList(uid: String) -> Bool {
var array: [AnyObject]! = self.pUserDefault.arrayForKey(pReadLater)
if (array == nil) {
return false
}
return contains(array as [String], uid)
}
class var sharedInstance: Preferences {
return _preferencesSharedInstance
}
}
| gpl-2.0 | 56609a25e07104c501e8ae9c521cd2e1 | 24.470588 | 79 | 0.628945 | 4.388514 | false | false | false | false |
ziyincody/MTablesView | Example/MTablesView/Extensions.swift | 1 | 1866 | //
// extensions.swift
// Pods
//
// Created by Ziyin Wang on 2017-02-18.
//
//
import UIKit
extension UIView {
@available(iOS 9.0, *)
func anchor(_ top:NSLayoutYAxisAnchor? = nil, left:NSLayoutXAxisAnchor? = nil, bottom:NSLayoutYAxisAnchor? = nil, right:NSLayoutXAxisAnchor? = nil, centerX:NSLayoutXAxisAnchor? = nil, centerY:NSLayoutYAxisAnchor? = nil, topConstant:CGFloat = 0, leftConstant:CGFloat = 0, bottomConstant:CGFloat = 0, rightConstant:CGFloat = 0, widthConstant:CGFloat = 0, heightConstant:CGFloat = 0) -> [NSLayoutConstraint] {
translatesAutoresizingMaskIntoConstraints = false
var anchors = [NSLayoutConstraint]()
if let top = top {
anchors.append(topAnchor.constraint(equalTo: top,constant: topConstant))
}
if let bottom = bottom {
anchors.append(bottomAnchor.constraint(equalTo: bottom,constant: bottomConstant))
}
if let left = left {
anchors.append(leftAnchor.constraint(equalTo: left,constant: leftConstant))
}
if let right = right {
anchors.append(rightAnchor.constraint(equalTo: right,constant: -rightConstant))
}
if let centerX = centerX
{
anchors.append(centerXAnchor.constraint(equalTo: centerX))
}
if let centerY = centerY
{
anchors.append(centerYAnchor.constraint(equalTo: centerY))
}
if widthConstant > 0 {
anchors.append(widthAnchor.constraint(equalToConstant: widthConstant))
}
if heightConstant > 0 {
anchors.append(heightAnchor.constraint(equalToConstant: heightConstant))
}
anchors.forEach({$0.isActive = true})
return anchors
}
}
| mit | c4deaef2c41171941f854da7c5fa57fe | 31.172414 | 410 | 0.607181 | 5.154696 | false | false | false | false |
Swinject/SwinjectAutoregistration | Sources/ResolutionError.swift | 1 | 1692 | //
// Warnings.swift
// SwinjectAutoregistration
//
// Created by Tomas Kohout on 18/01/2017.
// Copyright © 2017 Swinject Contributors. All rights reserved.
//
import Foundation
enum ResolutionError {
case tooManyDependencies(Int)
var message: String {
switch self {
case .tooManyDependencies(let dependencyCount):
return "⚠ Autoregistration is limited to maximum of \(maxDependencies) dependencies, tried to resolve \(dependencyCount). Use regular `register` method instead. "
}
}
}
/// Shows warnings based on information parsed from initializers description
func resolutionErrors<Service, Parameters>(forInitializer initializer: (Parameters) -> Service) -> [ResolutionError] {
#if os(Linux) || os(Android)
//Warnings are not supported on Linux
return []
#else
let parser = TypeParser(string: String(describing: Parameters.self))
guard let type = parser.parseType() else { return [] }
let dependencies: [Type]
//Multiple arguments
if case .tuple(let types) = type {
dependencies = types
//Single argument
} else if case .identifier(_) = type {
dependencies = [type]
} else {
return []
}
var warnings: [ResolutionError] = []
if dependencies.count > maxDependencies {
warnings.append(.tooManyDependencies(dependencies.count))
}
return warnings
#endif
}
func hasUnique(arguments: [Any.Type]) -> Bool {
for (index, arg) in arguments.enumerated() {
if (arguments.enumerated().filter { index != $0 && arg == $1 }).count > 0 {
return false
}
}
return true
}
| mit | 80000eeb4db972f23f82b3e9e443774d | 27.15 | 174 | 0.639432 | 4.387013 | false | false | false | false |
xiaomudegithub/viossvc | viossvc/General/Helper/ChatMsgHepler.swift | 1 | 3387 | //
// ChatManageHepler.swift
// viossvc
//
// Created by yaowang on 2016/12/3.
// Copyright © 2016年 com.yundian. All rights reserved.
//
import UIKit
import XCGLogger
class ChatMsgHepler: NSObject {
static let shared = ChatMsgHepler()
var chatSessionHelper:ChatSessionHelper?
override init() {
super.init()
AppAPIHelper.chatAPI().setReceiveMsgBlock { [weak self] (msg) in
let chatModel = msg as? ChatMsgModel
if chatModel != nil {
AppAPIHelper.userAPI().getUserInfo(chatModel!.from_uid, complete: { [weak self] (userInfo) in
if let user = userInfo as? UserInfoModel {
if UIApplication.sharedApplication().applicationState == .Background {
let localNotify = UILocalNotification()
localNotify.fireDate = NSDate().dateByAddingTimeInterval(0.1)
localNotify.timeZone = NSTimeZone.defaultTimeZone()
localNotify.applicationIconBadgeNumber += 1
localNotify.soundName = UILocalNotificationDefaultSoundName
if #available(iOS 8.2, *) {
localNotify.alertTitle = "优悦助理"
} else {
// Fallback on earlier versions
}
localNotify.alertBody = user.nickname! + " : " + chatModel!.content
UIApplication.sharedApplication().scheduleLocalNotification(localNotify)
}
}
}, error: nil)
self?.didChatMsg(chatModel!)
}
}
}
func sendMsg(toUid:Int,msg:String, type:Int = 0 ) {
let chatModel = ChatMsgModel()
chatModel.content = msg
chatModel.msg_type = type
chatModel.from_uid = CurrentUserHelper.shared.uid
chatModel.to_uid = toUid
chatModel.msg_time = Int(NSDate().timeIntervalSince1970)
AppAPIHelper.chatAPI().sendMsg(chatModel, complete: { (obj) in
}, error: { (error) in
XCGLogger.debug("\(error)")
})
didChatMsg(chatModel)
}
func offlineMsgs() {
AppAPIHelper.chatAPI().offlineMsgList(CurrentUserHelper.shared.uid, complete: { [weak self] (chatModels) in
self?.didOfflineMsgsComplete(chatModels as? [ChatMsgModel])
}, error: { (error) in
XCGLogger.debug("\(error)")
})
}
func didOfflineMsgsComplete(chatModels:[ChatMsgModel]!) {
//!!!: 离线消息多时要优化
for chatModel in chatModels {
didChatMsg(chatModel)
}
}
func findHistoryMsg(uid:Int,offset:Int,pageSize:Int) -> [ChatMsgModel] {
return ChatDataBaseHelper.ChatMsg.findHistoryMsg(uid, offset: offset, pageSize:pageSize)
}
func didChatMsg(chatMsgModel:ChatMsgModel) {
XCGLogger.debug("\(chatMsgModel)")
ChatDataBaseHelper.ChatMsg.addModel(chatMsgModel)
chatSessionHelper?.receiveMsg(chatMsgModel)
// if chatMsgModel.from_uid != CurrentUserHelper.shared.uid {
// sendMsg(chatMsgModel.from_uid, msg: chatMsgModel.content)
// }
}
}
| apache-2.0 | a7617947f225761a4495e4c872514123 | 36.730337 | 115 | 0.561346 | 4.797143 | false | false | false | false |
laurentVeliscek/AudioKit | Examples/iOS/SongProcessor/SongProcessor/View Controllers/iTunes Library Access/SongsViewController.swift | 2 | 3132 | //
// SongsViewController.swift
// SongProcessor
//
// Created by Aurelius Prochazka on 6/22/16.
// Copyright © 2016 AudioKit. All rights reserved.
//
import UIKit
import AVFoundation
import MediaPlayer
class SongsViewController: UITableViewController {
var albumName: String!
var artistName: String!
var songsList = []
override func viewDidLoad() {
super.viewDidLoad()
let albumPredicate = MPMediaPropertyPredicate(value: albumName,
forProperty: MPMediaItemPropertyAlbumTitle,
comparisonType: .Contains)
let artistPredicate = MPMediaPropertyPredicate(value: artistName,
forProperty: MPMediaItemPropertyArtist,
comparisonType: .Contains)
let songsQuery = MPMediaQuery.songsQuery()
songsQuery.addFilterPredicate(albumPredicate)
songsQuery.addFilterPredicate(artistPredicate)
songsQuery.addFilterPredicate(MPMediaPropertyPredicate(
value: NSNumber(bool: false),
forProperty: MPMediaItemPropertyIsCloudItem))
if songsQuery.items != nil {
songsList = songsQuery.items!
tableView.reloadData()
}
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return songsList.count
}
override func tableView(tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "SongCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) ?? UITableViewCell(style: .Default, reuseIdentifier: cellIdentifier)
let song: MPMediaItem = songsList[indexPath.row] as! MPMediaItem
let songTitle = song.valueForProperty(MPMediaItemPropertyTitle) as! String
let minutes = song.valueForProperty(MPMediaItemPropertyPlaybackDuration)!.floatValue / 60
let seconds = song.valueForProperty(MPMediaItemPropertyPlaybackDuration)!.floatValue % 60
cell.textLabel?.text = songTitle
cell.detailTextLabel?.text = String(format: "%d:%02d", minutes, seconds)
return cell
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "SongSegue" {
if let indexPath = tableView.indexPathForSelectedRow {
let songVC = segue.destinationViewController as! SongViewController
songVC.song = songsList[indexPath.row] as? MPMediaItem
songVC.title = songVC.song!.valueForProperty(MPMediaItemPropertyTitle) as? String
}
}
}
} | mit | 8501033557de5d0a3f810ac03bafbad2 | 36.285714 | 147 | 0.615139 | 5.986616 | false | false | false | false |
wireapp/wire-ios | Scripts/updateLicenses/main.swift | 1 | 6987 | //
// Wire
// Copyright (C) 2020 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/.
//
// --------------------------------------------------------------------
// This script updates the Wire-iOS/Resources/Licenses file with the
// latest licenses and dependencies from Carthage.
//
// In Xcode, add this script as a build phase, before the "Copy Bundle
// Resources" phase in the main target.
//
// The first input file must be the Cartfile.resolved file. The second
// input file must be the Cartfile/Checkouts directory. The third input
// file must be the EmbeddedDependencies file. The output filecmust be the
// plist file that will contain the licenses.
//
// This script will be run everytime we clean the project, and when the
// build enviroment changes (when we update Carthage or add/remove
// dependencies).
//
import Foundation
// MARK: - Models
/// The structure representing license items to add in the Plist.
struct Dependency: Codable {
/// The name of the project.
let name: String
/// The text of the license file.
let licenseText: String
/// The URL of the project.
let projectURL: URL
enum CodingKeys: String, CodingKey {
case name = "Name"
case licenseText = "LicenseText"
case projectURL = "ProjectURL"
}
}
/// The different file names for the license files.
let licenseSpellings = [
"LICENSE",
"License",
"LICENSE.txt",
"License.txt",
"LICENSE.md",
"License.md"
]
// MARK: - Helpers
/// Exits the script because of an error.
func fail(_ error: String) -> Never {
print("💥 \(error)")
exit(-1)
}
/// Prints an info message.
func info(_ message: String) {
print("ℹ️ \(message)")
}
/// Prints a success message and exits the script.
func success(_ message: String) -> Never {
print("✅ \(message)")
exit(0)
}
extension String {
/// Removes the license columns in the string.
var removingColumns: String {
let paragraphs = self.components(separatedBy: "\n\n")
var singleLines: [String] = []
for paragraph in paragraphs {
let lines = paragraph.components(separatedBy: "\n")
let sanitizedLines = lines.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
let singleLine = sanitizedLines.joined(separator: " ")
singleLines.append(singleLine)
}
return singleLines.joined(separator: "\n\n")
}
}
/// Gets the license text in the given directory.
func getLicenseURL(in directory: URL) -> URL? {
guard let topLevelItems = try? FileManager.default.contentsOfDirectory(atPath: directory.path) else {
return nil
}
for spelling in licenseSpellings {
if topLevelItems.contains(spelling) {
let possibleURL = directory.appendingPathComponent(spelling)
guard FileManager.default.fileExists(atPath: possibleURL.path) else {
continue
}
return possibleURL
}
}
return nil
}
// MARK: - Parsing
/// Get the list of depedencies from the Cartfile.resolved file.
func generateFromCartfileResolved(_ content: String, checkoutsDir: URL) -> [Dependency] {
let dependencyLines = content.split(separator: "\n").filter { $0.hasPrefix("github") }
var items: [Dependency] = []
for dependency in dependencyLines {
// 1) Parse the component info from the Carthage file (ex: github "wireapp/dependency" "version")
let components = dependency.components(separatedBy: " ")
guard components.count == 3 else {
info("Skipping invalid dependency.")
continue
}
let projectPath = components[1].trimmingCharacters(in: .punctuationCharacters)
let url = URL(string: "https://github.com/\(projectPath)")!
let projectComponents = projectPath.components(separatedBy: "/")
guard projectComponents.count == 2 else {
info("Skipping invalid dependency.")
continue
}
let name = projectComponents[1].trimmingCharacters(in: .symbols)
// Do not include Wire frameworks
guard !name.hasPrefix("wire-ios-"), !name.hasPrefix("avs-ios-") else {
info("Skipping Wire component.")
continue
}
// 2) Get the license text from the checkout out directory
let projectCheckoutFolder = checkoutsDir.appendingPathComponent(name, isDirectory: true)
guard let licenseTextURL = getLicenseURL(in: projectCheckoutFolder) else {
info("The dependency \(name) does not have a license. Skipping.")
continue
}
guard let data = try? Data(contentsOf: licenseTextURL) else {
info("Could not read the license of \(name). Skipping.")
break
}
let licenseText = String(decoding: data, as: UTF8.self).removingColumns
//3) Create the item
let item = Dependency(name: name, licenseText: licenseText, projectURL: url)
items.append(item)
}
return items
}
// MARK: - Execution
let (cartfileURL, checkoutsURL, embeddedDependencies) = (URL(fileURLWithPath: "Cartfile.resolved"),
URL(fileURLWithPath: "Carthage/Checkouts"),
URL(fileURLWithPath: "EmbeddedDependencies.plist"))
let outputURL = URL(fileURLWithPath:"Wire-iOS/Resources/Licenses.generated.plist")
// 1) Decode the Cartfile
let cartfileBinary = try Data(contentsOf: cartfileURL)
let cartfileContents = String(decoding: cartfileBinary, as: UTF8.self)
let dependenciesBinary = try Data(contentsOf: embeddedDependencies)
let existingDependencies = try PropertyListDecoder().decode([Dependency].self, from: dependenciesBinary)
let dynamicItems = generateFromCartfileResolved(cartfileContents, checkoutsDir: checkoutsURL)
let items = (existingDependencies + dynamicItems).sorted {
$0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending
}
info("Encoding \(items.count) dependencies.")
let encoder = PropertyListEncoder()
encoder.outputFormat = .binary
// 2) Encode and write the data
let encodedPlist = try encoder.encode(items)
try? FileManager.default.removeItem(at: outputURL)
try encodedPlist.write(to: outputURL)
success("Successfully updated the list of licenses")
| gpl-3.0 | 97f9d35f1fd012bdd93843d79ce085c1 | 31.156682 | 108 | 0.663801 | 4.478819 | false | false | false | false |
toggl/superday | teferi/UI/Modules/Timeline/Views/ExpandedTimelineCell.swift | 1 | 1613 | import UIKit
class ExpandedTimelineCell: UITableViewCell
{
static let cellIdentifier = "ExpandedTimelineCell"
private(set) var item: SlotTimelineItem? = nil
@IBOutlet private weak var lineView : LineView!
@IBOutlet private weak var slotTime : UILabel!
@IBOutlet private weak var elapsedTime : UILabel!
@IBOutlet private weak var lineHeight: NSLayoutConstraint!
@IBOutlet private weak var activityTagView: ActivityTagView!
@IBOutlet private weak var separatorView : UIView!
func configure(item: SlotTimelineItem, visibleSeparator: Bool)
{
self.item = item
slotTime.text = item.startTime.formatedShortStyle
layoutLine(withItem: item)
elapsedTime.textColor = item.category.color
elapsedTime.text = formatedElapsedTimeText(for: item.duration)
setupActivityTag(withTagText: item.activityTagText)
separatorView.isHidden = !visibleSeparator
}
private func layoutLine(withItem item: SlotTimelineItem)
{
lineHeight.constant = calculatedLineHeight(for: item.duration)
lineView.color = item.category.color
lineView.collapsed = false
lineView.fading = false
lineView.layoutIfNeeded()
}
private func setupActivityTag(withTagText tagText: String?)
{
guard let tagText = tagText else {
activityTagView.isHidden = true
return
}
activityTagView.isHidden = false
activityTagView.configure(name: tagText)
}
}
| bsd-3-clause | b7508d447487f53137a54921c31b81d6 | 28.87037 | 70 | 0.656541 | 5.237013 | false | false | false | false |
ashfurrow/Moya | Sources/ReactiveMoya/MoyaProvider+Reactive.swift | 1 | 2321 | import Foundation
import ReactiveSwift
#if !COCOAPODS
import Moya
#endif
extension MoyaProvider: ReactiveExtensionsProvider {}
public extension Reactive where Base: MoyaProviderType {
/// Designated request-making method.
func request(_ token: Base.Target, callbackQueue: DispatchQueue? = nil) -> SignalProducer<Response, MoyaError> {
return SignalProducer { [weak base] observer, lifetime in
let cancellableToken = base?.request(token, callbackQueue: callbackQueue, progress: nil) { result in
switch result {
case let .success(response):
observer.send(value: response)
observer.sendCompleted()
case let .failure(error):
observer.send(error: error)
}
}
lifetime.observeEnded {
cancellableToken?.cancel()
}
}
}
/// Designated request-making method with progress.
func requestWithProgress(_ token: Base.Target, callbackQueue: DispatchQueue? = nil) -> SignalProducer<ProgressResponse, MoyaError> {
let progressBlock: (Signal<ProgressResponse, MoyaError>.Observer) -> (ProgressResponse) -> Void = { observer in
return { progress in
observer.send(value: progress)
}
}
let response: SignalProducer<ProgressResponse, MoyaError> = SignalProducer { [weak base] observer, lifetime in
let cancellableToken = base?.request(token, callbackQueue: callbackQueue, progress: progressBlock(observer)) { result in
switch result {
case .success:
observer.sendCompleted()
case let .failure(error):
observer.send(error: error)
}
}
lifetime.observeEnded {
cancellableToken?.cancel()
}
}
// Accumulate all progress and combine them when the result comes
return response.scan(ProgressResponse()) { last, progress in
let progressObject = progress.progressObject ?? last.progressObject
let response = progress.response ?? last.response
return ProgressResponse(progress: progressObject, response: response)
}
}
}
| mit | c5f48e96dc9bb07d4fe338b93950459b | 37.683333 | 136 | 0.605343 | 5.74505 | false | false | false | false |
therealglazou/quaxe-for-swift | quaxe/core/Trees.swift | 1 | 8272 | /**
* Quaxe for Swift
*
* Copyright 2016-2017 Disruptive Innovations
*
* Original author:
* Daniel Glazman <[email protected]>
*
* Contributors:
*
*/
/*
* https://dom.spec.whatwg.org/#trees
*
* status: done
*/
internal class Trees {
static func remove(_ node: Node, _ parent: Node) -> Void {
if (node.previousSibling != nil) {
(node.previousSibling as! Node).mNextSibling = node.nextSibling;
}
if (node.nextSibling != nil) {
(node.nextSibling as! Node).mPreviousSibling = node.previousSibling;
}
if nil != parent.firstChild &&
parent.firstChild as! Node === node {
parent.mFirstChild = node.nextSibling;
}
if nil != parent.lastChild &&
parent.lastChild as! Node === node {
parent.mLastChild = nil;
}
}
static func insertBefore(_ node: Node, _ parent: Node, _ child: Node?) -> Void {
if nil == child {
// append
node.mPreviousSibling = parent.mLastChild
node.mNextSibling = nil
node.mParentNode = parent
parent.mLastChild = node
if nil == parent.firstChild {
parent.mFirstChild = node
}
}
else {
node.mParentNode = parent
node.mNextSibling = child
node.mPreviousSibling = child!.previousSibling
if nil != child!.previousSibling {
(child!.mPreviousSibling as! Node).mNextSibling = node
}
else {
parent.mFirstChild = node
}
child!.mPreviousSibling = node
}
}
static func append(_ node: Node, _ parent: Node) -> Void {
insertBefore(node, parent, nil)
}
static func getRootOf(_ n: Node) -> Node {
var node = n
while nil != node.parentNode {
node = node.parentNode as! Node
}
return node
}
static func isDescendantOf(_ n: Node, _ candidate: Node) -> Bool {
var node = n
while nil != node.parentNode {
if node.parentNode as! Node === candidate {
return true
}
node = node.parentNode as! Node
}
return false
}
static func isInclusiveDescendantOf(_ node: Node, _ candidate: Node) -> Bool {
return node === candidate ||
Trees.isDescendantOf(node, candidate)
}
static func isAncestorOf(_ node: Node, _ candidate: Node) -> Bool {
return Trees.isDescendantOf(candidate, node)
}
static func isInclusiveAncestorOf(_ node: Node, _ candidate: Node) -> Bool {
return Trees.isInclusiveDescendantOf(candidate, node)
}
static func isSiblingOf(_ node: Node, _ candidate: Node) -> Bool {
return nil != node.parentNode &&
nil != candidate.parentNode &&
node.parentNode as! Node === candidate.parentNode as! Node
}
static func isInclusiveSiblingOf(_ node: Node, _ candidate: Node) -> Bool {
return node === candidate ||
Trees.isSiblingOf(node, candidate)
}
static func isPreceding(_ node: Node, _ candidate: Node) -> Bool {
return Trees.getRootOf(node) === Trees.getRootOf(candidate) &&
node.compareDocumentPosition(candidate) == Node.DOCUMENT_POSITION_PRECEDING
}
static func isFollowing(_ node: Node, _ candidate: Node) -> Bool {
return Trees.getRootOf(node) === Trees.getRootOf(candidate) &&
node.compareDocumentPosition(candidate) == Node.DOCUMENT_POSITION_FOLLOWING
}
static func indexOf(_ node: Node) -> ulong {
var rv: ulong = 0
var child: pNode? = node
while nil != child && nil != child!.previousSibling {
rv += 1
child = child!.previousSibling
}
return rv
}
static func _listElementsWithQualifiedName(_ root: pNode?, _ qualifiedName: DOMString, _ ea: Array<Element>) -> Void {
var elementArray = ea
var child = root
while nil != child {
if Node.ELEMENT_NODE == child!.nodeType {
if "*" == qualifiedName {
elementArray.append(child as! Element)
}
else if nil != child!.ownerDocument &&
"html" == child!.ownerDocument!.type {
if (child as! Element).namespaceURI == Namespaces.HTML_NAMESPACE &&
(child as! Element).qualifiedName.lowercased() == qualifiedName.lowercased() {
elementArray.append(child as! Element)
}
if (child as! Element).namespaceURI != Namespaces.HTML_NAMESPACE &&
(child as! Element).qualifiedName == qualifiedName {
elementArray.append(child as! Element)
}
}
else if (child as! Element).qualifiedName == qualifiedName {
elementArray.append(child as! Element)
}
}
if nil != child!.firstChild {
Trees._listElementsWithQualifiedName(child!.firstChild, qualifiedName, elementArray)
}
child = child!.nextSibling
}
}
static func listElementsWithQualifiedName(_ root: Node, _ qualifiedName: DOMString) -> HTMLCollection {
let elementArray: Array<Element> = []
Trees._listElementsWithQualifiedName(root.firstChild, qualifiedName, elementArray)
return HTMLCollection(elementArray)
}
static func _listElementsWithQualifiedNameAndNamespace(_ root: pNode?, _ namespace: DOMString?, _ localName: DOMString, _ ea: Array<Element>) -> Void {
var elementArray = ea
var child = root
while nil != child {
if Node.ELEMENT_NODE == child!.nodeType {
if "*" == namespace && "*" == localName {
elementArray.append(child as! Element)
}
else if "*" == namespace {
if (child as! Element).localName == localName {
elementArray.append(child as! Element)
}
}
else if "*" == localName {
if (child as! Element).namespaceURI == namespace {
elementArray.append(child as! Element)
}
}
else {
if (child as! Element).localName == localName &&
(child as! Element).namespaceURI == namespace {
elementArray.append(child as! Element)
}
}
}
if nil != child!.firstChild {
Trees._listElementsWithQualifiedNameAndNamespace(child!.firstChild, namespace, localName, elementArray)
}
child = child!.nextSibling
}
}
static func listElementsWithQualifiedNameAndNamespace(_ root: Node, _ ns: DOMString?, _ localName: DOMString) -> HTMLCollection {
var namespace = ns
let elementArray: Array<Element> = []
if "" == namespace {
namespace = nil
}
Trees._listElementsWithQualifiedNameAndNamespace(root.firstChild, namespace, localName, elementArray)
return HTMLCollection(elementArray)
}
static func _listElementsWithClassNames(_ root: pNode?, _ classes: Set<String>, _ ea: Array<Element>) -> Void {
var elementArray = ea
var child = root
while nil != child {
if Node.ELEMENT_NODE == child!.nodeType {
let elementClasses = OrderedSets.parse((child as! Element).className)
if elementClasses.isSubset(of: classes) {
elementArray.append(child as! Element)
}
}
if nil != child!.firstChild {
Trees._listElementsWithClassNames(child!.firstChild, classes, elementArray)
}
child = child!.nextSibling
}
}
static func listElementsWithClassNames(_ root: Node, _ classNames: DOMString) -> HTMLCollection {
let classes = OrderedSets.parse(classNames)
if classes.isEmpty {
return HTMLCollection()
}
let elementArray: Array<Element> = []
Trees._listElementsWithClassNames(root.firstChild, classes, elementArray)
return HTMLCollection(elementArray)
}
static func length(_ node: Node) -> ulong {
switch node.nodeType {
case Node.DOCUMENT_TYPE_NODE: return 0
case Node.TEXT_NODE,
Node.COMMENT_NODE,
Node.PROCESSING_INSTRUCTION_NODE: return (node as! CharacterData).length
default: return node.childNodes.length
}
}
static func nextInTraverseOrder(_ node: Node) -> pNode? {
if nil != node.firstChild {
return node.firstChild
}
if nil != node.nextSibling {
return node.nextSibling
}
var parent = node.parentNode
while nil != parent && nil == parent!.nextSibling {
parent = parent!.parentNode
}
if nil != parent {
return parent!.nextSibling
}
return nil
}
}
| mpl-2.0 | 64989a183640ac974a592d14de7994fd | 29.865672 | 153 | 0.625242 | 4.233367 | false | false | false | false |
Rendel27/RDExtensionsSwift | RDExtensionsSwift/RDExtensionsSwift/Source/CGRect/CGRect+Layout.swift | 1 | 2908 | //
// CGRect+Layout.swift
//
// Created by Giorgi Iashvili on 19.09.16.
// Copyright (c) 2016 Giorgi Iashvili
//
// 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.
//
public extension CGRect {
/// RDExtensionsSwift: Get or Set frame origin x
var x : CGFloat { get { return self.origin.x } set { self.origin.x = newValue } }
/// RDExtensionsSwift: Get or Set frame origin y
var y : CGFloat { get { return self.origin.y } set { self.origin.y = newValue } }
/// RDExtensionsSwift: Get or Set frame width
var width : CGFloat { get { return self.size.width } set { self.size = CGSize(width: newValue, height: self.size.height) } }
/// RDExtensionsSwift: Get or Set frame height
var height : CGFloat { get { return self.size.height } set { self.size = CGSize(width: self.size.width, height: newValue) } }
/// RDExtensionsSwift: Get or Set frame center x
var centerX : CGFloat { get { return self.x + self.width/2 } set { self.x = newValue - self.width/2 } }
/// RDExtensionsSwift: Get or Set frame center y
var centerY : CGFloat { get { return self.y + self.height/2 } set { self.y = newValue - self.height/2 } }
/// RDExtensionsSwift: Get or Set frame last x
var lastX : CGFloat { get { return self.x + self.width } set { self.x = newValue - self.width } }
/// RDExtensionsSwift: Get or Set frame last y
var lastY : CGFloat { get { return self.y + self.height } set { self.y = newValue - self.height } }
/// RDExtensionsSwift: Get or Set frame center point
var center : CGPoint { get { return CGPoint(x: self.centerX, y: self.centerY) } set { self.centerX = newValue.x; self.centerY = newValue.y } }
/// RDExtensionsSwift: Get or Set frame middle point
var middle : CGPoint { get { return CGPoint(x: self.width/2, y: self.height/2) } }
}
| mit | e5d46243145725e06908c81ddc3b9aaa | 49.137931 | 146 | 0.685351 | 4.067133 | false | false | false | false |
almazrafi/Metatron | Sources/ID3v2/FrameStuffs/ID3v2UserTextInformation.swift | 1 | 4705 | //
// ID3v2UserTextInformation.swift
// Metatron
//
// Copyright (c) 2016 Almaz Ibragimov
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public class ID3v2UserTextInformation: ID3v2FrameStuff {
// MARK: Instance Properties
public var textEncoding: ID3v2TextEncoding = ID3v2TextEncoding.utf8
public var description: String = ""
public var fields: [String] = []
// MARK:
public var isEmpty: Bool {
return self.fields.isEmpty
}
// MARK: Initializers
public init() {
}
public required init(fromData data: [UInt8], version: ID3v2Version) {
guard data.count > 2 else {
return
}
guard let textEncoding = ID3v2TextEncoding(rawValue: data[0]) else {
return
}
guard let description = textEncoding.decode([UInt8](data.suffix(from: 1))) else {
return
}
var offset = description.endIndex + 1
guard offset < data.count else {
return
}
var fields: [String] = []
repeat {
guard let field = textEncoding.decode([UInt8](data.suffix(from: offset))) else {
return
}
fields.append(field.text)
offset += field.endIndex
if offset >= data.count {
if field.terminated {
fields.append("")
}
break
}
}
while true
self.textEncoding = textEncoding
self.description = description.text
self.fields = fields
}
// MARK: Instance Methods
public func toData(version: ID3v2Version) -> [UInt8]? {
guard !self.isEmpty else {
return nil
}
let textEncoding: ID3v2TextEncoding
switch version {
case ID3v2Version.v2, ID3v2Version.v3:
if self.textEncoding == ID3v2TextEncoding.latin1 {
textEncoding = ID3v2TextEncoding.latin1
} else {
textEncoding = ID3v2TextEncoding.utf16
}
case ID3v2Version.v4:
textEncoding = self.textEncoding
}
var data = [textEncoding.rawValue]
data.append(contentsOf: textEncoding.encode(self.description, termination: true))
for i in 0..<(self.fields.count - 1) {
data.append(contentsOf: textEncoding.encode(self.fields[i], termination: true))
}
data.append(contentsOf: textEncoding.encode(self.fields.last!, termination: false))
return data
}
public func toData() -> (data: [UInt8], version: ID3v2Version)? {
guard let data = self.toData(version: ID3v2Version.v4) else {
return nil
}
return (data: data, version: ID3v2Version.v4)
}
}
public class ID3v2UserTextInformationFormat: ID3v2FrameStuffSubclassFormat {
// MARK: Type Properties
public static let regular = ID3v2UserTextInformationFormat()
// MARK: Instance Methods
public func createStuffSubclass(fromData data: [UInt8], version: ID3v2Version) -> ID3v2UserTextInformation {
return ID3v2UserTextInformation(fromData: data, version: version)
}
public func createStuffSubclass(fromOther other: ID3v2UserTextInformation) -> ID3v2UserTextInformation {
let stuff = ID3v2UserTextInformation()
stuff.textEncoding = other.textEncoding
stuff.description = other.description
stuff.fields = other.fields
return stuff
}
public func createStuffSubclass() -> ID3v2UserTextInformation {
return ID3v2UserTextInformation()
}
}
| mit | 49510c3a6e66054eb9617b159a0c271c | 27.865031 | 112 | 0.640383 | 4.340406 | false | false | false | false |
RemyDCF/tpg-offline | tpg offline/JSON Models/Stop.swift | 1 | 6701 | //
// Stop.swift
// tpgoffline
//
// Created by Rémy Da Costa Faro on 09/06/2017.
// Copyright © 2018 Rémy Da Costa Faro DA COSTA FARO. All rights reserved.
//
import Foundation
import CoreLocation
import Intents
struct Stop: Codable {
struct Localisations: Codable {
struct Destinations: Codable {
var line: String
var destination: String
var destinationTransportAPI: String
}
var location: CLLocation
var destinations: [Destinations]
public init(location: CLLocation, destinations: [Destinations]) {
self.location = location
self.destinations = destinations
}
enum CodingKeys: String, CodingKey {
case latitude
case longitude
case destinations
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let latitude = try container.decode(Double.self, forKey: .latitude)
let longitude = try container.decode(Double.self, forKey: .longitude)
let destinations = try container.decode([Destinations].self,
forKey: .destinations)
self.init(location: CLLocation(latitude: latitude, longitude: longitude),
destinations: destinations)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.location.coordinate.latitude, forKey: .latitude)
try container.encode(self.location.coordinate.longitude, forKey: .longitude)
try container.encode(self.destinations, forKey: .destinations)
}
}
/// The name of the stop
var name: String
/// The name that will be show if the title and the subtitle are separated
var title: String
/// The text that will be show beside the title
var subTitle: String
/// The stop code of the stop. This stop code is attributed by the tpg
var code: String
/// The location of the stop
var location: CLLocation
/// The distance of the user from the stop
var distance: Double
/// The id that represent the stop on the SBB API.
var sbbId: String
/// The id that represent the stop in the app.
var appId: Int
/// Is a connections map aviable for the stop.
var connectionsMap: Bool
/// Pricing zones for the stop
var pricingZone: [Int]
/// Name on the SBB API
var nameTransportAPI: String
/// Physical stops of the global stop
var localisations: [Localisations]
/// Lines and operators aviable for the stop
var lines: [String: Operator]
@available(iOS 12.0, *)
@available(watchOSApplicationExtension 5.0, *)
var intent: DeparturesIntent {
let intent = DeparturesIntent()
intent.stop = INObject(identifier: "\(code)", display: name)
intent.versionNumber = 1.0
intent.suggestedInvocationPhrase =
String(format: "View departures for %@".localized, name)
return intent
}
public init(name: String,
title: String,
subTitle: String,
code: String,
location: CLLocation,
distance: Double,
sbbId: String,
appId: Int,
pricingZone: [Int],
nameTransportAPI: String,
localisations: [Localisations],
connectionsMap: Bool,
lines: [String: Operator]) {
self.name = name
self.title = title
self.subTitle = subTitle
self.code = code
self.location = location
self.distance = distance
self.sbbId = sbbId
self.appId = appId
self.pricingZone = pricingZone
self.nameTransportAPI = nameTransportAPI
self.localisations = localisations
self.connectionsMap = connectionsMap
self.lines = lines
}
enum CodingKeys: String, CodingKey {
case name
case title
case subTitle
case code
case latitude
case longitude
case sbbId
case appId
case pricingZone
case nameTransportAPI
case localisations
case connectionsMap
case lines
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let name = try container.decode(String.self, forKey: .name)
let title = try container.decode(String.self, forKey: .title)
let subTitle = try container.decode(String.self, forKey: .subTitle)
let code = try container.decode(String.self, forKey: .code)
let latitude = try container.decode(Double.self, forKey: .latitude)
let longitude = try container.decode(Double.self, forKey: .longitude)
let sbbId = try container.decode(String.self, forKey: .sbbId)
let appId = try container.decode(Int.self, forKey: .appId)
let pricingZone = try container.decode([Int].self, forKey: .pricingZone)
let nameTransportAPI =
try container.decode(String.self, forKey: .nameTransportAPI)
let localisations =
try container.decode([Localisations].self, forKey: .localisations)
let connectionsMap = try container.decode(Bool.self, forKey: .connectionsMap)
let lines = try container.decode([String: Operator].self, forKey: .lines)
self.init(name: name,
title: title,
subTitle: subTitle,
code: code,
location: CLLocation(latitude: latitude, longitude: longitude),
distance: 0,
sbbId: sbbId,
appId: appId,
pricingZone: pricingZone,
nameTransportAPI: nameTransportAPI,
localisations: localisations,
connectionsMap: connectionsMap,
lines: lines)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.name, forKey: .name)
try container.encode(self.title, forKey: .title)
try container.encode(self.subTitle, forKey: .subTitle)
try container.encode(self.code, forKey: .code)
try container.encode(self.location.coordinate.latitude, forKey: .latitude)
try container.encode(self.location.coordinate.longitude, forKey: .longitude)
try container.encode(self.sbbId, forKey: .sbbId)
try container.encode(self.appId, forKey: .appId)
try container.encode(self.pricingZone, forKey: .pricingZone)
try container.encode(self.nameTransportAPI, forKey: .nameTransportAPI)
try container.encode(self.localisations, forKey: .localisations)
try container.encode(self.connectionsMap, forKey: .connectionsMap)
try container.encode(self.lines, forKey: .lines)
}
static func == (lhd: Stop, rhd: Stop) -> Bool {
return lhd.appId == rhd.appId
}
enum Operator: String, Codable {
case tpg = "tpg"
case tac = "tac"
}
}
| mit | f84218947285fcb784952b24400cf5a7 | 30.895238 | 82 | 0.669155 | 4.244613 | false | false | false | false |
gottesmm/swift | test/DebugInfo/generic_arg2.swift | 2 | 925 | // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests %s -emit-ir -g -o - | %FileCheck %s
// CHECK: define hidden void @_T012generic_arg25ClassC3foo{{.*}}, %swift.type* %U
// CHECK: [[Y:%.*]] = getelementptr inbounds %C12generic_arg25Class, %C12generic_arg25Class* %2, i32 0, i32 0, i32 0
// store %swift.opaque* %[[Y]], %swift.opaque** %[[Y_SHADOW:.*]], align
// CHECK: call void @llvm.dbg.declare(metadata %swift.opaque** %y.addr, metadata ![[U:.*]], metadata !{{[0-9]+}})
// Make sure there is no conflicting dbg.value for this variable.x
// CHECK-NOT: dbg.value{{.*}}metadata ![[U]]
class Class <T> {
// CHECK: ![[U]] = !DILocalVariable(name: "y", arg: 2{{.*}} line: [[@LINE+1]],
func foo<U>(_ x: T, y: U) {}
func bar(_ x: String, y: Int64) {}
init() {}
}
func main() {
var object: Class<String> = Class()
var x = "hello"
var y : Int64 = 1234
object.bar(x, y: y)
object.foo(x, y: y)
}
main()
| apache-2.0 | b14f17417db01a7a1e37be5f5cc5231e | 34.576923 | 116 | 0.603243 | 2.899687 | false | false | false | false |
manuelescrig/SwiftSkeleton | SwiftSkeleton/Classes/Blocks/BlockButton.swift | 7 | 3398 | //
// BlockButton.swift
//
//
// Created by Cem Olcay on 12/08/15.
//
//
import UIKit
public typealias BlockButtonAction = (_ sender: BlockButton) -> Void
///Make sure you use "[weak self] (sender) in" if you are using the keyword self inside the closure or there might be a memory leak
open class BlockButton: UIButton {
// MARK: Propeties
open var highlightLayer: CALayer?
open var action: BlockButtonAction?
// MARK: Init
public init() {
super.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
defaultInit()
}
public init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat) {
super.init(frame: CGRect(x: x, y: y, width: w, height: h))
defaultInit()
}
public init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat, action: BlockButtonAction?) {
super.init (frame: CGRect(x: x, y: y, width: w, height: h))
self.action = action
defaultInit()
}
public init(action: @escaping BlockButtonAction) {
super.init(frame: CGRect.zero)
self.action = action
defaultInit()
}
public override init(frame: CGRect) {
super.init(frame: frame)
defaultInit()
}
public init(frame: CGRect, action: @escaping BlockButtonAction) {
super.init(frame: frame)
self.action = action
defaultInit()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
defaultInit()
}
private func defaultInit() {
addTarget(self, action: #selector(BlockButton.didPressed(_:)), for: UIControlEvents.touchUpInside)
addTarget(self, action: #selector(BlockButton.highlight), for: [UIControlEvents.touchDown, UIControlEvents.touchDragEnter])
addTarget(self, action: #selector(BlockButton.unhighlight), for: [
UIControlEvents.touchUpInside,
UIControlEvents.touchUpOutside,
UIControlEvents.touchCancel,
UIControlEvents.touchDragExit
])
setTitleColor(UIColor.black, for: UIControlState.normal)
setTitleColor(UIColor.blue, for: UIControlState.selected)
}
open func addAction(_ action: @escaping BlockButtonAction) {
self.action = action
}
// MARK: Action
open func didPressed(_ sender: BlockButton) {
action?(sender)
}
// MARK: Highlight
open func highlight() {
if action == nil {
return
}
let highlightLayer = CALayer()
highlightLayer.frame = layer.bounds
highlightLayer.backgroundColor = UIColor.black.cgColor
highlightLayer.opacity = 0.5
var maskImage: UIImage? = nil
UIGraphicsBeginImageContextWithOptions(layer.bounds.size, false, 0)
if let context = UIGraphicsGetCurrentContext() {
layer.render(in: context)
maskImage = UIGraphicsGetImageFromCurrentImageContext()
}
UIGraphicsEndImageContext()
let maskLayer = CALayer()
maskLayer.contents = maskImage?.cgImage
maskLayer.frame = highlightLayer.frame
highlightLayer.mask = maskLayer
layer.addSublayer(highlightLayer)
self.highlightLayer = highlightLayer
}
open func unhighlight() {
if action == nil {
return
}
highlightLayer?.removeFromSuperlayer()
highlightLayer = nil
}
}
| mit | 9d85c8b36b91c5f017f0d49b3fedab42 | 28.807018 | 132 | 0.629782 | 4.623129 | false | false | false | false |
vimeo/VimeoUpload | VimeoUpload/Upload/Operations/Async/ExportOperation.swift | 1 | 8820 | //
// ExportOperation.swift
// VimeoUpload
//
// Created by Hanssen, Alfie on 10/13/15.
// Copyright © 2015 Vimeo. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import AVFoundation
#if os(iOS)
import MobileCoreServices
#elseif os(OSX)
import CoreServices
#endif
@objc public class ExportOperation: ConcurrentOperation
{
private static let ProgressKeyPath = "progress"
private static let FileType = AVFileType.mp4
private(set) var exportSession: AVAssetExportSession
// We KVO on this internally in order to call the progressBlock, see note below as to why [AH] 10/22/2015
@objc private dynamic var progress: Float = 0
private var exportProgressKVOContext = UInt8()
var progressBlock: ProgressBlock?
private(set) var outputURL: URL?
private(set) var error: NSError?
// MARK: - Initialization
convenience init(asset: AVAsset, documentsFolderURL: URL? = nil)
{
let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetPassthrough)!
self.init(exportSession: exportSession, documentsFolderURL: documentsFolderURL)
}
init(exportSession: AVAssetExportSession, documentsFolderURL: URL? = nil)
{
// exportSession.timeRange must be valid so that the exportSession's estimatedOutputFileLength is non zero
// We use estimatedOutputFileLength below to check that there is ample disk space to perform the export [AH] 10/15/2015
exportSession.timeRange = CMTimeRangeMake(start: CMTime.zero, duration: exportSession.asset.duration)
assert(CMTIMERANGE_IS_EMPTY(exportSession.timeRange) == false, "exportSession.timeRange is empty")
assert(CMTIMERANGE_IS_INDEFINITE(exportSession.timeRange) == false, "exportSession.timeRange is indefinite")
assert(CMTIMERANGE_IS_INVALID(exportSession.timeRange) == false, "exportSession.timeRange is invalid")
assert(CMTIMERANGE_IS_VALID(exportSession.timeRange) == true, "exportSession.timeRange is not valid")
assert(CMTIME_IS_POSITIVEINFINITY(exportSession.timeRange.duration) == false, "exportSession.timeRange.duration is infinite")
exportSession.shouldOptimizeForNetworkUse = true
exportSession.outputFileType = ExportOperation.FileType
do
{
let filename = ProcessInfo.processInfo.globallyUniqueString
exportSession.outputURL = try URL.uploadURL(documentsFolderURL: documentsFolderURL, withFileName: filename, fileType: type(of: self).FileType.rawValue)
}
catch let error as NSError
{
fatalError("Error creating upload export directory: \(error.localizedDescription)")
}
self.exportSession = exportSession
super.init()
self.addObservers()
}
deinit
{
self.removeObservers()
self.progressBlock = nil
self.exportSession.cancelExport()
}
// MARK: Overrides
@objc override public func main()
{
if self.isCancelled
{
return
}
if self.exportSession.asset.isExportable == false // DRM protected
{
self.error = NSError.error(withDomain: UploadErrorDomain.ExportOperation.rawValue, code: UploadLocalErrorCode.assetIsNotExportable.rawValue, description: "Asset is not exportable")
self.state = .finished
return
}
// AVAssetExportSession does not do an internal check to see if there's ample disk space available to perform the export [AH] 12/06/2015
// However this check will not work with presetName "passthrough" since that preset reports estimatedOutputFileLength of zero always.
let availableDiskSpace = try? FileManager.default.availableDiskSpace()
if let space = availableDiskSpace, space.int64Value < self.exportSession.estimatedOutputFileLength
{
self.error = NSError.error(withDomain: UploadErrorDomain.ExportOperation.rawValue, code: UploadLocalErrorCode.diskSpaceException.rawValue, description: "Not enough disk space to copy asset")
self.state = .finished
return
}
self.exportSession.exportAsynchronously(completionHandler: { [weak self] () -> Void in
guard let strongSelf = self else
{
return
}
if strongSelf.isCancelled
{
return
}
if let error = strongSelf.exportSession.error
{
strongSelf.error = (error as NSError).error(byAddingDomain: UploadErrorDomain.ExportOperation.rawValue)
if (error as NSError).domain == AVFoundationErrorDomain && (error as NSError).code == AVError.Code.diskFull.rawValue
{
strongSelf.error = (error as NSError).error(byAddingDomain: UploadErrorDomain.ExportOperation.rawValue).error(byAddingCode: UploadLocalErrorCode.diskSpaceException.rawValue)
}
else
{
strongSelf.error = (error as NSError).error(byAddingDomain: UploadErrorDomain.ExportOperation.rawValue)
}
}
else if let outputURL = strongSelf.exportSession.outputURL, FileManager.default.fileExists(atPath: outputURL.path)
{
strongSelf.outputURL = outputURL
}
else
{
strongSelf.error = NSError.error(withDomain: UploadErrorDomain.ExportOperation.rawValue, code: nil, description: "Export session finished with no error and no output URL.")
}
strongSelf.state = .finished
})
// For some reason, not sure why, KVO on self.exportSession.progress does not trigger calls to observeValueForKeyPath
// So I'm using this while loop to update a dynamic property instead, and KVO'ing on that [AH] 10/22/2015
DispatchQueue.global(qos: .utility).async { [weak self] () -> Void in
while self?.exportSession.status == .waiting || self?.exportSession.status == .exporting
{
self?.progress = self?.exportSession.progress ?? 0
}
}
}
@objc override public func cancel()
{
super.cancel()
self.progressBlock = nil
self.exportSession.cancelExport()
}
// MARK: KVO
private func addObservers()
{
self.addObserver(self, forKeyPath: type(of: self).ProgressKeyPath, options: NSKeyValueObservingOptions.new, context: &self.exportProgressKVOContext)
}
private func removeObservers()
{
self.removeObserver(self, forKeyPath: type(of: self).ProgressKeyPath, context: &self.exportProgressKVOContext)
}
@objc override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?)
{
if let keyPath = keyPath
{
switch (keyPath, context)
{
case(type(of: self).ProgressKeyPath, .some(&self.exportProgressKVOContext)):
let progress = (change?[.newKey] as AnyObject).doubleValue ?? 0
self.progressBlock?(progress)
default:
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
else
{
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
}
| mit | 7f2ff27f96a1bb1f3c50c16a1ebc1e56 | 39.828704 | 202 | 0.654269 | 5.019351 | false | false | false | false |
IvanRublev/PersistentStorageSerializable | Example/Tests/PersistentStorageMock.swift | 1 | 1394 | //
// PersistentStorageMock.swift
// PersistentStorageSerializable
//
// Created by Ivan Rublev on 4/5/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Foundation
import PersistentStorageSerializable
class PersistentStorageMock: PersistentStorage {
var transactionWasBegan = false
func beginTransaction() throws {
transactionWasBegan = true
}
open static let shared: PersistentStorage = PersistentStorageMock()
var registeredDefaultValues: [String : Any]?
func register(defaultValues: [String : Any]) {
registeredDefaultValues = defaultValues
}
typealias ValuesDictionary = Dictionary<String, Any>
var tempValues = ValuesDictionary()
var values = ValuesDictionary()
public func get(valueOf key: String) -> Any? {
if let value = tempValues[key] {
return value
}
return values[key]
}
enum InternalError: Error {
case Failure
}
var throwOnSet: InternalError?
func set(value: Any?, for key: String) throws {
if let errorToThrow = throwOnSet {
throw errorToThrow
}
tempValues[key] = value
}
var synchronizeWasCalled = false
func finishTransaction() throws {
values = tempValues
tempValues.removeAll()
synchronizeWasCalled = true
}
}
| mit | 3286c478936155cf24fdcadfcc522dd2 | 23.438596 | 71 | 0.644652 | 4.957295 | false | false | false | false |
fedepo/phoneid_iOS | Pod/Classes/utils/PhoneIdLoginFlowManager.swift | 2 | 5127 | //
// PhoneIdLoginWorkflowManager.swift
// phoneid_iOS
//
// Copyright 2015 phone.id - 73 knots, 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 Foundation
open class PhoneIdLoginWorkflowManager:NSObject, Customizable {
@objc open var colorScheme: ColorScheme!
@objc open var localizationBundle: Bundle!
@objc open var localizationTableName: String!
var phoneIdService: PhoneIdService
var phoneIdComponentFactory: ComponentFactory
@objc public override init() {
phoneIdService = PhoneIdService.sharedInstance
phoneIdComponentFactory = phoneIdService.componentFactory
super.init()
prep()
}
@objc public init(phoneIdService _phoneIdService:PhoneIdService, phoneIdComponentFactory _phoneIdComponentFactory:ComponentFactory){
phoneIdService = _phoneIdService
phoneIdComponentFactory = _phoneIdComponentFactory
super.init()
prep()
}
@objc open func startLoginFlow(_ presentFromController:UIViewController? = nil,
initialPhoneNumerE164:String? = nil,
startAnimatingProgress:(()->())? = nil,
stopAnimationProgress:(()->())? = nil){
login(presentFromController:presentFromController,
initialPhoneNumerE164:initialPhoneNumerE164,
lock:nil,
unlock:nil,
startAnimatingProgress: startAnimatingProgress,
stopAnimationProgress: stopAnimationProgress)
}
func prep() {
localizationBundle = phoneIdComponentFactory.localizationBundle
localizationTableName = phoneIdComponentFactory.localizationTableName
colorScheme = phoneIdComponentFactory.colorScheme
}
func login(presentFromController controller:UIViewController?,
initialPhoneNumerE164:String?,
lock:(()->())?,
unlock:(()->())?,
startAnimatingProgress:(()->(Void))?,
stopAnimationProgress:(()->())?){
lock?()
if (phoneIdService.clientId == nil) {
fatalError("Phone.id is not configured for use: clientId is not set. Please call configureClient(clientId) first")
}
if (phoneIdService.appName != nil) {
self.presentLoginViewController(initialPhoneNumerE164, presentingViewController:self.presentingController())
unlock?()
} else {
startAnimatingProgress?()
phoneIdService.loadClients(phoneIdService.clientId!, completion: { [weak self] (error) -> Void in
guard let me = self else {return}
stopAnimationProgress?()
let presenter = me.presentingController()
if (error == nil) {
me.presentLoginViewController(initialPhoneNumerE164, presentingViewController:presenter)
} else {
let alertController = UIAlertController(title: error?.localizedDescription, message: error?.localizedFailureReason, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: me.localizedString("alert.button.title.dismiss"), style: .cancel, handler: nil));
presenter.present(alertController, animated: true, completion: nil)
}
unlock?()
})
}
}
fileprivate func presentingController() -> UIViewController{
let phoneIdWindow = PhoneIdWindow()
phoneIdWindow.makeActive()
let presentingController = phoneIdWindow.rootViewController!
return presentingController
}
fileprivate func presentLoginViewController(_ phoneNumberE164:String?, presentingViewController:UIViewController) {
let controller = phoneIdComponentFactory.loginViewController()
let navigation = UINavigationController(rootViewController: controller)
navigation.navigationBar.isHidden = true
if let phoneNumberE164 = phoneNumberE164 {
controller.phoneIdModel = NumberInfo(numberE164: phoneNumberE164)
}
presentingViewController.present(navigation, animated: true, completion: nil)
}
}
| apache-2.0 | 34755a8fa1ca056e42a7007396967eae | 37.261194 | 159 | 0.611859 | 5.79322 | false | false | false | false |
CosmicMind/Samples | Projects/Programmatic/TabsController/TabsController/AppTabsController.swift | 1 | 2435 | /*
* Copyright (C) 2015 - 2018, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import Material
class AppTabsController: TabsController {
open override func prepare() {
super.prepare()
tabBar.setLineColor(Color.orange.base, for: .selected) // or tabBar.lineColor = Color.orange.base
tabBar.setTabItemsColor(Color.grey.base, for: .normal)
tabBar.setTabItemsColor(Color.purple.base, for: .selected)
tabBar.setTabItemsColor(Color.green.base, for: .highlighted)
tabBar.tabItems.first?.setTabItemColor(Color.blue.base, for: .selected)
// let color = tabBar.tabItems.first?.getTabItemColor(for: .selected)
// tabBarAlignment = .top
// tabBar.tabBarStyle = .auto
// tabBar.dividerColor = nil
// tabBar.lineHeight = 5.0
// tabBar.lineAlignment = .bottom
// tabBar.backgroundColor = Color.blue.darken2
}
}
| bsd-3-clause | 3a4ed902153e5094c25a3317caf40e24 | 44.943396 | 101 | 0.740452 | 4.249564 | false | false | false | false |
cruisediary/Diving | Diving/Workers/Travels/TravelsWorker.swift | 1 | 2532 | //
// TravelWorker.swift
// Diving
//
// Created by CruzDiary on 7/5/16.
// Copyright © 2016 DigitalNomad. All rights reserved.
//
import UIKit
import RealmSwift
class TravelsWorker: NSObject {
let travelsService: TravelsServiceProtocol
init (travelsService: TravelsServiceProtocol) {
self.travelsService = travelsService
}
func createTravel(createForm: TravelCreateForm) {
//travelsService.createObject(createForm)
}
func fetchTravels(completionHandler: (travles:[Travel]) -> Void) {
travelsService.fetchTravels { (result) in
switch result {
case .success(let fetched):
completionHandler(travles: fetched)
case .failure(let error):
print(error)
}
}
}
}
protocol TravelsServiceProtocol {
func fetchTravels(completionHandler: TravelsFetchTravelsCompletionHandler)
func fetchTravel(id: String, completionHandler: TravelsFetchTravelCompletionHandler)
func createTravel(travelToCreate: Travel, completionHandler: TravelsCreateTravelCompletionHandler)
func updateTravel(travelToUpdate: Travel, completionHandler: TravelsUpdateTravelCompletionHandler)
func deleteTravel(id: String, completionHandler: TravelsDeleteTravelCompletionHandler)
}
typealias TravelsFetchTravelsCompletionHandler = (result: TravelsServiceResult<[Travel]>) -> Void
typealias TravelsFetchTravelCompletionHandler = (result: TravelsServiceResult<Travel>) -> Void
typealias TravelsCreateTravelCompletionHandler = (result: TravelsServiceResult<Void>) -> Void
typealias TravelsUpdateTravelCompletionHandler = (result: TravelsServiceResult<Void>) -> Void
typealias TravelsDeleteTravelCompletionHandler = (result: TravelsServiceResult<Void>) -> Void
enum TravelsServiceResult<U> {
case success(result: U)
case failure(error: TravelsServiceError)
}
enum TravelsServiceError: Equatable, ErrorType {
case cannotFetch(String)
case cannotCreate(String)
case cannotUpdate(String)
case cannotDelete(String)
}
func ==(lhs: TravelsServiceError, rhs: TravelsServiceError) -> Bool {
switch (lhs, rhs) {
case (.cannotFetch(let a), .cannotFetch(let b)) where a == b: return true
case (.cannotCreate(let a), .cannotCreate(let b)) where a == b: return true
case (.cannotUpdate(let a), .cannotUpdate(let b)) where a == b: return true
case (.cannotDelete(let a), .cannotDelete(let b)) where a == b: return true
default: return false
}
} | mit | 8b5d5adfcd2f4d026d7d1c69f5773ea4 | 34.661972 | 102 | 0.72422 | 4.401739 | false | false | false | false |
pkkup/Pkkup-iOS | Pkkup/models/PkkupLocation.swift | 1 | 3622 | //
// PkkupLocation.swift
// Pkkup
//
// Copyright (c) 2014 Pkkup. All rights reserved.
//
import Foundation
import CoreLocation
var _pkkupLocationCache = NSCache()
class PkkupLocation {
var locationDictionary: NSDictionary
// Location attributes
var id: Int?
var name: String?
var address: String?
var city: String?
var state: String?
var zipcode: String?
var latitude: Double?
var longitude: Double?
// Relations
var games: [PkkupGame]?
var players: [PkkupPlayer]?
var upcomingGames: [PkkupGame]?
var todayGames: [PkkupGame]?
var pastGames: [PkkupGame]?
init(dictionary: NSDictionary) {
self.locationDictionary = dictionary
id = dictionary["id"] as? Int
name = dictionary["name"] as? String
address = dictionary["address"] as? String
city = dictionary["city"] as? String
state = dictionary["state"] as? String
zipcode = dictionary["zipcode"] as? String
latitude = dictionary["latitude"] as? Double
longitude = dictionary["longitude"] as? Double
var gamesDict = dictionary["games"] as? NSDictionary
var upcomingArray = gamesDict?["upcoming"] as? [NSDictionary]
upcomingGames = PkkupGame.gamesWithArray(upcomingArray!)
var todayArray = gamesDict?["today"] as? [NSDictionary]
todayGames = PkkupGame.gamesWithArray(todayArray!)
var pastArray = gamesDict?["past"] as? [NSDictionary]
pastGames = PkkupGame.gamesWithArray(pastArray!)
_pkkupLocationCache.setObject(self, forKey: id!)
}
class func locationsWithArray(array: [NSDictionary]) -> [PkkupLocation] {
var locations = [PkkupLocation]()
for dictionary in array {
locations.append(PkkupLocation(dictionary: dictionary))
}
return locations
}
class func get(id: Int) -> PkkupLocation {
var location = PkkupLocation.getCached(id)!
return location
}
class func getCached(id: Int) -> PkkupLocation? {
var location = _pkkupLocationCache.objectForKey(id) as? PkkupLocation
return location
}
class func locationsWithIds(locationIds: [Int]) -> [PkkupLocation] {
var locations = locationIds.map({
(locationId: Int) -> PkkupLocation in
PkkupLocation.get(locationId)
})
return locations
}
func getCityAndStateString() -> String {
var value = "\(self.city!), \(self.state!)"
return value
}
func getWeather() {
// get from Forecast.io
// temp, status (sunny, cloudy, etc)
}
func getGames() -> [PkkupGame]? {
// get and store locally
return self.games
}
func getCurrentDistanceInMeters() -> Double? {
var currentLocation = HTKLocationUtils.sharedInstance.mostRecentLocation
var distanceMeters: Double?
if let currentLocation = currentLocation {
var thisCLLocation = CLLocation(latitude: self.latitude!, longitude: self.longitude!)
distanceMeters = currentLocation.distanceFromLocation(thisCLLocation)
}
return distanceMeters
}
func getCurrentDistanceInMiles() -> Double? {
var distanceMeters = getCurrentDistanceInMeters()
var distanceMiles: Double?
if let distanceMeters = distanceMeters {
let metersPerMile = 1609.344
distanceMiles = distanceMeters / metersPerMile
}
return distanceMiles
}
func getMap() {
// use MapKit
}
}
| mit | 0bff81e0ebac56f713cfd788a0f2e1e1 | 28.447154 | 97 | 0.627278 | 4.427873 | false | false | false | false |
dritani/Antique-Book-Scan | Antique Book Scan/ResultsViewController.swift | 1 | 17365 | //
// ResultsViewController.swift
// Antique Book Scan
//
// Created by Dritani on 2017-03-25.
// Copyright © 2017 AquariusLB. All rights reserved.
//
import UIKit
import NVActivityIndicatorView
import DZNEmptyDataSet
import MBProgressHUD
struct BookResult {
var market:String
var price:Float
var condition:String
var buyLink:String?
init(market:String,price:Float,condition:String,buyLink:String?) {
self.market = market
self.price = price
self.condition = condition
self.buyLink = buyLink
}
}
class ResultsViewController: UIViewController {
var bookData:BookData!
var completionAmazon:([BookResult]?)->Void = {_ in }
var completionEBay:([BookResult]?)->Void = {_ in }
var completionDT:([BookResult]?)->Void = {_ in }
var apisCalled:Int = 0
var maxAPIs = 2
var bookCoverImageView:UIImageView!
var bookTitle:UILabel!
var authorsLabel:UILabel!
var backButton:UIButton!
var resultsTableView:UITableView!
var newResults:[BookResult] = []
var usedResults:[BookResult] = []
var eBookResults:[BookResult] = []
// Beginning
override func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false
self.edgesForExtendedLayout = []
navigationController?.navigationBar.isHidden = true
setupContents()
setupCompletionHandlers()
callAPIs()
}
func setupContents() {
view.backgroundColor = UIColor.black
bookCoverImageView = UIImageView(image: UIImage(named:"default cover.png"))
let bookCoverImageSize = CGSize(width:100,height:150)
bookCoverImageView.frame = CGRect(origin:CGPoint(x:0,y:0),size: bookCoverImageSize)
bookCoverImageView.center = CGPoint(x:10+bookCoverImageView.frame.width/2, y:20+bookCoverImageView.frame.height/2)
if (bookData.coverURL != nil) {
getCoverImage()
}
view.addSubview(bookCoverImageView)
bookTitle = UILabel()
bookTitle.isOpaque = false
let title:String = bookData.subTitle != nil ? bookData.bookTitle + ": " + bookData.subTitle! : bookData.bookTitle
let authors = bookData.authors?.joined(separator: ", ")
var myString:String = title + "\n" + "by " + authors!
let myMutableString = NSMutableAttributedString(string: myString, attributes: [NSFontAttributeName:UIFont(name: "AvenirNext-Regular", size: 15)!])
myMutableString.addAttribute(NSForegroundColorAttributeName, value: yellowColor, range: NSRange(location:0,length:title.characters.count+4))
myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.white, range: NSRange(location:title.characters.count+1,length:authors!.characters.count+3))
bookTitle.attributedText = myMutableString
let bookTitleSize = CGSize(width: self.view.frame.width - bookCoverImageView.frame.width - 30, height: 75)
bookTitle.frame = CGRect(origin:CGPoint(x:0,y:0),size: bookTitleSize)
//bookTitle.sizeToFit()
bookTitle.lineBreakMode = .byWordWrapping
bookTitle.numberOfLines = 0
bookTitle.adjustsFontSizeToFitWidth = true
bookTitle.center = CGPoint(x:bookCoverImageView.frame.width + 20 + bookTitleSize.width/2, y:20 + bookTitle.frame.height/2)
view.addSubview(bookTitle)
backButton = UIButton()
backButton.setImage(UIImage(named: "backButton.png"), for: .normal)
let backButtonSize = CGSize(width:50,height:27)
backButton.frame = CGRect(origin:CGPoint(x:0,y:0),size: backButtonSize)
backButton.center = CGPoint(x:view.frame.width-10-backButton.frame.width/2, y:bookCoverImageView.frame.height + 20 - backButton.frame.height/2)
backButton.addTarget(self, action: #selector(self.returnToCamera), for: .touchUpInside)
view.addSubview(backButton)
resultsTableView = UITableView()
resultsTableView.tableHeaderView = nil
let resultsTableViewSize = CGSize(width:view.bounds.size.width,height:view.bounds.size.height-40-bookCoverImageView.frame.height)
resultsTableView.frame = CGRect(origin:CGPoint.zero,size: resultsTableViewSize)
resultsTableView.center = CGPoint(x:view.frame.size.width/2, y:20 + bookCoverImageView.frame.height + 20 + resultsTableView.frame.height/2)
resultsTableView.delegate = self
resultsTableView.dataSource = self
resultsTableView.backgroundColor = UIColor.black
resultsTableView.register(resultTableViewCell.self, forCellReuseIdentifier: "resultTableViewCell")
resultsTableView.emptyDataSetSource = self;
resultsTableView.emptyDataSetDelegate = self;
resultsTableView.tableFooterView = UIView()
resultsTableView.separatorStyle = .none
view.addSubview(resultsTableView)
}
func returnToCamera() {
sharedSession.getAllTasks(completionHandler: { tasks in
for task in tasks {
task.cancel()
}
})
navigationController?.popToRootViewController(animated: true)
}
func getCoverImage() {
let url = URL(string: bookData.coverURL!)
let request = URLRequest(url: url!)
print("getting cover image")
let task = sharedSession.dataTask(with: request) { (data, response, error) in
guard (error == nil) else {
print("There was an error with your request: \(error)")
return
}
guard let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode >= 200 && statusCode <= 299 else {
print("Your request returned a status code other than 2xx!")
return
}
guard let data = data else {
print("No data was returned by the request!")
return
}
let image = UIImage(data: data)
DispatchQueue.main.async {
self.bookCoverImageView.image = image
}
}
task.resume()
}
func setupCompletionHandlers() {
completionAmazon = {bookResults in
if bookResults == nil {
//self.loadingIcon.stopAnimating()
}
self.checkBookResults(bookResults: bookResults)
}
completionEBay = {bookResults in
self.checkBookResults(bookResults: bookResults)
}
completionDT = {bookResults in
self.checkBookResults(bookResults: bookResults)
}
}
func checkBookResults(bookResults:[BookResult]?) {
if (bookResults != nil) {
for bookResult in bookResults! {
let condition:String = bookResult.condition
switch condition {
case "new":
var insertionIndex = 0
for result in self.newResults {
if (bookResult.price > result.price) {
insertionIndex += 1
}
}
self.newResults.insert(bookResult, at: insertionIndex)
case "used":
var insertionIndex = 0
for result in self.usedResults {
if (bookResult.price > result.price) {
insertionIndex += 1
}
}
self.usedResults.insert(bookResult, at: insertionIndex)
case "eBook":
var insertionIndex = 0
for result in self.eBookResults {
if (bookResult.price > result.price) {
insertionIndex += 1
}
}
self.eBookResults.insert(bookResult, at: insertionIndex)
default:
break
}
}
DispatchQueue.main.async {
// reloadatindexpath???
self.resultsTableView.reloadData()
self.checkAPIsDone()
}
}
}
func checkAPIsDone() {
apisCalled += 1
if apisCalled == 2 {
self.resultsTableView.reloadData()
}
}
func callAPIs() {
callAmazonAPIPrice(title:bookData.bookTitle,subTitle:bookData.subTitle,authors:bookData.authors,completion:completionAmazon)
callEBayAPIPrice(title:bookData.bookTitle,subTitle:bookData.subTitle,authors:bookData.authors,completion:completionEBay)
//callDTAPIPrice(identifier: bookData.identifier, identifierString: bookData.identifierString,completion:completionDT)
}
}
// MARK: TableView Delegate and DataSource
extension ResultsViewController: UITableViewDelegate,UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int{
switch section {
case 0:
return newResults.count
case 1:
return usedResults.count
case 2:
return eBookResults.count
default:
break
}
return 0
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerViewSize = CGSize(width:view.bounds.size.width,height:20)
let headerViewRect = CGRect(origin:CGPoint.zero,size: headerViewSize)
let headerView = UILabel(frame: headerViewRect)
headerView.backgroundColor = yellowColor
headerView.textColor = UIColor.black
headerView.font = UIFont(name: "AvenirNext-Regular", size: 15)
headerView.textAlignment = .center
switch section {
case 0:
headerView.text = "New"
case 1:
headerView.text = "Used"
case 2:
headerView.text = "eBook"
default:
break
}
return headerView
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
switch section {
case 0:
if newResults.count == 0 {
return 0
} else {
return 20
}
case 1:
if usedResults.count == 0 {
return 0
} else {
return 20
}
case 2:
if eBookResults.count == 0 {
return 0
} else {
return 20
}
default:
break
}
return 20
}
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell:resultTableViewCell
cell = tableView.dequeueReusableCell(withIdentifier: "resultTableViewCell")! as! resultTableViewCell
var resultsArray:[BookResult]!
switch indexPath.section {
case 0:
resultsArray = newResults
case 1:
resultsArray = usedResults
case 2:
resultsArray = eBookResults
default:
break
}
// set cell image and title
let market = resultsArray[indexPath.row].market
switch market {
case "amazon":
cell.marketImage.image = UIImage(named:"amazon logo.jpg")
cell.marketLabel.text = "Amazon"
case "ebay":
cell.marketImage.image = UIImage(named:"ebay logo.png")
cell.marketLabel.text = "eBay"
case "alibris":
cell.marketImage.image = UIImage(named:"alibris logo.png")
cell.marketLabel.text = "Alibris"
case "abebooks":
cell.marketImage.image = UIImage(named:"abebooks logo.jpg")
cell.marketLabel.text = "Abebooks"
case "b&n":
cell.marketImage.image = UIImage(named:"barnes and noble logo.png")
cell.marketLabel.text = "Barnes & Noble"
default:
break
}
// set cell price
cell.priceLabel.text = String(format: "%.02f", resultsArray[indexPath.row].price)
return cell
}
func tableView(_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath){
var resultsArray:[BookResult]!
switch indexPath.section {
case 0:
resultsArray = newResults
case 1:
resultsArray = usedResults
case 2:
resultsArray = eBookResults
default:
break
}
if resultsArray.count != 0 {
let buyLink:String? = resultsArray[indexPath.row].buyLink
if buyLink != nil {
//UIApplication.shared.open(URL(string:buyLink!)!, options: [:], completionHandler: nil)
let hud = MBProgressHUD.showAdded(to: view, animated: true)
hud.mode = .customView
hud.customView = UIImageView(image: UIImage(named:"clipboard.png"))
hud.label.text = "Copied link to clipboard"
hud.center = view.center
hud.isHidden = false
_ = Timer.scheduledTimer(withTimeInterval: 2, repeats: false, block: {_ in
hud.hide(animated: true)
})
UIPasteboard.general.string = buyLink!
}
}
}
}
extension ResultsViewController: DZNEmptyDataSetSource,DZNEmptyDataSetDelegate {
func customView(forEmptyDataSet scrollView: UIScrollView!) -> UIView! {
let viewToReturn = UIView(frame: resultsTableView.frame)
var emptyImage:UIImage!
var emptyText:String!
if apisCalled == maxAPIs {
emptyImage = imageWithImage(image: UIImage(named:"no books found.png")!, newSize:CGSize(width:viewToReturn.frame.width*0.5,height:viewToReturn.frame.height*0.5))
emptyText = "No results found"
} else {
emptyImage = imageWithImage(image: UIImage(named:"getting books.png")!,newSize:CGSize(width:viewToReturn.frame.width*0.5,height:viewToReturn.frame.height*0.5))
emptyText = "Fetching results"
}
// add ImageView
let imageView = UIImageView(image: emptyImage)
imageView.center = CGPoint(x:viewToReturn.frame.width/2,y:-viewToReturn.frame.height/7)
viewToReturn.addSubview(imageView)
let attributes:[String:Any] = [NSFontAttributeName: UIFont(name: "AvenirNext-Regular", size: 20) as Any,NSForegroundColorAttributeName:yellowColor]
let emptyTitle:NSAttributedString! = NSAttributedString(string: emptyText, attributes: attributes)
// add UILabel
let label = UILabel()
label.textAlignment = .center
label.attributedText = emptyTitle
let labelSize = CGSize(width: 200, height: 40)
label.frame = CGRect(origin:CGPoint.zero,size: labelSize)
label.adjustsFontSizeToFitWidth = true
label.center = CGPoint(x:viewToReturn.frame.width/2,y:imageView.center.y+imageView.frame.height/2+label.frame.height/2+10)
viewToReturn.addSubview(label)
//add Loading Indicator
let loadingIcon2 = NVActivityIndicatorView(frame: CGRect(origin:CGPoint(x:0,y:0),size: CGSize(width:40,height:40)), type: .ballSpinFadeLoader, color: UIColor.yellow)
let loadingIconSize = CGSize(width:40,height:40)
loadingIcon2.frame = CGRect(origin:CGPoint.zero,size: loadingIconSize)
loadingIcon2.center = CGPoint(x:viewToReturn.frame.width/2, y:label.center.y+label.frame.height/2+loadingIcon2.frame.height/2+10)
loadingIcon2.startAnimating()
if apisCalled != maxAPIs {
viewToReturn.addSubview(loadingIcon2)
}
return viewToReturn
}
func imageWithImage(image:UIImage, newSize:CGSize) -> UIImage{
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0);
image.draw(in: CGRect(origin: CGPoint.zero, size: CGSize(width: newSize.width, height: newSize.height)))
let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}
func backgroundColor(forEmptyDataSet scrollView: UIScrollView!) -> UIColor! {
return UIColor.black
}
func emptyDataSetShouldDisplay(_ scrollView: UIScrollView!) -> Bool {
return true
}
func emptyDataSetShouldAllowTouch(_ scrollView: UIScrollView!) -> Bool {
return true
}
func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView!) -> Bool {
return true
}
}
| mit | eecfa6f3127e333620c8f8664bbc8fdc | 35.024896 | 176 | 0.591166 | 5.080164 | false | false | false | false |
kylebrowning/waterwheel.swift | Sources/iOS/Extensions/UIViewExtension.swift | 1 | 1636 | //
// ViewExtension.swift
// Pods
//
// Created by Kyle Browning on 8/9/16.
//
//
import UIKit
@available(iOS 9.0, *)
extension UIView {
public func constrainEqual(_ attribute: NSLayoutAttribute, to: AnyObject, multiplier: CGFloat = 1, constant: CGFloat = 0) {
constrainEqual(attribute, to: to, attribute, multiplier: multiplier, constant: constant)
}
public func constrainEqual(_ attribute: NSLayoutAttribute, to: AnyObject, _ toAttribute: NSLayoutAttribute, multiplier: CGFloat = 1, constant: CGFloat = 0) {
NSLayoutConstraint.activate([
NSLayoutConstraint(item: self, attribute: attribute, relatedBy: .equal, toItem: to, attribute: toAttribute, multiplier: multiplier, constant: constant)
])
}
public func constrainEdges(to view: UIView) {
constrainEqual(.top, to: view, .top)
constrainEqual(.leading, to: view, .leading)
constrainEqual(.trailing, to: view, .trailing)
constrainEqual(.bottom, to: view, .bottom)
}
/// If the `view` is nil, we take the superview.
// public func center(in view: UIView? = nil) {
// guard let container = view ?? self.superview else { fatalError() }
//// centerXAnchor.constrainEqualS(acnhor: container.centerXAnchor)
//// centerYAnchor.constrainEqualS(acnhor: container.centerYAnchor)
// }
}
//@available(iOS 9.0, *)
//extension NSLayoutAnchor {
// public func constrainEqualS(acnhor anchor: NSLayoutAnchor, constant: CGFloat = 0) {
// let constraint = self.constraint(equalTo: anchor, constant: constant)
// constraint.isActive = true
// }
//}
| mit | 59c42ee3772940952c5f5d57271fa1b2 | 36.181818 | 163 | 0.669927 | 4.039506 | false | false | false | false |
ahoppen/swift | benchmark/single-source/CharacterProperties.swift | 10 | 14444 | //===--- CharacterProperties.swift ----------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 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
//
//===----------------------------------------------------------------------===//
////////////////////////////////////////////////////////////////////////////////
// WARNING: This file is manually generated from .gyb template and should not
// be directly modified. Instead, make changes to CharacterProperties.swift.gyb
// and run scripts/generate_harness/generate_harness.py to regenerate this file.
////////////////////////////////////////////////////////////////////////////////
import TestsUtils
import Foundation
public let benchmarks = [
BenchmarkInfo(
name: "CharacterPropertiesFetch",
runFunction: run_CharacterPropertiesFetch,
tags: [.validation, .api, .String],
setUpFunction: { blackHole(workload) },
legacyFactor: 10),
BenchmarkInfo(
name: "CharacterPropertiesStashed",
runFunction: run_CharacterPropertiesStashed,
tags: [.validation, .api, .String],
setUpFunction: { setupStash() },
legacyFactor: 10),
BenchmarkInfo(
name: "CharacterPropertiesStashedMemo",
runFunction: run_CharacterPropertiesStashedMemo,
tags: [.validation, .api, .String],
setUpFunction: { setupMemo() },
legacyFactor: 10),
BenchmarkInfo(
name: "CharacterPropertiesPrecomputed",
runFunction: run_CharacterPropertiesPrecomputed,
tags: [.validation, .api, .String],
setUpFunction: { setupPrecomputed() },
legacyFactor: 10),
]
extension Character {
var firstScalar: UnicodeScalar { return unicodeScalars.first! }
}
// Fetch the CharacterSet for every call
func isAlphanumeric(_ c: Character) -> Bool {
return CharacterSet.alphanumerics.contains(c.firstScalar)
}
func isCapitalized(_ c: Character) -> Bool {
return CharacterSet.capitalizedLetters.contains(c.firstScalar)
}
func isControl(_ c: Character) -> Bool {
return CharacterSet.controlCharacters.contains(c.firstScalar)
}
func isDecimal(_ c: Character) -> Bool {
return CharacterSet.decimalDigits.contains(c.firstScalar)
}
func isLetter(_ c: Character) -> Bool {
return CharacterSet.letters.contains(c.firstScalar)
}
func isLowercase(_ c: Character) -> Bool {
return CharacterSet.lowercaseLetters.contains(c.firstScalar)
}
func isUppercase(_ c: Character) -> Bool {
return CharacterSet.uppercaseLetters.contains(c.firstScalar)
}
func isNewline(_ c: Character) -> Bool {
return CharacterSet.newlines.contains(c.firstScalar)
}
func isWhitespace(_ c: Character) -> Bool {
return CharacterSet.whitespaces.contains(c.firstScalar)
}
func isPunctuation(_ c: Character) -> Bool {
return CharacterSet.punctuationCharacters.contains(c.firstScalar)
}
// Stash the set
let alphanumerics = CharacterSet.alphanumerics
func isAlphanumericStashed(_ c: Character) -> Bool {
return alphanumerics.contains(c.firstScalar)
}
let capitalizedLetters = CharacterSet.capitalizedLetters
func isCapitalizedStashed(_ c: Character) -> Bool {
return capitalizedLetters.contains(c.firstScalar)
}
let controlCharacters = CharacterSet.controlCharacters
func isControlStashed(_ c: Character) -> Bool {
return controlCharacters.contains(c.firstScalar)
}
let decimalDigits = CharacterSet.decimalDigits
func isDecimalStashed(_ c: Character) -> Bool {
return decimalDigits.contains(c.firstScalar)
}
let letters = CharacterSet.letters
func isLetterStashed(_ c: Character) -> Bool {
return letters.contains(c.firstScalar)
}
let lowercaseLetters = CharacterSet.lowercaseLetters
func isLowercaseStashed(_ c: Character) -> Bool {
return lowercaseLetters.contains(c.firstScalar)
}
let uppercaseLetters = CharacterSet.uppercaseLetters
func isUppercaseStashed(_ c: Character) -> Bool {
return uppercaseLetters.contains(c.firstScalar)
}
let newlines = CharacterSet.newlines
func isNewlineStashed(_ c: Character) -> Bool {
return newlines.contains(c.firstScalar)
}
let whitespaces = CharacterSet.whitespaces
func isWhitespaceStashed(_ c: Character) -> Bool {
return whitespaces.contains(c.firstScalar)
}
let punctuationCharacters = CharacterSet.punctuationCharacters
func isPunctuationStashed(_ c: Character) -> Bool {
return punctuationCharacters.contains(c.firstScalar)
}
func setupStash() {
blackHole(workload)
blackHole(alphanumerics)
blackHole(capitalizedLetters)
blackHole(controlCharacters)
blackHole(decimalDigits)
blackHole(letters)
blackHole(lowercaseLetters)
blackHole(uppercaseLetters)
blackHole(newlines)
blackHole(whitespaces)
blackHole(punctuationCharacters)
}
// Memoize the stashed set
var alphanumericsMemo = Set<UInt32>()
func isAlphanumericStashedMemo(_ c: Character) -> Bool {
let scalar = c.firstScalar
if alphanumericsMemo.contains(scalar.value) { return true }
if alphanumerics.contains(scalar) {
alphanumericsMemo.insert(scalar.value)
return true
}
return false
}
var capitalizedLettersMemo = Set<UInt32>()
func isCapitalizedStashedMemo(_ c: Character) -> Bool {
let scalar = c.firstScalar
if capitalizedLettersMemo.contains(scalar.value) { return true }
if capitalizedLetters.contains(scalar) {
capitalizedLettersMemo.insert(scalar.value)
return true
}
return false
}
var controlCharactersMemo = Set<UInt32>()
func isControlStashedMemo(_ c: Character) -> Bool {
let scalar = c.firstScalar
if controlCharactersMemo.contains(scalar.value) { return true }
if controlCharacters.contains(scalar) {
controlCharactersMemo.insert(scalar.value)
return true
}
return false
}
var decimalDigitsMemo = Set<UInt32>()
func isDecimalStashedMemo(_ c: Character) -> Bool {
let scalar = c.firstScalar
if decimalDigitsMemo.contains(scalar.value) { return true }
if decimalDigits.contains(scalar) {
decimalDigitsMemo.insert(scalar.value)
return true
}
return false
}
var lettersMemo = Set<UInt32>()
func isLetterStashedMemo(_ c: Character) -> Bool {
let scalar = c.firstScalar
if lettersMemo.contains(scalar.value) { return true }
if letters.contains(scalar) {
lettersMemo.insert(scalar.value)
return true
}
return false
}
var lowercaseLettersMemo = Set<UInt32>()
func isLowercaseStashedMemo(_ c: Character) -> Bool {
let scalar = c.firstScalar
if lowercaseLettersMemo.contains(scalar.value) { return true }
if lowercaseLetters.contains(scalar) {
lowercaseLettersMemo.insert(scalar.value)
return true
}
return false
}
var uppercaseLettersMemo = Set<UInt32>()
func isUppercaseStashedMemo(_ c: Character) -> Bool {
let scalar = c.firstScalar
if uppercaseLettersMemo.contains(scalar.value) { return true }
if uppercaseLetters.contains(scalar) {
uppercaseLettersMemo.insert(scalar.value)
return true
}
return false
}
var newlinesMemo = Set<UInt32>()
func isNewlineStashedMemo(_ c: Character) -> Bool {
let scalar = c.firstScalar
if newlinesMemo.contains(scalar.value) { return true }
if newlines.contains(scalar) {
newlinesMemo.insert(scalar.value)
return true
}
return false
}
var whitespacesMemo = Set<UInt32>()
func isWhitespaceStashedMemo(_ c: Character) -> Bool {
let scalar = c.firstScalar
if whitespacesMemo.contains(scalar.value) { return true }
if whitespaces.contains(scalar) {
whitespacesMemo.insert(scalar.value)
return true
}
return false
}
var punctuationCharactersMemo = Set<UInt32>()
func isPunctuationStashedMemo(_ c: Character) -> Bool {
let scalar = c.firstScalar
if punctuationCharactersMemo.contains(scalar.value) { return true }
if punctuationCharacters.contains(scalar) {
punctuationCharactersMemo.insert(scalar.value)
return true
}
return false
}
func setupMemo() {
blackHole(workload)
blackHole(alphanumericsMemo)
blackHole(capitalizedLettersMemo)
blackHole(controlCharactersMemo)
blackHole(decimalDigitsMemo)
blackHole(lettersMemo)
blackHole(lowercaseLettersMemo)
blackHole(uppercaseLettersMemo)
blackHole(newlinesMemo)
blackHole(whitespacesMemo)
blackHole(punctuationCharactersMemo)
}
// Precompute whole scalar set
func precompute(_ charSet: CharacterSet, capacity: Int) -> Set<UInt32> {
var result = Set<UInt32>(minimumCapacity: capacity)
for plane in 0...0x10 {
guard charSet.hasMember(inPlane: UInt8(plane)) else { continue }
let offset = plane &* 0x1_0000
for codePoint in 0...0xFFFF {
guard let scalar = UnicodeScalar(codePoint &+ offset) else { continue }
if charSet.contains(scalar) {
result.insert(scalar.value)
}
}
}
return result
}
var alphanumericsPrecomputed: Set<UInt32> =
precompute(alphanumerics, capacity: 122647)
func isAlphanumericPrecomputed(_ c: Character) -> Bool {
return alphanumericsPrecomputed.contains(c.firstScalar.value)
}
var capitalizedLettersPrecomputed: Set<UInt32> =
precompute(capitalizedLetters, capacity: 31)
func isCapitalizedPrecomputed(_ c: Character) -> Bool {
return capitalizedLettersPrecomputed.contains(c.firstScalar.value)
}
var controlCharactersPrecomputed: Set<UInt32> =
precompute(controlCharacters, capacity: 24951)
func isControlPrecomputed(_ c: Character) -> Bool {
return controlCharactersPrecomputed.contains(c.firstScalar.value)
}
var decimalDigitsPrecomputed: Set<UInt32> =
precompute(decimalDigits, capacity: 590)
func isDecimalPrecomputed(_ c: Character) -> Bool {
return decimalDigitsPrecomputed.contains(c.firstScalar.value)
}
var lettersPrecomputed: Set<UInt32> =
precompute(letters, capacity: 121145)
func isLetterPrecomputed(_ c: Character) -> Bool {
return lettersPrecomputed.contains(c.firstScalar.value)
}
var lowercaseLettersPrecomputed: Set<UInt32> =
precompute(lowercaseLetters, capacity: 2063)
func isLowercasePrecomputed(_ c: Character) -> Bool {
return lowercaseLettersPrecomputed.contains(c.firstScalar.value)
}
var uppercaseLettersPrecomputed: Set<UInt32> =
precompute(uppercaseLetters, capacity: 1733)
func isUppercasePrecomputed(_ c: Character) -> Bool {
return uppercaseLettersPrecomputed.contains(c.firstScalar.value)
}
var newlinesPrecomputed: Set<UInt32> =
precompute(newlines, capacity: 7)
func isNewlinePrecomputed(_ c: Character) -> Bool {
return newlinesPrecomputed.contains(c.firstScalar.value)
}
var whitespacesPrecomputed: Set<UInt32> =
precompute(whitespaces, capacity: 19)
func isWhitespacePrecomputed(_ c: Character) -> Bool {
return whitespacesPrecomputed.contains(c.firstScalar.value)
}
var punctuationCharactersPrecomputed: Set<UInt32> =
precompute(punctuationCharacters, capacity: 770)
func isPunctuationPrecomputed(_ c: Character) -> Bool {
return punctuationCharactersPrecomputed.contains(c.firstScalar.value)
}
func setupPrecomputed() {
blackHole(workload)
blackHole(alphanumericsPrecomputed)
blackHole(capitalizedLettersPrecomputed)
blackHole(controlCharactersPrecomputed)
blackHole(decimalDigitsPrecomputed)
blackHole(lettersPrecomputed)
blackHole(lowercaseLettersPrecomputed)
blackHole(uppercaseLettersPrecomputed)
blackHole(newlinesPrecomputed)
blackHole(whitespacesPrecomputed)
blackHole(punctuationCharactersPrecomputed)
}
// Compute on the fly
//
// TODO: If UnicodeScalars ever exposes category, etc., implement the others!
func isNewlineComputed(_ c: Character) -> Bool {
switch c.firstScalar.value {
case 0x000A...0x000D: return true
case 0x0085: return true
case 0x2028...0x2029: return true
default: return false
}
}
let workload = """
the quick brown 🦊 jumped over the lazy 🐶.
в чащах юга жил-был цитрус? да, но фальшивый экземпляр
𓀀𓀤𓁓𓁲𓃔𓃗𓃀𓃁𓃂𓃃𓆌𓆍𓆎𓆏𓆐𓆑𓆒𓆲𓁿
🝁ꃕ躍‾∾📦⺨
👍👩👩👧👧👨👨👦👦🇺🇸🇨🇦🇲🇽👍🏻👍🏼👍🏽👍🏾👍🏿
Lorem ipsum something something something...
"""
@inline(never)
public func run_CharacterPropertiesFetch(_ n: Int) {
for _ in 1...n {
for c in workload {
blackHole(isAlphanumeric(c))
blackHole(isCapitalized(c))
blackHole(isControl(c))
blackHole(isDecimal(c))
blackHole(isLetter(c))
blackHole(isLowercase(c))
blackHole(isUppercase(c))
blackHole(isNewline(c))
blackHole(isWhitespace(c))
blackHole(isPunctuation(c))
}
}
}
@inline(never)
public func run_CharacterPropertiesStashed(_ n: Int) {
for _ in 1...n {
for c in workload {
blackHole(isAlphanumericStashed(c))
blackHole(isCapitalizedStashed(c))
blackHole(isControlStashed(c))
blackHole(isDecimalStashed(c))
blackHole(isLetterStashed(c))
blackHole(isLowercaseStashed(c))
blackHole(isUppercaseStashed(c))
blackHole(isNewlineStashed(c))
blackHole(isWhitespaceStashed(c))
blackHole(isPunctuationStashed(c))
}
}
}
@inline(never)
public func run_CharacterPropertiesStashedMemo(_ n: Int) {
for _ in 1...n {
for c in workload {
blackHole(isAlphanumericStashedMemo(c))
blackHole(isCapitalizedStashedMemo(c))
blackHole(isControlStashedMemo(c))
blackHole(isDecimalStashedMemo(c))
blackHole(isLetterStashedMemo(c))
blackHole(isLowercaseStashedMemo(c))
blackHole(isUppercaseStashedMemo(c))
blackHole(isNewlineStashedMemo(c))
blackHole(isWhitespaceStashedMemo(c))
blackHole(isPunctuationStashedMemo(c))
}
}
}
@inline(never)
public func run_CharacterPropertiesPrecomputed(_ n: Int) {
for _ in 1...n {
for c in workload {
blackHole(isAlphanumericPrecomputed(c))
blackHole(isCapitalizedPrecomputed(c))
blackHole(isControlPrecomputed(c))
blackHole(isDecimalPrecomputed(c))
blackHole(isLetterPrecomputed(c))
blackHole(isLowercasePrecomputed(c))
blackHole(isUppercasePrecomputed(c))
blackHole(isNewlinePrecomputed(c))
blackHole(isWhitespacePrecomputed(c))
blackHole(isPunctuationPrecomputed(c))
}
}
}
// TODO: run_CharacterPropertiesComputed
// Local Variables:
// eval: (read-only-mode 1)
// End:
| apache-2.0 | 56a322a552f6bd2aa083d2202847ec0d | 31.352273 | 80 | 0.726589 | 4.045183 | false | false | false | false |
penniooi/TestKichen | TestKitchen/TestKitchen/AppDelegate.swift | 1 | 6199 | //
// AppDelegate.swift
// TestKitchen
//
// Created by aloha on 16/8/15.
// Copyright © 2016年 胡颉禹. All rights reserved.
//
import UIKit
import CoreData
import SnapKit
import Kingfisher
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
self.window?.rootViewController = MainTabBarViewController()
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.qianfeng.TestKitchen" 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("TestKitchen", 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()
}
}
}
}
| mit | c3b08d077130fc0547de185430e9c19b | 52.826087 | 291 | 0.720679 | 5.878443 | false | false | false | false |
dreamsxin/swift | validation-test/compiler_crashers_fixed/01509-bool-edited.swift | 11 | 700 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
// This test was tweaked slightly from the original 1509-bool.swift, because an
// unrelated change happened to avoid the crash.
ance(x) { self.c]
var b {
}
case ..d<T>, U, (c == {
return self.h == e? = {
}
for c : Sequence where f: C {
func b: Int
}
}
}
protocol a {
func b(Any] = "a<T) {
typealias A : A {
| apache-2.0 | 6c02e3824f596c0ec094b31f26d963c0 | 28.166667 | 79 | 0.695714 | 3.286385 | false | false | false | false |
kfarst/alarm | alarm/SwiftColors.swift | 1 | 4254 | // SwiftColors.swift
//
// Copyright (c) 2014 Doan Truong Thi
//
// 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.
#if os(iOS)
import UIKit
typealias SWColor = UIColor
#else
import Cocoa
typealias SWColor = NSColor
#endif
public extension SWColor {
/**
Create non-autoreleased color with in the given hex string
Alpha will be set as 1 by default
:param: hexString
:returns: color with the given hex string
*/
public convenience init?(hexString: String) {
self.init(hexString: hexString, alpha: 1.0)
}
/**
Create non-autoreleased color with in the given hex string and alpha
:param: hexString
:param: alpha
:returns: color with the given hex string and alpha
*/
public convenience init?(hexString: String, alpha: Float) {
var hex = hexString
// Check for hash and remove the hash
if hex.hasPrefix("#") {
hex = hex.substringFromIndex(advance(hex.startIndex, 1))
}
if let match = hex.rangeOfString("(^[0-9A-Fa-f]{6}$)|(^[0-9A-Fa-f]{3}$)", options: .RegularExpressionSearch) {
// Deal with 3 character Hex strings
if count(hex) == 3 {
var redHex = hex.substringToIndex(advance(hex.startIndex, 1))
var greenHex = hex.substringWithRange(Range<String.Index>(start: advance(hex.startIndex, 1), end: advance(hex.startIndex, 2)))
var blueHex = hex.substringFromIndex(advance(hex.startIndex, 2))
hex = redHex + redHex + greenHex + greenHex + blueHex + blueHex
}
let redHex = hex.substringToIndex(advance(hex.startIndex, 2))
let greenHex = hex.substringWithRange(Range<String.Index>(start: advance(hex.startIndex, 2), end: advance(hex.startIndex, 4)))
let blueHex = hex.substringWithRange(Range<String.Index>(start: advance(hex.startIndex, 4), end: advance(hex.startIndex, 6)))
var redInt: CUnsignedInt = 0
var greenInt: CUnsignedInt = 0
var blueInt: CUnsignedInt = 0
NSScanner(string: redHex).scanHexInt(&redInt)
NSScanner(string: greenHex).scanHexInt(&greenInt)
NSScanner(string: blueHex).scanHexInt(&blueInt)
self.init(red: CGFloat(redInt) / 255.0, green: CGFloat(greenInt) / 255.0, blue: CGFloat(blueInt) / 255.0, alpha: CGFloat(alpha))
}
else {
// Note:
// The swift 1.1 compiler is currently unable to destroy partially initialized classes in all cases,
// so it disallows formation of a situation where it would have to. We consider this a bug to be fixed
// in future releases, not a feature. -- Apple Forum
self.init()
return nil
}
}
/**
Create non-autoreleased color with in the given hex value
Alpha will be set as 1 by default
:param: hex
:returns: color with the given hex value
*/
public convenience init?(hex: Int) {
self.init(hex: hex, alpha: 1.0)
}
/**
Create non-autoreleased color with in the given hex value and alpha
:param: hex
:param: alpha
:returns: color with the given hex value and alpha
*/
public convenience init?(hex: Int, alpha: Float) {
var hexString = NSString(format: "%2X", hex)
self.init(hexString: hexString as String, alpha: alpha)
}
} | mit | a65677fcca0b6d579593325dfd51574c | 36 | 134 | 0.686413 | 4.199408 | false | false | false | false |
creatubbles/ctb-api-swift | CreatubblesAPIClient/Sources/Requests/User/FetchFollowedHashtagsResponseHandler.swift | 1 | 2348 | //
// FetchFollowedHashtagsResponseHandler.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// 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 ObjectMapper
class FetchFollowedHashtagsResponseHandler: ResponseHandler {
fileprivate let completion: HashtagsClosure?
init(completion: HashtagsClosure?) {
self.completion = completion
}
override func handleResponse(_ response: Dictionary<String, AnyObject>?, error: Error?) {
if let response = response,
let hashtagsMapper = Mapper<HashtagMapper>().mapArray(JSONObject: response["data"]) {
let metadata = MappingUtils.metadataFromResponse(response)
let pageInfo = MappingUtils.pagingInfoFromResponse(response)
let dataMapper = MappingUtils.dataIncludeMapperFromResponse(response, metadata: metadata)
let hashtags = hashtagsMapper.map({ Hashtag(mapper: $0, dataMapper: dataMapper, metadata: metadata) })
executeOnMainQueue { self.completion?(hashtags, pageInfo, ErrorTransformer.errorFromResponse(response, error: error)) }
} else {
executeOnMainQueue { self.completion?(nil, nil, ErrorTransformer.errorFromResponse(response, error: error)) }
}
}
}
| mit | bcf7cdd064f30dd6012edc8cee3cdef3 | 46.918367 | 131 | 0.725298 | 4.821355 | false | false | false | false |
Dywane3Peter/YP | YP/Common/Controller/YPTabBarController.swift | 1 | 1843 | //
// YPTabBarController.swift
// YP
//
// Created by peter on 2017/8/3.
// Copyright © 2017年 peter. All rights reserved.
//
import UIKit
class YPTabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
setSubUpTabBarVC();
self.selectedIndex = 1
}
func setSubUpTabBarVC() {
let homeVC = HomeVC.controllerInitWithNib()
let homeNavBarVC = UINavigationController(rootViewController: homeVC)
homeNavBarVC.tabBarItem = UITabBarItem(title: "", image: UIImage(named: "calendar")?.withRenderingMode(.alwaysOriginal), selectedImage: UIImage(named: "calendar_highlight")?.withRenderingMode(.alwaysOriginal))
homeNavBarVC.tabBarItem.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0)
self.addChildViewController(homeNavBarVC)
let runVC = RunVC.controllerInitWithNib()
let runNavBarVC = UINavigationController(rootViewController: runVC)
runNavBarVC.tabBarItem = UITabBarItem(title: "", image: UIImage(named: "run")?.withRenderingMode(.alwaysOriginal), selectedImage: UIImage(named: "run_highlight")?.withRenderingMode(.alwaysOriginal))
runNavBarVC.tabBarItem.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0)
self.addChildViewController(runNavBarVC)
let settingVC = SettingVC.controllerInitWithNib()
let settingNavBarVC = UINavigationController(rootViewController: settingVC)
settingNavBarVC.tabBarItem = UITabBarItem(title: "", image: UIImage(named: "user")?.withRenderingMode(.alwaysOriginal), selectedImage: UIImage(named: "user_highlight")?.withRenderingMode(.alwaysOriginal))
settingNavBarVC.tabBarItem.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0)
self.addChildViewController(settingNavBarVC)
self.hidesBottomBarWhenPushed = true;
}
}
| mit | f24e898921bb4325832d5d214b4fc771 | 46.179487 | 217 | 0.719565 | 4.804178 | false | false | false | false |
codeforgreenville/trolley-tracker-ios-client | TrolleyTracker/Controllers/Model/TrolleyScheduleService.swift | 1 | 2594 | //
// TrolleyScheduleService.swift
// TrolleyTracker
//
// Created by Austin Younts on 10/11/15.
// Copyright © 2015 Code For Greenville. All rights reserved.
//
import Foundation
class TrolleyScheduleService {
private let client: APIClient
init(client: APIClient) {
self.client = client
}
func loadTrolleySchedules(_ completion: @escaping ModelController.LoadScheduleCompletion) {
// check user defaults (should probably go in an operation)
let localSchedulesOperation = LoadLocalSchedulesOperation()
localSchedulesOperation.completionBlock = { [weak localSchedulesOperation] in
guard let schedules = localSchedulesOperation?.loadedSchedules else { return }
DispatchQueue.main.async {
completion(schedules)
}
}
OperationQueue.main.addOperation(localSchedulesOperation)
// load from network
loadSchedulesFromNetwork(completion)
}
private func loadSchedulesFromNetwork(_ completion: @escaping ModelController.LoadScheduleCompletion) {
// Load all Routes so we have names for the RouteSchedules (associated by RouteID)
let routesOperation = LoadRoutesFromNetworkOperation(client: client)
// Load all schedules
let schedulesOperation = LoadSchedulesFromNetworkOperation(client: client)
// Aggregate schedules, assigning names from the Routes we retrieved
let aggregateOperation = AggregateSchedulesOperation()
aggregateOperation.completionBlock = { [weak aggregateOperation] in
guard let routeSchedules = aggregateOperation?.routeSchedules , routeSchedules.count > 0 else { return }
DispatchQueue.main.async {
OperationQueue.main.addOperation(SaveSchedulesOperation(schedules: routeSchedules))
completion(routeSchedules)
}
}
let adapterOp = BlockOperation {
aggregateOperation.routes = routesOperation.routes
aggregateOperation.schedules = schedulesOperation.schedules
}
adapterOp.addDependency(schedulesOperation)
adapterOp.addDependency(routesOperation)
aggregateOperation.addDependency(adapterOp)
OperationQueues.networkQueue.addOperation(routesOperation)
OperationQueues.networkQueue.addOperation(schedulesOperation)
OperationQueues.computationQueue.addOperation(adapterOp)
OperationQueues.computationQueue.addOperation(aggregateOperation)
}
}
| mit | 440089042306b7855f04f6158f7d7752 | 36.57971 | 116 | 0.694948 | 5.612554 | false | false | false | false |
V3ronique/TailBook | TailBook/TailBook/HomeViewController.swift | 1 | 6830 | //
// HomeViewController.swift
// TailBook
//
// Created by Roni Beberoni on 2/4/16.
// Copyright © 2016 Veronica. All rights reserved.
//
import UIKit
import Parse
class HomeViewController: UIViewController {
@IBOutlet weak var logOutBtn: UIButton!
@IBOutlet weak var userPhoto: UIImageView!
@IBOutlet weak var dogSizeLabel: UILabel!
@IBOutlet weak var dogNameLabel: UILabel!
@IBOutlet weak var breedLabel: UILabel!
@IBOutlet weak var ageLabel: UILabel!
@IBOutlet weak var genderLabel: UILabel!
@IBOutlet weak var userNameLabel: UILabel!
let imagePicker: UIImagePickerController! = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
self.logOutBtn.hidden = true
let recognizer: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "swipeLeft:")
recognizer.direction = .Left
self.view .addGestureRecognizer(recognizer)
let doubleTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "handleDoubleTap:")
doubleTap.numberOfTapsRequired = 2
self.view.addGestureRecognizer(doubleTap)
self.navigationController?.navigationBarHidden = true
let holdToSee = UILongPressGestureRecognizer(target: self, action: "longPressAdd:");
holdToSee.minimumPressDuration = 1.00;
self.view.addGestureRecognizer(holdToSee);
if let pUserName = PFUser.currentUser()?["username"] as? String {
let query = PFQuery(className: "Dog")
query.whereKey("UserId", equalTo: (PFUser.currentUser()?.objectId)!)
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if(error == nil) {
var alert = UIAlertView(title: "Error", message: "\(error)", delegate: self, cancelButtonTitle: "OK")
}
//dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
self.userPhoto.image = UIImage(data: NSData(contentsOfURL: NSURL(string:"http://media-cache-ak0.pinimg.com/originals/7e/15/2e/7e152ed74e2c4bbc26eb11556a411e4e.jpg")!)!)
//})
let dog = try! query.getFirstObject()
self.userNameLabel.text = pUserName
self.dogNameLabel.text = dog["Name"] as? String
self.dogSizeLabel.text = dog["Size"] as? String
self.breedLabel.text = dog["Breed"] as? String
self.ageLabel.text = String(dog["Age"]) as? String
if (dog["Gender"] as! Bool){
self.genderLabel.text = "female"
} else {
self.genderLabel.text = "male"
}
}
}
}
func longPressAdd(sender: UILongPressGestureRecognizer) {
let alert: UIAlertController = UIAlertController(title: "Change photo", message: "Do you want to take a new header photo?", preferredStyle: .Alert);
alert.addAction(UIAlertAction(title: "Yes", style: .Default, handler: { (UIAlertAction) -> Void in
if let tv = self.userPhoto {
if (UIImagePickerController.isSourceTypeAvailable(.Camera)) {
if UIImagePickerController.availableCaptureModesForCameraDevice(.Rear) != nil {
self.imagePicker.allowsEditing = false
self.imagePicker.sourceType = .Camera
self.imagePicker.cameraCaptureMode = .Photo
self.presentViewController(self.imagePicker, animated: true, completion: {})
} else {
UIAlertController(title: "Rear camera doesn't exist", message: "Application cannot access the camera.", preferredStyle: .Alert)
}
} else {
UIAlertController(title:"Camera inaccessable", message: "Application cannot access the camera.", preferredStyle: .Alert)
}
}
}));
alert.addAction(UIAlertAction(title: "No", style: .Default, handler: nil));
self.presentViewController(alert, animated: true, completion: nil);
}
override func viewWillAppear(animated: Bool) {
if (PFUser.currentUser() == nil) {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("LoginView")
self.presentViewController(vc, animated: true, completion: nil)
})
}
}
func handleDoubleTap(recognizer:UITapGestureRecognizer) {
if (self.logOutBtn.hidden == false){
self.logOutBtn.hidden = true
} else{
self.logOutBtn.hidden = false
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
print("Got an image")
var image:UIImage!
if let pickedImage:UIImage = (info[UIImagePickerControllerOriginalImage]) as? UIImage {
let selectorToCall = Selector("imageWasSavedSuccessfully:didFinishSavingWithError:context:")
UIImageWriteToSavedPhotosAlbum(pickedImage, self, selectorToCall, nil)
image = pickedImage
}
imagePicker.dismissViewControllerAnimated(true, completion: {
self.userPhoto.image = image
})
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
print("User canceled image")
dismissViewControllerAnimated(true, completion: {
})
}
@IBAction func logOutAction(sender: AnyObject) {
let alert: UIAlertController = UIAlertController(title: "Logout", message: (PFUser.currentUser()!["username"] as? String)! + ", do you really want to logout?", preferredStyle: .Alert);
alert.addAction(UIAlertAction(title: "Yes", style: .Default, handler: { (UIAlertAction) -> Void in
PFUser.logOut()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("LoginView")
self.presentViewController(vc, animated: true, completion: nil)
})
}))
alert.addAction(UIAlertAction(title: "No", style: .Default, handler: nil));
self.presentViewController(alert, animated: true, completion: nil);
}
func swipeLeft(recognizer : UISwipeGestureRecognizer) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("NewsFeed") as! NewsFeedPageContentTableViewController
self.presentViewController(vc, animated: true, completion: nil)
}
}
| mit | b422f3c555131bbc4fb996b744c81abc | 44.526667 | 193 | 0.640797 | 5.054774 | false | false | false | false |
PhillipEnglish/TIY-Assignments | TheGrailDiaryParsed/HistoricalSitesTableViewController.swift | 1 | 6751 | //
// HistoricalSitesTableViewController.swift
// TheGrailDiary
//
// Created by Phillip English on 10/19/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
class HistoricalSitesTableViewController: UITableViewController
{
//This is an arbitrary comment so I can make a second commit
var temples = Array<Temple>()
var isNotToggled = false
var liked = [PFObject]() //PFObject(className: "Liked")
//var isLiked = [PFObject]()
let ankh = UIImage(named: "Ankh")! as UIImage;
let ankhFilled = UIImage(named: "AnkhFilled")! as UIImage;
override func viewDidLoad() {
super.viewDidLoad()
title = "Temples of Ancient Egypt"
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
// override func viewDidAppear(animated: Bool)
// {
// super.viewDidAppear(animated)
// refreshLiked()
// }
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
// #warning Incomplete implementation, return the number of rows
return temples.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("TempleCell", forIndexPath: indexPath) as! TempleCell
// Configure the cell...
let aTemple = temples[indexPath.row]
cell.titleLabel.text = aTemple.name
cell.detailLabel.text = aTemple.deity
return cell
}
/*
// Override to support conditional editing of the table view.
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 to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
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
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// 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.
}
*/
//MARK: - Action Handlers
@IBAction func likeButtonClicked(sender: UIButton)
{
//liked.fetch()
if sender.tag == 0
{
//parseThing()
sender.setImage(ankhFilled, forState: UIControlState.Normal)
sender.tag = 1
//liked
}
else
{
sender.setImage(ankh, forState: UIControlState.Normal)
sender.tag = 0
}
}
func loadTemples()
{
do
{
let filePath = NSBundle.mainBundle().pathForResource("temples", ofType: "json")
let dataFromFile = NSData(contentsOfFile: filePath!)
let templeData: NSArray! = try NSJSONSerialization.JSONObjectWithData(dataFromFile!, options: []) as! NSArray
for templeDictionary in templeData
{
let aTemple = Temple(dictionary: templeDictionary as! NSDictionary)
temples.append(aTemple)
}
temples.sortInPlace({ $0.name < $1.name})
}
catch let error as NSError
{
print(error)
}
}
// override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
// {
// //let aTemple = temples[indexPath.row]
// let NVCfromTemplate = storyboard?.instantiateViewControllerWithIdentifier("TempleDetailViewController") as! TempleDetailViewController
// NVCfromTemplate.temple = temples[indexPath.row]
// presentViewController(NVCfromTemplate, animated: true, completion: nil)
//
//
// }
//MARK: - Parse Experiment
// func parseThing()
// {
// //let liked = PFObject(className: "Liked")
// //liked["num"] = 1
//
// liked.saveInBackgroundWithBlock{
// (success: Bool, error: NSError?) -> Void in
// if success
// {
// print("great")
// }
// else
// {
// print(error?.localizedDescription)
// }
//
// }
//MARK: - Parse Querie
func refreshLiked()
{
if PFUser.currentUser() != nil
{
let query = PFQuery(className: "Liked")
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil
{
self.liked = objects!
self.tableView.reloadData()
}
else
{
print(error?.localizedDescription)
}
}
}
}
}
| cc0-1.0 | 4cab7a7b4f3d126beb5bb40da55706c8 | 29.681818 | 157 | 0.598222 | 5.240683 | false | false | false | false |
webim/webim-client-sdk-ios | WebimClientLibrary/Backend/Items/Responses/LocationStatusResponse.swift | 1 | 2304 | //
// LocationStatusResponse.swift
// WebimClientLibrary
//
// Created by Nikita Kaberov on 10.02.21.
// Copyright © 2021 Webim. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
/**
- author:
Nikita Kaberov
- copyright:
2021 Webim
*/
final class LocationStatusResponse {
// MARK: - Constants
// Raw values equal to field names received in responses from server.
private enum JSONField: String {
case onlineOperators = "onlineOperators"
case onlineStatus = "onlineStatus"
}
// MARK: - Properties
private var onlineOperators: Bool?
private var onlineStatus: String?
// MARK: - Initialization
init(jsonDictionary: [String: Any?]) {
if let onlineOperators = jsonDictionary[JSONField.onlineOperators.rawValue] as? Bool {
self.onlineOperators = onlineOperators
}
if let onlineStatus = jsonDictionary[JSONField.onlineStatus.rawValue] as? String {
self.onlineStatus = onlineStatus
}
}
// MARK: - Methods
func getOnlineOperator() -> Bool? {
return onlineOperators
}
func getOnlineStatus() -> String? {
return onlineStatus
}
}
| mit | 2180d856335c32fb434e0f90981eb006 | 32.376812 | 94 | 0.692575 | 4.480545 | false | false | false | false |
anthonyApptist/Poplur | Poplur/UIExtensions.swift | 1 | 2235 | //
// CustomLabels.swift
// Poplur
//
// Created by Mark Meritt on 2016-11-13.
// Copyright © 2016 Apptist. All rights reserved.
//
import UIKit
extension UILabel {
func setSpacing(space: CGFloat) {
let attributedString = NSMutableAttributedString(string: (self.text!))
attributedString.addAttribute(NSKernAttributeName, value: space, range: NSMakeRange(0, attributedString.length))
self.attributedText = attributedString
}
}
extension UIButton {
func setSpacing(space: CGFloat) {
let attributedString = NSMutableAttributedString(string: (self.titleLabel?.text!)!)
attributedString.addAttribute(NSKernAttributeName, value: space, range: NSMakeRange(0, attributedString.length))
self.titleLabel?.attributedText = attributedString
}
}
extension UITextField {
func addBorder() {
self.layer.borderColor = UIColor.black.cgColor
self.layer.borderWidth = 2.4
}
}
extension UIView {
func pinToTop(view: UIView, margin: CGFloat) -> NSLayoutConstraint {
let topViewConstraint = NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: view, attribute: .topMargin, multiplier: 1, constant: margin)
return topViewConstraint
}
func pinToLeft(view: UIView, margin: CGFloat) -> NSLayoutConstraint {
let leftViewConstraint = NSLayoutConstraint(item: self, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leadingMargin, multiplier: 1, constant: margin)
return leftViewConstraint
}
func pinToRight(view: UIView, margin: CGFloat) -> NSLayoutConstraint {
let rightViewConstraint = NSLayoutConstraint(item: self, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailingMargin, multiplier: 1, constant: margin)
return rightViewConstraint
}
func pinToBottom(view: UIView, margin: CGFloat) -> NSLayoutConstraint {
let bottomViewConstraint = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottomMargin, multiplier: 1.0, constant: margin)
return bottomViewConstraint
}
}
| apache-2.0 | 512c877aad98d665e215c87623f24d84 | 34.460317 | 180 | 0.688004 | 4.877729 | false | false | false | false |
josve05a/wikipedia-ios | Wikipedia/Code/WMFWelcomePageViewController.swift | 2 | 10434 | import Foundation
import UIKit
enum WMFWelcomePageType {
case intro
case exploration
case languages
case analytics
}
public protocol WMFWelcomeNavigationDelegate: class{
func showNextWelcomePage(_ sender: AnyObject)
}
class WMFWelcomePageViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate, WMFWelcomeNavigationDelegate, Themeable {
private var theme = Theme.standard
func apply(theme: Theme) {
self.theme = theme
guard viewIfLoaded != nil else {
return
}
nextButton.setTitleColor(theme.colors.link, for: .normal)
nextButton.setTitleColor(theme.colors.disabledText, for: .disabled)
nextButton.setTitleColor(theme.colors.link, for: .highlighted)
themeToPageControl()
skipButton.setTitleColor(theme.colors.unselected, for: .normal)
for child in pageControllers {
guard let themeable = child as? Themeable else {
continue
}
themeable.apply(theme: theme)
}
}
private func themeToPageControl() {
guard
viewIfLoaded != nil,
view.window != nil
else {
return
}
pageControl?.pageIndicatorTintColor = theme.colors.pageIndicator
pageControl?.currentPageIndicatorTintColor = theme.colors.pageIndicatorCurrent
}
@objc var completionBlock: (() -> Void)?
func showNextWelcomePage(_ sender: AnyObject){
guard let sender = sender as? UIViewController, let index = pageControllers.firstIndex(of: sender), index != pageControllers.count - 1 else {
dismiss(animated: true, completion:completionBlock)
return
}
view.isUserInteractionEnabled = false
let nextIndex = index + 1
let direction:UIPageViewController.NavigationDirection = UIApplication.shared.wmf_isRTL ? .reverse : .forward
let nextVC = pageControllers[nextIndex]
hideButtons(for: nextVC)
setViewControllers([nextVC], direction: direction, animated: true, completion: {(Bool) in
self.view.isUserInteractionEnabled = true
})
}
/*
func showPreviousWelcomePage(_ sender: AnyObject){
guard let sender = sender as? UIViewController, let index = pageControllers.index(of: sender), index > 0 else {
return
}
view.isUserInteractionEnabled = false
let prevIndex = index - 1
let direction:UIPageViewControllerNavigationDirection = UIApplication.shared.wmf_isRTL ? .forward : .reverse
setViewControllers([pageControllers[prevIndex]], direction: direction, animated: true, completion: {(Bool) in
self.view.isUserInteractionEnabled = true
})
}
*/
private func containerControllerForWelcomePageType(_ type: WMFWelcomePageType) -> WMFWelcomeContainerViewController {
let controller = WMFWelcomeContainerViewController.wmf_viewControllerFromWelcomeStoryboard()
controller.welcomeNavigationDelegate = self
controller.welcomePageType = type
controller.apply(theme: theme)
return controller
}
private lazy var pageControllers: [UIViewController] = {
var controllers:[UIViewController] = []
controllers.append(containerControllerForWelcomePageType(.intro))
controllers.append(containerControllerForWelcomePageType(.exploration))
controllers.append(containerControllerForWelcomePageType(.languages))
controllers.append(containerControllerForWelcomePageType(.analytics))
return controllers
}()
private lazy var pageControl: UIPageControl? = {
return view.wmf_firstSubviewOfType(UIPageControl.self)
}()
let nextButton = UIButton()
let skipButton = UIButton()
let buttonHeight: CGFloat = 40.0
let buttonSidePadding: CGFloat = 10.0
let buttonCenterXOffset: CGFloat = 88.0
override func viewDidLoad() {
super.viewDidLoad()
dataSource = self
delegate = self
let direction:UIPageViewController.NavigationDirection = UIApplication.shared.wmf_isRTL ? .forward : .reverse
setViewControllers([pageControllers.first!], direction: direction, animated: true, completion: nil)
configureAndAddNextButton()
configureAndAddSkipButton()
if let scrollView = view.wmf_firstSubviewOfType(UIScrollView.self) {
scrollView.clipsToBounds = false
}
updateFonts()
apply(theme: theme)
}
private func configureAndAddNextButton(){
nextButton.translatesAutoresizingMaskIntoConstraints = false
nextButton.addTarget(self, action: #selector(nextButtonTapped), for: .touchUpInside)
nextButton.isUserInteractionEnabled = true
nextButton.setContentCompressionResistancePriority(.required, for: .horizontal)
nextButton.titleLabel?.numberOfLines = 1
nextButton.setTitle(CommonStrings.nextTitle, for: .normal)
view.addSubview(nextButton)
nextButton.heightAnchor.constraint(equalToConstant: buttonHeight).isActive = true
view.addConstraint(NSLayoutConstraint(item: nextButton, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0))
let leading = NSLayoutConstraint(item: nextButton, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: buttonCenterXOffset)
leading.priority = .defaultHigh
let trailing = NSLayoutConstraint(item: nextButton, attribute: .trailing, relatedBy: .lessThanOrEqual, toItem: view, attribute: .trailing, multiplier: 1, constant: buttonSidePadding)
trailing.priority = .required
view.addConstraints([leading, trailing])
}
private func configureAndAddSkipButton(){
skipButton.translatesAutoresizingMaskIntoConstraints = false
skipButton.addTarget(self, action: #selector(skipButtonTapped), for: .touchUpInside)
skipButton.isUserInteractionEnabled = true
skipButton.setContentCompressionResistancePriority(.required, for: .horizontal)
skipButton.titleLabel?.numberOfLines = 1
skipButton.setTitle(CommonStrings.skipTitle, for: .normal)
view.addSubview(skipButton)
skipButton.heightAnchor.constraint(equalToConstant: buttonHeight).isActive = true
view.addConstraint(NSLayoutConstraint(item: skipButton, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0))
let leading = NSLayoutConstraint(item: skipButton, attribute: .leading, relatedBy: .greaterThanOrEqual, toItem: view, attribute: .leading, multiplier: 1, constant: buttonSidePadding)
leading.priority = .required
let trailing = NSLayoutConstraint(item: skipButton, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: -buttonCenterXOffset)
trailing.priority = .defaultHigh
view.addConstraints([leading, trailing])
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
updateFonts()
}
private func updateFonts() {
skipButton.titleLabel?.font = UIFont.wmf_font(.semiboldFootnote, compatibleWithTraitCollection: traitCollection)
nextButton.titleLabel?.font = UIFont.wmf_font(.semiboldFootnote, compatibleWithTraitCollection: traitCollection)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let pageControl = pageControl {
pageControl.isUserInteractionEnabled = false
themeToPageControl()
}
}
@objc func nextButtonTapped(_ sender: UIButton) {
if let currentVC = viewControllers?.first {
showNextWelcomePage(currentVC)
}
}
@objc func skipButtonTapped(_ sender: UIButton) {
/*
if let currentVC = viewControllers?.first {
showPreviousWelcomePage(currentVC)
}
*/
dismiss(animated: true, completion:completionBlock)
}
func presentationCount(for pageViewController: UIPageViewController) -> Int {
return pageControllers.count
}
func presentationIndex(for pageViewController: UIPageViewController) -> Int {
guard let viewControllers = viewControllers, let currentVC = viewControllers.first, let presentationIndex = pageControllers.firstIndex(of: currentVC) else {
return 0
}
return presentationIndex
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let index = pageControllers.firstIndex(of: viewController) else {
return nil
}
return index >= pageControllers.count - 1 ? nil : pageControllers[index + 1]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let index = pageControllers.firstIndex(of: viewController) else {
return nil
}
return index == 0 ? nil : pageControllers[index - 1]
}
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool){
if completed {
hideButtons(for: pageControllers[presentationIndex(for: pageViewController)])
}
}
func hideButtons(for vc: UIViewController){
let isLastPage = pageControllers.firstIndex(of: vc) == pageControllers.count - 1
let newAlpha:CGFloat = isLastPage ? 0.0 : 1.0
let alphaChanged = pageControl?.alpha != newAlpha
nextButton.isEnabled = !isLastPage // Gray out the next button when transitioning to last page (per design)
guard alphaChanged else { return }
UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveLinear, animations: {
self.nextButton.alpha = newAlpha
self.skipButton.alpha = newAlpha
self.pageControl?.alpha = newAlpha
}, completion: nil)
}
}
| mit | 3597885f8ef263923716e4204aa60113 | 43.025316 | 190 | 0.691489 | 5.606663 | false | false | false | false |
ephread/Instructions | Examples/Example/Sources/Core/Custom Views/TransparentCoachMarkBodyView.swift | 1 | 1438 | // Copyright (c) 2015-present Frédéric Maquin <[email protected]> and contributors.
// Licensed under the terms of the MIT License.
import UIKit
import Instructions
// Transparent coach mark (text without background, cool arrow)
internal class TransparentCoachMarkBodyView: UIControl, CoachMarkBodyView {
// MARK: - Internal properties
var nextControl: UIControl? { return self }
weak var highlightArrowDelegate: CoachMarkBodyHighlightArrowDelegate?
var hintLabel = UITextView()
// MARK: - Initialization
override init (frame: CGRect) {
super.init(frame: frame)
self.setupInnerViewHierarchy()
}
convenience init() {
self.init(frame: CGRect.zero)
}
required init?(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding.")
}
// MARK: - Private methods
private func setupInnerViewHierarchy() {
self.translatesAutoresizingMaskIntoConstraints = false
hintLabel.backgroundColor = UIColor.clear
hintLabel.textColor = UIColor.white
hintLabel.font = UIFont.systemFont(ofSize: 15.0)
hintLabel.isScrollEnabled = false
hintLabel.textAlignment = .left
hintLabel.isEditable = false
hintLabel.translatesAutoresizingMaskIntoConstraints = false
hintLabel.isUserInteractionEnabled = false
self.addSubview(hintLabel)
hintLabel.fillSuperview()
}
}
| mit | 9eb60e23c16fe7bc8f703c1df30b62c3 | 28.916667 | 82 | 0.70195 | 5.240876 | false | false | false | false |
rgravina/tddtris | TddTetrisTests/Components/Game/DefaultCollisionDetectorTest.swift | 1 | 1947 | import XCTest
import Nimble
@testable import TddTetris
class DefaultCollisionDetectorTest: XCTestCase {
func test_willCollide_returnsTrueWhenTetrominoReachesBottom() {
let tetromino = STetromino(
position: (0, 18),
blocks: [
(column: 0, row: 1),
(column: 1, row: 0),
(column: 1, row: 1),
(column: 2, row: 0)
]
)
let gameState = GameState()
gameState.tetromino = tetromino
let detector = DefaultCollisionDetector(state: gameState)
let result = detector.wouldCollide(.down)
expect(result).to(beTrue())
}
func test_willCollide_returnsTrueWhenTetrominoIsObstructedDirectlyBelow() {
let tetromino = STetromino(
position: (0, 0),
blocks: [
(column: 0, row: 1),
(column: 1, row: 0),
(column: 1, row: 1),
(column: 2, row: 0)
]
)
let gameState = GameState()
gameState.tetromino = tetromino
gameState.occupy(position: Position(column: 0, row: 2))
let detector = DefaultCollisionDetector(state: gameState)
let result = detector.wouldCollide(.down)
expect(result).to(beTrue())
}
func test_willCollide_returnsTrueWhenTetrominoIsObstructedDirectlyLeft() {
let tetromino = STetromino(
position: (1, 0),
blocks: [
(column: 0, row: 1),
(column: 1, row: 1),
(column: 1, row: 0),
(column: 2, row: 0)
]
)
let gameState = GameState()
gameState.tetromino = tetromino
gameState.occupy(position: Position(column: 0, row: 1))
let detector = DefaultCollisionDetector(state: gameState)
let result = detector.wouldCollide(.left)
expect(result).to(beTrue())
}
}
| mit | f2e7df76117ad90a5591ff836e92628f | 30.918033 | 79 | 0.545455 | 4.425 | false | true | false | false |
kongtomorrow/ProjectEuler-Swift | ProjectEuler/p25.swift | 1 | 1453 | //
// p25.swift
// ProjectEuler
//
// Created by Ken Ferry on 8/10/14.
// Copyright (c) 2014 Understudy. All rights reserved.
//
import Foundation
extension Problems {
func p25() -> Int {
/*
1000-digit Fibonacci number
Problem 25
Published on 30 August 2002 at 06:00 pm [Server Time]
The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:
F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is the first term to contain three digits.
What is the first term in the Fibonacci sequence to contain 1000 digits?
*/
//Fn is the integer closest to gr^n / sqrt(5)
// log_10(gr^n / sqrt(5)) = nlog_10(gr)-log_10(sqrt(5))
// = nlog10(1+sqrt(5)/2) -log_10(sqrt(5))
// = nlog10(1+sqrt(5)) - nlog10(2) - log10(sqrt(5)
let desiredDigits = 1000
let goldenRatio = (1.0 + sqrt(5)) / 2
func digitsOfFib(n:Int) -> Int {
let digitsDoub = Double(n) * log10(goldenRatio) - log10(sqrt(5)) + 1
return Int(digitsDoub)
}
return ints.map(digitsOfFib).takeWhile({$0 < desiredDigits})!.count() + 1
}
} | mit | ee198afe97c1817de7aba8c7071a21b5 | 26.884615 | 81 | 0.518979 | 3.425532 | false | false | false | false |
WildDogTeam/demo-ios-officemover | OfficeMover5000/Constants.swift | 1 | 2190 | //
// Constants.swift
// OfficeMover500
//
// Created by Garin on 11/2/15.
// Copyright (c) 2015 Wilddog. All rights reserved.
//
import UIKit
let RoomWidth = 600
let RoomHeight = 800
let ThresholdMoved = CGFloat(10)
let BorderBlue = UIColor(red: CGFloat(214.0/255.0), green: CGFloat(235.0/255.0), blue: CGFloat(249.0/255.0), alpha: 1.0)
let TopbarBlue = UIColor(red: CGFloat(22.0/255.0), green: CGFloat(148.0/255.0), blue: CGFloat(223.0/255.0), alpha: 1.0)
let LoginBlue = UIColor(red: CGFloat(13.0/255.0), green: CGFloat(124.0/255.0), blue: CGFloat(189.0/255.0), alpha: 1.0)
let FontBlue = UIColor(red: CGFloat(9.0/255.0), green: CGFloat(144.0/255.0), blue: CGFloat(201.0/255.0), alpha: 1.0)
let ErrorBodyRed = UIColor(red: CGFloat(254.0/255.0), green: CGFloat(243.0/255.0), blue: CGFloat(242.0/255.0), alpha: 1.0)
let ErrorBorderRed = UIColor(red: CGFloat(249.0/255.0), green: CGFloat(208.0/255.0), blue: CGFloat(201.0/255.0), alpha: 1.0)
let UnselectedGrey = UIColor(red: CGFloat(148.0/255.0), green: CGFloat(165.0/255.0), blue: CGFloat(166.0/255.0), alpha: 1.0)
let SelectedGrey = UIColor(red: CGFloat(51.0/255.0), green: CGFloat(72.0/255.0), blue: CGFloat(95.0/255.0), alpha: 1.0)
let SynergyBlue = UIColor(red: CGFloat(40.0/255.0), green: CGFloat(165.0/255.0), blue: CGFloat(166.0/255.0), alpha: 1.0)
let ProximaNovaLight20 = UIFont(name: "ProximaNova-Light", size: 20)!
// Each icon on the add menu should have one of these. The second value is the name of the asset
let Items = [
("Android Toy", "android", "android"),
("Ball Pit Pool", "ballpit", "ballpit"),
("Office Desk", "desk", "desk"),
("Dog (Corgi)", "dog", "dog_corgi"),
("Dog (Retriever)", "dog", "dog_retriever"),
("Laptop", "computer", "laptop"),
("Nerfgun Pistol", "nerf", "nerfgun"),
("Pacman Arcade", "game", "pacman"),
("Ping Pong Table", "pingpong", "pingpong"),
("Plant (Shrub)", "plant", "plant1"),
("Plant (Succulent)", "plant", "plant2"),
("Red Stapler", "stapler", "redstapler")
]
let Floors = [
("Casino Carpet", "carpet"),
("Grid Pattern", "grid"),
("Tile Flooring", "tile"),
("Hardwood Floor", "wood"),
("No Background", "")
] | mit | 319bb24f5aa0c7db56720a2a616b3232 | 41.960784 | 124 | 0.646119 | 2.723881 | false | false | false | false |
WalterCreazyBear/Swifter30 | iMessageDemo/iMessageExtension/BGMessagesViewController.swift | 1 | 3662 | //
// MessagesViewController.swift
// iMessageExtension
//
// Created by Bear on 2017/8/3.
// Copyright © 2017年 Bear. All rights reserved.
//
import UIKit
import Messages
class BGMessagesViewController: MSMessagesAppViewController {
var nav : UINavigationController!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
let rootVC = BGRootViewController()
let nav = UINavigationController()
nav.pushViewController(rootVC, animated: false)
self.addChildViewController(nav)
self.view.addSubview(nav.view)
let imessageUserDefault = UserDefaults.init(suiteName: "group.imessage.bear")
print("\(String(describing: imessageUserDefault?.value(forKey: "name")))")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
BGConversationManager.shared.appDeleagte = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Conversation Handling
override func willBecomeActive(with conversation: MSConversation) {
// Called when the extension is about to move from the inactive to active state.
// This will happen when the extension is about to present UI.
// Use this method to configure the extension and restore previously stored state.
}
override func didResignActive(with conversation: MSConversation) {
// Called when the extension is about to move from the active to inactive state.
// This will happen when the user dissmises the extension, changes to a different
// conversation or quits Messages.
// Use this method to release shared resources, save user data, invalidate timers,
// and store enough state information to restore your extension to its current state
// in case it is terminated later.
}
override func didReceive(_ message: MSMessage, conversation: MSConversation) {
// Called when a message arrives that was generated by another instance of this
// extension on a remote device.
// Use this method to trigger UI updates in response to the message.
}
override func didStartSending(_ message: MSMessage, conversation: MSConversation) {
// Called when the user taps the send button.
}
override func didCancelSending(_ message: MSMessage, conversation: MSConversation) {
// Called when the user deletes the message without sending it.
// Use this to clean up state related to the deleted message.
}
override func willTransition(to presentationStyle: MSMessagesAppPresentationStyle) {
// Called before the extension transitions to a new presentation style.
// Use this method to prepare for the change in presentation style.
}
override func didTransition(to presentationStyle: MSMessagesAppPresentationStyle) {
// Called after the extension transitions to a new presentation style.
// Use this method to finalize any behaviors associated with the change in presentation style.
if(presentationStyle == .compact)
{
NotificationCenter.default.post(name: NSNotification.Name.init("MSMessagesAppPresentationStyleCompact"), object: nil)
}
else
{
NotificationCenter.default.post(name: NSNotification.Name.init("MSMessagesAppPresentationStyleExpanded"), object: nil)
}
}
}
| mit | 9bd96ffd6fe6f5cd22d44ecdab15bb17 | 37.114583 | 130 | 0.681334 | 5.477545 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/Services/UsersService.swift | 2 | 1844 | import Foundation
import WordPressKit
/// UserService is responsible for interacting with UserServiceRemoteXMLRPC to fetch User and Profile related details
/// from self-hosted blogs. See the PeopleService for WordPress.com blogs via the REST API.
///
open class UsersService {
/// XMLRPC API associated to the Endpoint.
///
let api: WordPressOrgXMLRPCApi
/// Endpoint's Username.
///
let username: String
/// Endpoint's Password.
///
let password: String
/// Designated Initializer.
///
init?(username: String, password: String, xmlrpc: String) {
guard let endpoint = URL(string: xmlrpc) else {
return nil
}
self.api = WordPressOrgXMLRPCApi(endpoint: endpoint)
self.username = username
self.password = password
}
/// Fetch profile information for the user of the specified blog.
///
func fetchProfile(onCompletion: @escaping ((UserProfile?) -> Void)) {
let remote = UsersServiceRemoteXMLRPC(api: api, username: username, password: password)
remote.fetchProfile({ remoteProfile in
var profile = UserProfile()
profile.bio = remoteProfile.bio
profile.displayName = remoteProfile.displayName
profile.email = remoteProfile.email
profile.firstName = remoteProfile.firstName
profile.lastName = remoteProfile.lastName
profile.nicename = remoteProfile.nicename
profile.nickname = remoteProfile.nickname
profile.url = remoteProfile.url
profile.userID = remoteProfile.userID
profile.username = remoteProfile.username
onCompletion(profile)
}, failure: { error in
DDLogError(error.debugDescription)
onCompletion(nil)
})
}
}
| gpl-2.0 | d342c8883328205d57fdbcd2e6cd05d3 | 29.733333 | 117 | 0.645336 | 5.093923 | false | false | false | false |
modocache/Gift | Gift/Repository/Repository+Branch.swift | 1 | 2979 | import ReactiveCocoa
import LlamaKit
public extension Repository {
/**
Enumerates references that refer to branches in a repository.
As the references are enumerated, their values are sent via a signal.
:param: type The type of branch to include in the enumeration.
:returns: A signal that will notify subscribers of branches as they are
enumerated. Dispose of the signal in order to discontinue
the enueration.
*/
public func branches(type: BranchType = .Local) -> SignalProducer<Reference, NSError> {
return SignalProducer { (observer, disposable) in
// Create a branch iterator. If this fails, notify the subscriber
// of an error and exit early.
var out = COpaquePointer.null()
let errorCode = git_branch_iterator_new(&out, self.cRepository, git_branch_t(type.rawValue))
if errorCode == GIT_OK.value {
let iterator = BranchIterator(cBranchIterator: out)
// Iterate over each branch reference.
var next = iterator.next()
while next.errorCode == GIT_OK.value {
// For each reference, check if the signal has been disposed of.
// If so, cancel early.
if disposable.disposed {
return
}
// Otherwise, continue sending the subscriber references.
sendNext(observer, Reference(cReference: next.cReference))
next = iterator.next()
}
// Iteration completion means one of two things:
if next.errorCode == GIT_ITEROVER.value {
// 1. There are no branch references to iterate over, i.e.: GIT_ITEROVER.
// If that's the case, notify the subsciber that the signal has completed.
sendCompleted(observer)
} else {
// 2. An error occurred while iterating. If that's the case, notify the
// subscriber of the error.
sendError(observer, NSError.libGit2Error(next.errorCode, libGit2PointOfFailure: iterator.pointOfFailure))
}
} else {
sendError(observer, NSError.libGit2Error(errorCode, libGit2PointOfFailure: "git_branch_iterator_new"))
}
}
}
/**
Looks up a branch by a given name.
:param: name The name of the branch to look up.
:param: branchType A classier specifying whether to include results from
local branches, remote branches, or both.
:returns: The result of the lookup: either a reference to a
branch or an error indicating what went wrong.
*/
public func lookupBranch(name: String, branchType: BranchType = .Local) -> Result<Reference, NSError> {
var out = COpaquePointer.null()
let errorCode = git_branch_lookup(&out, cRepository, name, git_branch_t(branchType.rawValue))
if errorCode == GIT_OK.value {
return success(Reference(cReference: out))
} else {
return failure(NSError.libGit2Error(errorCode, libGit2PointOfFailure: "git_branch_lookup"))
}
}
}
| mit | dc737b2504c41d053985d65a496f543d | 41.557143 | 115 | 0.658946 | 4.493213 | false | false | false | false |
dhardiman/MVVMTools | Tests/MVVMTests/ViewBindingTests.swift | 1 | 1222 | //
// ViewBindingTests.swift
// MVVMTests
//
// Created by Dave Hardiman on 10/04/2016.
// Copyright © 2016 David Hardiman. All rights reserved.
//
import XCTest
import ReactiveKit
import Nimble
@testable import MVVM
class TestViewModel: ViewModel {
internal var model: String? {
didSet {
observableString.value = model ?? ""
}
}
let observableString = Property("")
}
class TestView: UIView, View {
let viewModel: TestViewModel = TestViewModel()
}
class ViewBindingTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testItIsPossibleToBindAValueToALabel() {
let testView = TestView()
let label = UILabel()
testView.addSubview(label)
testView.bind(testView.viewModel.observableString, toLabel: label)
testView.updateViewModel("test string")
expect(label.text).to(equal("test string"))
}
}
| mit | b55a3400af3a7e7b7bb86d63766e7276 | 24.4375 | 111 | 0.656839 | 4.392086 | false | true | false | false |
alvinvarghese/DeLorean | DeLorean/Result.swift | 1 | 4581 | //
// Result.swift
// swiftz
//
// Created by Maxwell Swadling on 9/06/2014.
// Copyright (c) 2014 Maxwell Swadling. All rights reserved.
//
import class Foundation.NSError
import typealias Foundation.NSErrorPointer
public enum Result<V> {
case Error(NSError)
case Value(Box<V>)
public init(_ e: NSError?, _ v: V) {
if let ex = e {
self = Result.Error(ex)
} else {
self = Result.Value(Box(v))
}
}
public init(_ e:NSError){
self = Result.Error(e)
}
public init(_ v:V){
self = Result.Value(Box(v))
}
/// Much like the ?? operator for Optional types, takes a value and a function,
/// and if the Result is Error, returns the error, otherwise maps the function over
/// the value in Value and returns that value.
public func fold<B>(value: B, f: V -> B) -> B {
switch self {
case Error(_):
return value
case let Value(v):
return f(v.value)
}
}
/// Named function for `>>-`. If the Result is Error, simply returns
/// a New Error with the value of the receiver. If Value, applies the function `f`
/// and returns the result.
public func flatMap<S>(f: V -> Result<S>) -> Result<S> {
return self >>- f
}
/// Creates an Error with the given value.
public static func error(e: NSError) -> Result<V> {
return .Error(e)
}
/// Creates a Value with the given value.
public static func value(v: V) -> Result<V> {
return .Value(Box(v))
}
/// Returns a boolean indicating if the Value has succeed
public var isSuccess: Bool {
get {
switch self {
case .Value(_):
return true
case .Error(_):
return false
}
}
}
/// Returns the current boxed Value
public var value: V? {
get {
switch self {
case .Value(let boxedValue):
return boxedValue.value
default:
return nil
}
}
}
/// Returns a boolean indicating if the Result has failed
public var isFailure: Bool {
get {
return !self.isSuccess
}
}
/// Returns the error
public var error: NSError? {
get {
switch self {
case .Error(let error):
return error
default:
return nil
}
}
}
}
/// MARK: Equatable
public func == <V: Equatable>(lhs: Result<V>, rhs: Result<V>) -> Bool {
switch (lhs, rhs) {
case let (.Error(l), .Error(r)) where l == r:
return true
case let (.Value(l), .Value(r)) where l.value == r.value:
return true
default:
return false
}
}
public func != <V: Equatable>(lhs: Result<V>, rhs: Result<V>) -> Bool {
return !(lhs == rhs)
}
/// MARK: Functor, Applicative, Monad
/// Applicative `pure` function, lifts a value into a Value.
public func pure<V>(a: V) -> Result<V> {
return .Value(Box(a))
}
/// Functor `fmap`. If the Result is Error, ignores the function and returns the Error.
/// If the Result is Value, applies the function to the Right value and returns the result
/// in a new Value.
public func <^> <VA, VB>(f: VA -> VB, a: Result<VA>) -> Result<VB> {
switch a {
case let .Error(l):
return .Error(l)
case let .Value(r):
return Result.Value(Box(f(r.value)))
}
}
/// Applicative Functor `apply`. Given an Result<VA -> VB> and an Result<VA>,
/// returns a Result<VB>. If the `f` or `a' param is an Error, simply returns an Error with the
/// same value. Otherwise the function taken from Value(f) is applied to the value from Value(a)
/// And a Value is returned.
public func <*> <VA, VB>(f: Result<VA -> VB>, a: Result<VA>) -> Result<VB> {
switch (a, f) {
case let (.Error(l), _):
return .Error(l)
case let (.Value(r), .Error(m)):
return .Error(m)
case let (.Value(r), .Value(g)):
return Result<VB>.Value(Box(g.value(r.value)))
}
}
/// Monadic `bind`. Given an Result<VA>, and a function from VA -> Result<VB>,
/// applies the function `f` if `a` is Value, otherwise the function is ignored and an Error
/// with the Error value from `a` is returned.
public func >>- <VA, VB>(a: Result<VA>, f: VA -> Result<VB>) -> Result<VB> {
switch a {
case let .Error(l):
return .Error(l)
case let .Value(r):
return f(r.value)
}
}
| mit | 29c694126f8740bd1cc6271d83c913fb | 27.277778 | 96 | 0.552281 | 3.823873 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.