repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 202
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cabarique/TheProposalGame
|
MyProposalGame/Libraries/SKUtils/SKAction+Extensions.swift
|
1
|
3281
|
/*
* Copyright (c) 2013-2014 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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 SpriteKit
import AVFoundation
public extension SKAction {
/**
* Performs an action after the specified delay.
*/
public class func afterDelay(delay: NSTimeInterval, performAction action: SKAction) -> SKAction {
return SKAction.sequence([SKAction.waitForDuration(delay), action])
}
/**
* Performs a block after the specified delay.
*/
public class func afterDelay(delay: NSTimeInterval, runBlock block: dispatch_block_t) -> SKAction {
return SKAction.afterDelay(delay, performAction: SKAction.runBlock(block))
}
/**
* Removes the node from its parent after the specified delay.
*/
public class func removeFromParentAfterDelay(delay: NSTimeInterval) -> SKAction {
return SKAction.afterDelay(delay, performAction: SKAction.removeFromParent())
}
/**
* Creates an action to perform a parabolic jump.
*/
public class func jumpToHeight(height: CGFloat, duration: NSTimeInterval, originalPosition: CGPoint) -> SKAction {
return SKAction.customActionWithDuration(duration) {(node, elapsedTime) in
let fraction = elapsedTime / CGFloat(duration)
let yOffset = height * 4 * fraction * (1 - fraction)
node.position = CGPoint(x: originalPosition.x, y: originalPosition.y + yOffset)
}
}
public class func playSoundFileNamed(fileName: String, atVolume: Float, waitForCompletion: Bool, withExtension fileExtension: String = ".wav") -> SKAction {
let soundPath = NSBundle.mainBundle().URLForResource(fileName, withExtension: fileExtension)
let player: AVAudioPlayer = try! AVAudioPlayer(contentsOfURL: soundPath!)
player.volume = atVolume
let playAction: SKAction = SKAction.runBlock { () -> Void in
player.play()
}
if(waitForCompletion){
let waitAction = SKAction.waitForDuration(player.duration)
let groupAction: SKAction = SKAction.group([playAction, waitAction])
return groupAction
}
return playAction
}
}
|
mit
|
577c22b16f256de6ec3bf4d2a08454c5
| 40.531646 | 160 | 0.690034 | 5.063272 | false | false | false | false |
tardieu/swift
|
test/IRGen/abitypes.swift
|
1
|
40897
|
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -Xllvm -new-mangling-for-tests -I %S/Inputs/abi %s -emit-ir | %FileCheck -check-prefix=%target-cpu-%target-os %s
// FIXME: rdar://problem/19648117 Needs splitting objc parts out
// XFAIL: linux
import gadget
import Foundation
@objc protocol P1 {}
@objc protocol P2 {}
@objc protocol Work {
func doStuff(_ x: Int64)
}
// armv7s-ios: [[ARMV7S_MYRECT:%.*]] = type { float, float, float, float }
// arm64-ios: [[ARM64_MYRECT:%.*]] = type { float, float, float, float }
// arm64-tvos: [[ARM64_MYRECT:%.*]] = type { float, float, float, float }
// armv7k-watchos: [[ARMV7K_MYRECT:%.*]] = type { float, float, float, float }
class Foo {
// x86_64-macosx: define hidden void @_T08abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F(%VSC6MyRect* noalias nocapture sret, %C8abitypes3Foo*) {{.*}} {
// x86_64-macosx: define hidden { <2 x float>, <2 x float> } @_T08abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo(i8*, i8*) unnamed_addr {{.*}} {
// x86_64-ios: define hidden void @_T08abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F(%VSC6MyRect* noalias nocapture sret, %C8abitypes3Foo*) {{.*}} {
// x86_64-ios: define hidden { <2 x float>, <2 x float> } @_T08abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo(i8*, i8*) unnamed_addr {{.*}} {
// i386-ios: define hidden void @_T08abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F(%VSC6MyRect* noalias nocapture sret, %C8abitypes3Foo*) {{.*}} {
// i386-ios: define hidden void @_T08abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo(%VSC6MyRect* noalias nocapture sret, i8*, i8*) unnamed_addr {{.*}} {
// armv7-ios: define hidden void @_T08abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F(%VSC6MyRect* noalias nocapture sret, %C8abitypes3Foo*) {{.*}} {
// armv7-ios: define hidden void @_T08abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo(%VSC6MyRect* noalias nocapture sret, i8*, i8*) unnamed_addr {{.*}} {
// armv7s-ios: define hidden void @_T08abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F(%VSC6MyRect* noalias nocapture sret, %C8abitypes3Foo*) {{.*}} {
// armv7s-ios: define hidden void @_T08abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo(%VSC6MyRect* noalias nocapture sret, i8*, i8*) unnamed_addr {{.*}} {
// arm64-ios: define hidden void @_T08abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F(%VSC6MyRect* noalias nocapture sret, %C8abitypes3Foo*) {{.*}} {
// arm64-ios: define hidden [[ARM64_MYRECT]] @_T08abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo(i8*, i8*) unnamed_addr {{.*}} {
// x86_64-tvos: define hidden void @_T08abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F(%VSC6MyRect* noalias nocapture sret, %C8abitypes3Foo*) {{.*}} {
// x86_64-tvos: define hidden { <2 x float>, <2 x float> } @_T08abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo(i8*, i8*) unnamed_addr {{.*}} {
// arm64-tvos: define hidden void @_T08abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F(%VSC6MyRect* noalias nocapture sret, %C8abitypes3Foo*) {{.*}} {
// arm64-tvos: define hidden [[ARM64_MYRECT]] @_T08abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo(i8*, i8*) unnamed_addr {{.*}} {
// i386-watchos: define hidden void @_T08abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F(%VSC6MyRect* noalias nocapture sret, %C8abitypes3Foo*) {{.*}} {
// i386-watchos: define hidden void @_T08abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo(%VSC6MyRect* noalias nocapture sret, i8*, i8*) unnamed_addr {{.*}} {
// armv7k-watchos: define hidden void @_T08abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F(%VSC6MyRect* noalias nocapture sret, %C8abitypes3Foo*) {{.*}} {
// armv7k-watchos: define hidden [[ARMV7K_MYRECT]] @_T08abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo(i8*, i8*) unnamed_addr {{.*}} {
dynamic func bar() -> MyRect {
return MyRect(x: 1, y: 2, width: 3, height: 4)
}
// x86_64-macosx: define hidden double @_T08abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}F(%VSC6CGRect* noalias nocapture dereferenceable({{.*}}), %C8abitypes3Foo*) {{.*}} {
// x86_64-macosx: define hidden double @_T08abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}FTo(i8*, i8*, %VSC6CGRect* byval align 8) unnamed_addr {{.*}} {
// armv7-ios: define hidden double @_T08abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}F(%VSC6CGRect* noalias nocapture dereferenceable({{.*}}), %C8abitypes3Foo*) {{.*}} {
// armv7-ios: define hidden double @_T08abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}FTo(i8*, i8*, [4 x i32]) unnamed_addr {{.*}} {
// armv7s-ios: define hidden double @_T08abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}F(%VSC6CGRect* noalias nocapture dereferenceable({{.*}}), %C8abitypes3Foo*) {{.*}} {
// armv7s-ios: define hidden double @_T08abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}FTo(i8*, i8*, [4 x i32]) unnamed_addr {{.*}} {
// armv7k-watchos: define hidden double @_T08abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}F(%VSC6CGRect* noalias nocapture dereferenceable(16), %C8abitypes3Foo*) {{.*}} {
// armv7k-watchos: define hidden double @_T08abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}FTo(i8*, i8*, [4 x float]) unnamed_addr {{.*}} {
dynamic func getXFromNSRect(_ r: NSRect) -> Double {
return Double(r.origin.x)
}
// x86_64-macosx: define hidden float @_T08abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}F(%VSC6MyRect* noalias nocapture dereferenceable({{.*}}), %C8abitypes3Foo*) {{.*}} {
// x86_64-macosx: define hidden float @_T08abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}FTo(i8*, i8*, <2 x float>, <2 x float>) unnamed_addr {{.*}} {
// armv7-ios: define hidden float @_T08abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}F(%VSC6MyRect* noalias nocapture dereferenceable({{.*}}), %C8abitypes3Foo*) {{.*}} {
// armv7-ios: define hidden float @_T08abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}FTo(i8*, i8*, [4 x i32]) unnamed_addr {{.*}} {
// armv7s-ios: define hidden float @_T08abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}F(%VSC6MyRect* noalias nocapture dereferenceable({{.*}}), %C8abitypes3Foo*) {{.*}} {
// armv7s-ios: define hidden float @_T08abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}FTo(i8*, i8*, [4 x i32]) unnamed_addr {{.*}} {
// armv7k-watchos: define hidden float @_T08abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}F(%VSC6MyRect* noalias nocapture dereferenceable(16), %C8abitypes3Foo*) {{.*}} {
// armv7k-watchos: define hidden float @_T08abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}FTo(i8*, i8*, [4 x float]) unnamed_addr {{.*}} {
dynamic func getXFromRect(_ r: MyRect) -> Float {
return r.x
}
// Call from Swift entrypoint with exploded Rect to @objc entrypoint
// with unexploded ABI-coerced type.
// x86_64-macosx: define hidden float @_T08abitypes3FooC17getXFromRectSwift{{.*}}(%VSC6MyRect* noalias nocapture dereferenceable({{.*}}), [[SELF:%.*]]*) {{.*}} {
// x86_64-macosx: [[COERCED:%.*]] = alloca [[MYRECT:%.*MyRect.*]], align 8
// x86_64-macosx: [[SEL:%.*]] = load i8*, i8** @"\01L_selector(getXFromRect:)", align 8
// x86_64-macosx: [[CAST:%.*]] = bitcast [[MYRECT]]* [[COERCED]] to { <2 x float>, <2 x float> }*
// x86_64-macosx: [[T0:%.*]] = getelementptr inbounds { <2 x float>, <2 x float> }, { <2 x float>, <2 x float> }* [[CAST]], i32 0, i32 0
// x86_64-macosx: [[FIRST_HALF:%.*]] = load <2 x float>, <2 x float>* [[T0]]
// x86_64-macosx: [[T0:%.*]] = getelementptr inbounds { <2 x float>, <2 x float> }, { <2 x float>, <2 x float> }* [[CAST]], i32 0, i32 1
// x86_64-macosx: [[SECOND_HALF:%.*]] = load <2 x float>, <2 x float>* [[T0]]
// x86_64-macosx: [[SELFCAST:%.*]] = bitcast [[SELF]]* %1 to i8*
// x86_64-macosx: [[RESULT:%.*]] = call float bitcast (void ()* @objc_msgSend to float (i8*, i8*, <2 x float>, <2 x float>)*)(i8* [[SELFCAST]], i8* [[SEL]], <2 x float> [[FIRST_HALF]], <2 x float> [[SECOND_HALF]])
// armv7-ios: define hidden float @_T08abitypes3FooC17getXFromRectSwift{{[_0-9a-zA-Z]*}}F(%VSC6MyRect* noalias nocapture dereferenceable({{.*}}), [[SELF:%.*]]*) {{.*}} {
// armv7-ios: [[COERCED:%.*]] = alloca [[MYRECT:%.*MyRect.*]], align 4
// armv7-ios: [[SEL:%.*]] = load i8*, i8** @"\01L_selector(getXFromRect:)", align 4
// armv7-ios: [[CAST:%.*]] = bitcast [[MYRECT]]* [[COERCED]] to [4 x i32]*
// armv7-ios: [[LOADED:%.*]] = load [4 x i32], [4 x i32]* [[CAST]]
// armv7-ios: [[SELFCAST:%.*]] = bitcast [[SELF]]* %1 to i8*
// armv7-ios: [[RESULT:%.*]] = call float bitcast (void ()* @objc_msgSend to float (i8*, i8*, [4 x i32])*)(i8* [[SELFCAST]], i8* [[SEL]], [4 x i32] [[LOADED]])
// armv7s-ios: define hidden float @_T08abitypes3FooC17getXFromRectSwift{{[_0-9a-zA-Z]*}}F(%VSC6MyRect* noalias nocapture dereferenceable({{.*}}), [[SELF:%.*]]*) {{.*}} {
// armv7s-ios: [[COERCED:%.*]] = alloca [[MYRECT:%.*MyRect.*]], align 4
// armv7s-ios: [[SEL:%.*]] = load i8*, i8** @"\01L_selector(getXFromRect:)", align 4
// armv7s-ios: [[CAST:%.*]] = bitcast [[MYRECT]]* [[COERCED]] to [4 x i32]*
// armv7s-ios: [[LOADED:%.*]] = load [4 x i32], [4 x i32]* [[CAST]]
// armv7s-ios: [[SELFCAST:%.*]] = bitcast [[SELF]]* %1 to i8*
// armv7s-ios: [[RESULT:%.*]] = call float bitcast (void ()* @objc_msgSend to float (i8*, i8*, [4 x i32])*)(i8* [[SELFCAST]], i8* [[SEL]], [4 x i32] [[LOADED]])
// armv7k-watchos: define hidden float @_T08abitypes3FooC17getXFromRectSwift{{[_0-9a-zA-Z]*}}F(%VSC6MyRect* noalias nocapture dereferenceable(16), [[SELF:%.*]]*) {{.*}} {
// armv7k-watchos: [[COERCED:%.*]] = alloca [[MYRECT:%.*MyRect.*]], align 4
// armv7k-watchos: [[SEL:%.*]] = load i8*, i8** @"\01L_selector(getXFromRect:)", align 4
// armv7k-watchos: [[CAST:%.*]] = bitcast [[MYRECT]]* [[COERCED]] to [4 x float]*
// armv7k-watchos: [[LOADED:%.*]] = load [4 x float], [4 x float]* [[CAST]]
// armv7k-watchos: [[SELFCAST:%.*]] = bitcast [[SELF]]* %1 to i8*
// armv7k-watchos: [[RESULT:%.*]] = call float bitcast (void ()* @objc_msgSend to float (i8*, i8*, [4 x float])*)(i8* [[SELFCAST]], i8* [[SEL]], [4 x float] [[LOADED]])
func getXFromRectSwift(_ r: MyRect) -> Float {
return getXFromRect(r)
}
// Ensure that MyRect is passed as an indirect-byval on x86_64 because we run out of registers for direct arguments
// x86_64-macosx: define hidden float @_T08abitypes3FooC25getXFromRectIndirectByVal{{[_0-9a-zA-Z]*}}FTo(i8*, i8*, float, float, float, float, float, float, float, %VSC6MyRect* byval align 4) unnamed_addr {{.*}} {
dynamic func getXFromRectIndirectByVal(_: Float, second _: Float,
third _: Float, fourth _: Float,
fifth _: Float, sixth _: Float,
seventh _: Float, withRect r: MyRect)
-> Float {
return r.x
}
// Make sure the caller-side from Swift also uses indirect-byval for the argument
// x86_64-macosx: define hidden float @_T08abitypes3FooC25getXFromRectIndirectSwift{{[_0-9a-zA-Z]*}}F(%VSC6MyRect* noalias nocapture dereferenceable({{.*}}), %C8abitypes3Foo*) {{.*}} {
func getXFromRectIndirectSwift(_ r: MyRect) -> Float {
let f : Float = 1.0
// x86_64-macosx: [[TEMP:%.*]] = alloca [[TEMPTYPE:%.*]], align 4
// x86_64-macosx: [[RESULT:%.*]] = call float bitcast (void ()* @objc_msgSend to float (i8*, i8*, float, float, float, float, float, float, float, [[TEMPTYPE]]*)*)(i8* %{{.*}}, i8* %{{.*}}, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, [[TEMPTYPE]]* byval align 4 [[TEMP]])
// x86_64-macosx: ret float [[RESULT]]
return getXFromRectIndirectByVal(f, second: f, third: f, fourth: f, fifth: f, sixth: f, seventh: f, withRect: r);
}
// x86_64 returns an HA of four floats directly in two <2 x float>
// x86_64-macosx: define hidden float @_T08abitypes3FooC4barc{{[_0-9a-zA-Z]*}}F(%CSo13StructReturns*, %C8abitypes3Foo*) {{.*}} {
// x86_64-macosx: load i8*, i8** @"\01L_selector(newRect)", align 8
// x86_64-macosx: [[RESULT:%.*]] = call { <2 x float>, <2 x float> } bitcast (void ()* @objc_msgSend
// x86_64-macosx: store { <2 x float>, <2 x float> } [[RESULT]]
// x86_64-macosx: [[CAST:%.*]] = bitcast { <2 x float>, <2 x float> }*
// x86_64-macosx: load { float, float, float, float }, { float, float, float, float }* [[CAST]]
// x86_64-macosx: ret float
//
// armv7 returns an HA of four floats indirectly
// armv7-ios: define hidden float @_T08abitypes3FooC4barc{{[_0-9a-zA-Z]*}}F(%CSo13StructReturns*, %C8abitypes3Foo*) {{.*}} {
// armv7-ios: [[RESULT:%.*]] = alloca [[RECTTYPE:%.*MyRect.*]], align 4
// armv7-ios: load i8*, i8** @"\01L_selector(newRect)", align 4
// armv7-ios: call void bitcast (void ()* @objc_msgSend_stret to void ([[RECTTYPE]]*, [[RECEIVER:.*]]*, i8*)*)([[RECTTYPE]]* noalias nocapture sret %call.aggresult
// armv7-ios: [[GEP1:%.*]] = getelementptr inbounds [[RECTTYPE]], [[RECTTYPE]]* [[RESULT]], i32 0, i32 1
// armv7-ios: [[GEP2:%.*]] = getelementptr inbounds {{.*}}, {{.*}}* [[GEP1]], i32 0, i32 0
// armv7-ios: [[RETVAL:%.*]] = load float, float* [[GEP2]], align 4
// armv7-ios: ret float [[RETVAL]]
//
// armv7s returns an HA of four floats indirectly
// armv7s-ios: define hidden float @_T08abitypes3FooC4barc{{[_0-9a-zA-Z]*}}F(%CSo13StructReturns*, %C8abitypes3Foo*) {{.*}} {
// armv7s-ios: [[RESULT:%.*]] = alloca [[RECTTYPE:%.*MyRect.*]], align 4
// armv7s-ios: load i8*, i8** @"\01L_selector(newRect)", align 4
// armv7s-ios: call void bitcast (void ()* @objc_msgSend_stret to void ([[RECTTYPE]]*, [[RECEIVER:.*]]*, i8*)*)([[RECTTYPE]]* noalias nocapture sret %call.aggresult
// armv7s-ios: [[GEP1:%.*]] = getelementptr inbounds [[RECTTYPE]], [[RECTTYPE]]* [[RESULT]], i32 0, i32 1
// armv7s-ios: [[GEP2:%.*]] = getelementptr inbounds {{.*}}, {{.*}}* [[GEP1]], i32 0, i32 0
// armv7s-ios: [[RETVAL:%.*]] = load float, float* [[GEP2]], align 4
// armv7s-ios: ret float [[RETVAL]]
//
// armv7k returns an HA of four floats directly
// armv7k-watchos: define hidden float @_T08abitypes3FooC4barc{{[_0-9a-zA-Z]*}}F(%CSo13StructReturns*, %C8abitypes3Foo*) {{.*}} {
// armv7k-watchos: load i8*, i8** @"\01L_selector(newRect)", align 4
// armv7k-watchos: [[RESULT:%.*]] = call [[ARMV7K_MYRECT]] bitcast (void ()* @objc_msgSend
// armv7k-watchos: store [[ARMV7K_MYRECT]] [[RESULT]]
// armv7k-watchos: [[CAST:%.*]] = bitcast [[ARMV7K_MYRECT]]*
// armv7k-watchos: load { float, float, float, float }, { float, float, float, float }* [[CAST]]
// armv7k-watchos: ret float
func barc(_ p: StructReturns) -> Float {
return p.newRect().y
}
// x86_64-macosx: define hidden { double, double, double } @_T08abitypes3FooC3baz{{[_0-9a-zA-Z]*}}F(%C8abitypes3Foo*) {{.*}} {
// x86_64-macosx: define hidden void @_T08abitypes3FooC3baz{{[_0-9a-zA-Z]*}}FTo(%VSC4Trio* noalias nocapture sret, i8*, i8*) unnamed_addr {{.*}} {
dynamic func baz() -> Trio {
return Trio(i: 1.0, j: 2.0, k: 3.0)
}
// x86_64-macosx: define hidden double @_T08abitypes3FooC4bazc{{[_0-9a-zA-Z]*}}F(%CSo13StructReturns*, %C8abitypes3Foo*) {{.*}} {
// x86_64-macosx: load i8*, i8** @"\01L_selector(newTrio)", align 8
// x86_64-macosx: [[CAST:%[0-9]+]] = bitcast {{%.*}}* %0
// x86_64-macosx: call void bitcast (void ()* @objc_msgSend_stret to void (%VSC4Trio*, [[OPAQUE:.*]]*, i8*)*)
func bazc(_ p: StructReturns) -> Double {
return p.newTrio().j
}
// x86_64-macosx: define hidden { i32, i32 } @_T08abitypes3FooC7getpair{{[_0-9a-zA-Z]*}}F(%CSo13StructReturns*, %C8abitypes3Foo*) {{.*}} {
// x86_64-macosx: [[RESULT:%.*]] = call i64 bitcast (void ()* @objc_msgSend to i64 ([[OPAQUE:.*]]*, i8*)*)
// x86_64-macosx: store i64 [[RESULT]]
// x86_64-macosx: [[CAST:%.*]] = bitcast i64* {{%.*}} to { i32, i32 }*
// x86_64-macosx: load { i32, i32 }, { i32, i32 }* [[CAST]]
// x86_64-macosx: ret { i32, i32 }
func getpair(_ p: StructReturns) -> IntPair {
return p.newPair()
}
// x86_64-macosx: define hidden i64 @_T08abitypes3FooC8takepair{{[_0-9a-zA-Z]*}}FTo(i8*, i8*, i64) unnamed_addr {{.*}} {
dynamic func takepair(_ p: IntPair) -> IntPair {
return p
}
// x86_64-macosx: define hidden { i32, i32 } @_T08abitypes3FooC9getnested{{[_0-9a-zA-Z]*}}F(%CSo13StructReturns*, %C8abitypes3Foo*) {{.*}} {
// x86_64-macosx: call i64 bitcast (void ()* @objc_msgSend to i64 ([[OPAQUE:.*]]*, i8*)*)
// x86_64-macosx-NEXT: bitcast
// x86_64-macosx-NEXT: llvm.lifetime.start
// x86_64-macosx-NEXT: store i64
// x86_64-macosx-NEXT: bitcast i64* {{[^ ]*}} to { i32, i32 }*
// x86_64-macosx-NEXT: load { i32, i32 }, { i32, i32 }*
// x86_64-macosx-NEXT: bitcast
// x86_64-macosx-NEXT: llvm.lifetime.end
// x86_64-macosx: ret { i32, i32 }
func getnested(_ p: StructReturns) -> NestedInts {
return p.newNestedInts()
}
// x86_64-macosx: define hidden i8* @_T08abitypes3FooC9copyClass{{[_0-9a-zA-Z]*}}FTo(i8*, i8*, i8*) unnamed_addr {{.*}} {
// x86_64-macosx: [[VALUE:%[0-9]+]] = call [[TYPE:%.*]]* @_T08abitypes3FooC9copyClass{{[_0-9a-zA-Z]*}}F
// x86_64-macosx: [[T0:%.*]] = phi [[TYPE]]* [ [[VALUE]],
// x86_64-macosx: [[T1:%.*]] = bitcast [[TYPE]]* [[T0]] to [[OBJC:%objc_class]]*
// x86_64-macosx: [[RESULT:%[0-9]+]] = bitcast [[OBJC]]* [[T1]] to i8*
// x86_64-macosx: ret i8* [[RESULT]]
dynamic func copyClass(_ a: AnyClass) -> AnyClass {
return a
}
// x86_64-macosx: define hidden i8* @_T08abitypes3FooC9copyProto{{[_0-9a-zA-Z]*}}FTo(i8*, i8*, i8*) unnamed_addr {{.*}} {
// x86_64-macosx: [[VALUE:%[0-9]+]] = call [[TYPE:%.*]] @_T08abitypes3FooC9copyProto{{[_0-9a-zA-Z]*}}F
// x86_64-macosx: [[RESULT:%[0-9]+]] = bitcast [[TYPE]] [[VALUE]] to i8*
// x86_64-macosx: ret i8* [[RESULT]]
dynamic func copyProto(_ a: AnyObject) -> AnyObject {
return a
}
// x86_64-macosx: define hidden i8* @_T08abitypes3FooC13copyProtoComp{{[_0-9a-zA-Z]*}}FTo(i8*, i8*, i8*) unnamed_addr {{.*}} {
// x86_64-macosx: [[VALUE:%[0-9]+]] = call [[TYPE:%.*]] @_T08abitypes3FooC13copyProtoComp{{[_0-9a-zA-Z]*}}F
// x86_64-macosx: [[RESULT:%[0-9]+]] = bitcast [[TYPE]] [[VALUE]] to i8*
// x86_64-macosx: ret i8* [[RESULT]]
dynamic func copyProtoComp(_ a: P1 & P2) -> P1 & P2 {
return a
}
// x86_64-macosx: define hidden i1 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F(i1, %C8abitypes3Foo*) {{.*}} {
// x86_64-macosx: define hidden signext i8 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo(i8*, i8*, i8 signext) unnamed_addr {{.*}} {
// x86_64-macosx: [[R1:%[0-9]+]] = call i1 @_T010ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F
// x86_64-macosx: [[R2:%[0-9]+]] = call i1 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F
// x86_64-macosx: [[R3:%[0-9]+]] = call i8 @_T010ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F(i1 [[R2]]
// x86_64-macosx: ret i8 [[R3]]
//
// x86_64-ios-fixme: define hidden i1 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F(i1, %C8abitypes3Foo*) {{.*}} {
// x86_64-ios-fixme: define internal zeroext i1 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo
// x86_64-ios-fixme: [[R1:%[0-9]+]] = call i1 @_T010ObjectiveC22_convertObjCBoolToBoolSbAA0cD0V1x_tF(i1 %2)
// x86_64-ios-fixme: [[R2:%[0-9]+]] = call i1 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F(i1 [[R1]]
// x86_64-ios-fixme: [[R3:%[0-9]+]] = call i1 @_T010ObjectiveC22_convertBoolToObjCBoolAA0eF0VSb1x_tF(i1 [[R2]])
// x86_64-ios-fixme: ret i1 [[R3]]
//
// armv7-ios-fixme: define hidden i1 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F(i1, %C8abitypes3Foo*) {{.*}} {
// armv7-ios-fixme: define internal signext i8 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo(i8*, i8*, i8 signext) unnamed_addr {{.*}} {
// armv7-ios-fixme: [[R1:%[0-9]+]] = call i1 @_T010ObjectiveC22_convertObjCBoolToBoolSbAA0cD0V1x_tF
// armv7-ios-fixme: [[R2:%[0-9]+]] = call i1 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F(i1 [[R1]]
// armv7-ios-fixme: [[R3:%[0-9]+]] = call i8 @_T010ObjectiveC22_convertBoolToObjCBoolAA0eF0VSb1x_tF(i1 [[R2]]
// armv7-ios-fixme: ret i8 [[R3]]
//
// armv7s-ios-fixme: define hidden i1 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F(i1, %C8abitypes3Foo*) {{.*}} {
// armv7s-ios-fixme: define internal signext i8 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo(i8*, i8*, i8 signext) unnamed_addr {{.*}} {
// armv7s-ios-fixme: [[R1:%[0-9]+]] = call i1 @_T010ObjectiveC22_convertObjCBoolToBoolSbAA0cD0V1x_tF
// armv7s-ios-fixme: [[R2:%[0-9]+]] = call i1 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F(i1 [[R1]]
// armv7s-ios-fixme: [[R3:%[0-9]+]] = call i8 @_T010ObjectiveC22_convertBoolToObjCBoolAA0eF0VSb1x_tF(i1 [[R2]]
// armv7s-ios-fixme: ret i8 [[R3]]
//
// arm64-ios-fixme: define hidden i1 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F(i1, %C8abitypes3Foo*) {{.*}} {
// arm64-ios-fixme: define internal zeroext i1 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo
// arm64-ios-fixme: [[R2:%[0-9]+]] = call i1 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F
// arm64-ios-fixme: ret i1 [[R2]]
//
// i386-ios-fixme: define hidden i1 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F(i1, %C8abitypes3Foo*) {{.*}} {
// i386-ios-fixme: define internal signext i8 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo(i8*, i8*, i8 signext) unnamed_addr {{.*}} {
// i386-ios-fixme: [[R1:%[0-9]+]] = call i1 @_T010ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F
// i386-ios-fixme: [[R2:%[0-9]+]] = call i1 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F(i1 [[R1]]
// i386-ios-fixme: [[R3:%[0-9]+]] = call i8 @_T010ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F(i1 [[R2]]
// i386-ios-fixme: ret i8 [[R3]]
//
// x86_64-tvos-fixme: define hidden i1 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F(i1, %C8abitypes3Foo*) {{.*}} {
// x86_64-tvos-fixme: define internal zeroext i1 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo
// x86_64-tvos-fixme: [[R1:%[0-9]+]] = call i1 @_T010ObjectiveC22_convertObjCBoolToBoolSbAA0cD0V1x_tF(i1 %2)
// x86_64-tvos-fixme: [[R2:%[0-9]+]] = call i1 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F(i1 [[R1]]
// x86_64-tvos-fixme: [[R3:%[0-9]+]] = call i1 @_T010ObjectiveC22_convertBoolToObjCBoolAA0eF0VSb1x_tF(i1 [[R2]])
// x86_64-tvos-fixme: ret i1 [[R3]]
//
// arm64-tvos-fixme: define hidden i1 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F(i1, %C8abitypes3Foo*) {{.*}} {
// arm64-tvos-fixme: define internal zeroext i1 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo
// arm64-tvos-fixme: [[R2:%[0-9]+]] = call i1 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F
// arm64-tvos-fixme: ret i1 [[R2]]
// i386-watchos: define hidden i1 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F(i1, %C8abitypes3Foo*)
// i386-watchos: define hidden zeroext i1 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo
// i386-watchos: [[R1:%[0-9]+]] = call i1 @_T010ObjectiveC22_convertObjCBoolToBoolSbAA0cD0VF(i1 %2)
// i386-watchos: [[R2:%[0-9]+]] = call i1 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F(i1 [[R1]]
// i386-watchos: [[R3:%[0-9]+]] = call i1 @_T010ObjectiveC22_convertBoolToObjCBoolAA0eF0VSbF(i1 [[R2]])
// i386-watchos: ret i1 [[R3]]
dynamic func negate(_ b: Bool) -> Bool {
return !b
}
// x86_64-macosx: define hidden i1 @_T08abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F(i1, %C8abitypes3Foo*) {{.*}} {
// x86_64-macosx: [[TOOBJCBOOL:%[0-9]+]] = call i8 @_T010ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F(i1 %0)
// x86_64-macosx: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 8
// x86_64-macosx: [[NEG:%[0-9]+]] = call signext i8 bitcast (void ()* @objc_msgSend to i8 ([[RECEIVER:.*]]*, i8*, i8)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i8 signext [[TOOBJCBOOL]])
// x86_64-macosx: [[TOBOOL:%[0-9]+]] = call i1 @_T010ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F(i8 [[NEG]])
// x86_64-macosx: ret i1 [[TOBOOL]]
//
// x86_64-macosx: define hidden signext i8 @_T08abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo(i8*, i8*, i8 signext)
// x86_64-macosx: [[TOBOOL:%[0-9]+]] = call i1 @_T010ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F
// x86_64-macosx: [[NEG:%[0-9]+]] = call i1 @_T08abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F(i1 [[TOBOOL]]
// x86_64-macosx: [[TOOBJCBOOL:%[0-9]+]] = call i8 @_T010ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F(i1 [[NEG]])
// x86_64-macosx: ret i8 [[TOOBJCBOOL]]
//
// x86_64-ios: define hidden i1 @_T08abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F(i1, %C8abitypes3Foo*) {{.*}} {
// x86_64-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 8
// x86_64-ios: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 ([[RECEIVER:.*]]*, i8*, i1)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext %0)
// x86_64-ios: ret i1 [[NEG]]
//
// x86_64-ios: define hidden zeroext i1 @_T08abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo(i8*, i8*, i1 zeroext)
// x86_64-ios: [[NEG:%[0-9]+]] = call i1 @_T08abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F(i1
// x86_64-ios: [[TOOBJCBOOL:%[0-9]+]] = call i1 @_T010ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F(i1 [[NEG]])
// x86_64-ios: ret i1 [[TOOBJCBOOL]]
//
// armv7-ios: define hidden i1 @_T08abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F(i1, %C8abitypes3Foo*) {{.*}} {
// armv7-ios: [[TOOBJCBOOL:%[0-9]+]] = call i8 @_T010ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F(i1 %0)
// armv7-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 4
// armv7-ios: [[NEG:%[0-9]+]] = call signext i8 bitcast (void ()* @objc_msgSend to i8 ([[RECEIVER:.*]]*, i8*, i8)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i8 signext [[TOOBJCBOOL]])
// armv7-ios: [[TOBOOL:%[0-9]+]] = call i1 @_T010ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F(i8 [[NEG]])
// armv7-ios: ret i1 [[TOBOOL]]
//
// armv7-ios: define hidden signext i8 @_T08abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo(i8*, i8*, i8 signext)
// armv7-ios: [[TOBOOL:%[0-9]+]] = call i1 @_T010ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F
// armv7-ios: [[NEG:%[0-9]+]] = call i1 @_T08abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F(i1 [[TOBOOL]]
// armv7-ios: [[TOOBJCBOOL:%[0-9]+]] = call i8 @_T010ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F(i1 [[NEG]])
// armv7-ios: ret i8 [[TOOBJCBOOL]]
//
// armv7s-ios: define hidden i1 @_T08abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F(i1, %C8abitypes3Foo*) {{.*}} {
// armv7s-ios: [[TOOBJCBOOL:%[0-9]+]] = call i8 @_T010ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F(i1 %0)
// armv7s-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 4
// armv7s-ios: [[NEG:%[0-9]+]] = call signext i8 bitcast (void ()* @objc_msgSend to i8 ([[RECEIVER:.*]]*, i8*, i8)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i8 signext [[TOOBJCBOOL]])
// armv7s-ios: [[TOBOOL:%[0-9]+]] = call i1 @_T010ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F(i8 [[NEG]])
// armv7s-ios: ret i1 [[TOBOOL]]
//
// armv7s-ios: define hidden signext i8 @_T08abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo(i8*, i8*, i8 signext)
// armv7s-ios: [[TOBOOL:%[0-9]+]] = call i1 @_T010ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F
// armv7s-ios: [[NEG:%[0-9]+]] = call i1 @_T08abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F(i1 [[TOBOOL]]
// armv7s-ios: [[TOOBJCBOOL:%[0-9]+]] = call i8 @_T010ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F(i1 [[NEG]])
// armv7s-ios: ret i8 [[TOOBJCBOOL]]
//
// arm64-ios: define hidden i1 @_T08abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F(i1, %C8abitypes3Foo*) {{.*}} {
// arm64-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 8
// arm64-ios: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 ([[RECEIVER:.*]]*, i8*, i1)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext %0)
// arm64-ios: ret i1 [[NEG]]
//
// arm64-ios: define hidden zeroext i1 @_T08abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo(i8*, i8*, i1 zeroext)
// arm64-ios: [[NEG:%[0-9]+]] = call i1 @_T08abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F(i1
// arm64-ios: [[TOOBJCBOOL:%[0-9]+]] = call i1 @_T010ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F(i1 [[NEG]])
// arm64-ios: ret i1 [[TOOBJCBOOL]]
//
// i386-ios: define hidden i1 @_T08abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F(i1, %C8abitypes3Foo*) {{.*}} {
// i386-ios: [[TOOBJCBOOL:%[0-9]+]] = call i8 @_T010ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F(i1 %0)
// i386-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 4
// i386-ios: [[NEG:%[0-9]+]] = call signext i8 bitcast (void ()* @objc_msgSend to i8 ([[RECEIVER:.*]]*, i8*, i8)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i8 signext [[TOOBJCBOOL]])
// i386-ios: [[TOBOOL:%[0-9]+]] = call i1 @_T010ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F(i8 [[NEG]])
// i386-ios: ret i1 [[TOBOOL]]
//
// i386-ios: define hidden signext i8 @_T08abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo(i8*, i8*, i8 signext)
// i386-ios: [[TOBOOL:%[0-9]+]] = call i1 @_T010ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F
// i386-ios: [[NEG:%[0-9]+]] = call i1 @_T08abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F(i1 [[TOBOOL]]
// i386-ios: [[TOOBJCBOOL:%[0-9]+]] = call i8 @_T010ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F(i1 [[NEG]])
// i386-ios: ret i8 [[TOOBJCBOOL]]
//
// x86_64-tvos: define hidden i1 @_T08abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F(i1, %C8abitypes3Foo*) {{.*}} {
// x86_64-tvos: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 8
// x86_64-tvos: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 ([[RECEIVER:.*]]*, i8*, i1)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext %0)
// x86_64-tvos: ret i1 [[NEG]]
//
// x86_64-tvos: define hidden zeroext i1 @_T08abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo(i8*, i8*, i1 zeroext)
// x86_64-tvos: [[NEG:%[0-9]+]] = call i1 @_T08abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F(i1
// x86_64-tvos: [[TOOBJCBOOL:%[0-9]+]] = call i1 @_T010ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F(i1 [[NEG]])
// x86_64-tvos: ret i1 [[TOOBJCBOOL]]
//
// arm64-tvos: define hidden i1 @_T08abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F(i1, %C8abitypes3Foo*) {{.*}} {
// arm64-tvos: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 8
// arm64-tvos: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 ([[RECEIVER:.*]]*, i8*, i1)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext %0)
// arm64-tvos: ret i1 [[NEG]]
//
// arm64-tvos: define hidden zeroext i1 @_T08abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo(i8*, i8*, i1 zeroext)
// arm64-tvos: [[NEG:%[0-9]+]] = call i1 @_T08abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F(i1
// arm64-tvos: [[TOOBJCBOOL:%[0-9]+]] = call i1 @_T010ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F(i1 [[NEG]])
// arm64-tvos: ret i1 [[TOOBJCBOOL]]
// i386-watchos: define hidden i1 @_T08abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F(i1, %C8abitypes3Foo*) {{.*}} {
// i386-watchos: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 4
// i386-watchos: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 ([[RECEIVER:.*]]*, i8*, i1)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext %0)
// i386-watchos: ret i1 [[NEG]]
//
// i386-watchos: define hidden zeroext i1 @_T08abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo(i8*, i8*, i1 zeroext)
// i386-watchos: [[NEG:%[0-9]+]] = call i1 @_T08abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F(i1
// i386-watchos: [[TOOBJCBOOL:%[0-9]+]] = call i1 @_T010ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F(i1 [[NEG]])
// i386-watchos: ret i1 [[TOOBJCBOOL]]
//
// armv7k-watchos: define hidden i1 @_T08abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F(i1, %C8abitypes3Foo*) {{.*}} {
// armv7k-watchos: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 4
// armv7k-watchos: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 ([[RECEIVER:.*]]*, i8*, i1)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext %0)
// armv7k-watchos: ret i1 [[NEG]]
//
// armv7k-watchos: define hidden zeroext i1 @_T08abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo(i8*, i8*, i1 zeroext)
// armv7k-watchos: [[NEG:%[0-9]+]] = call i1 @_T08abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F(i1
// armv7k-watchos: [[TOOBJCBOOL:%[0-9]+]] = call i1 @_T010ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F(i1 [[NEG]])
// armv7k-watchos: ret i1 [[TOOBJCBOOL]]
//
dynamic func negate2(_ b: Bool) -> Bool {
var g = Gadget()
return g.negate(b)
}
// x86_64-macosx: define hidden i1 @_T08abitypes3FooC7negate3SbSbF(i1, %C8abitypes3Foo*) {{.*}} {
// x86_64-macosx: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(invert:)", align 8
// x86_64-macosx: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 (%1*, i8*, i1)*)(%1* [[RECEIVER:%[0-9]+]], i8* [[SEL]], i1 zeroext %0)
// x86_64-macosx: ret i1 [[NEG]]
// x86_64-macosx: }
// x86_64-ios: define hidden i1 @_T08abitypes3FooC7negate3SbSbF(i1, %C8abitypes3Foo*) {{.*}} {
// x86_64-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(invert:)", align 8
// x86_64-ios: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 (%1*, i8*, i1)*)(%1* [[RECEIVER:%[0-9]+]], i8* [[SEL]], i1 zeroext %0)
// x86_64-ios: ret i1 [[NEG]]
// x86_64-ios: }
// i386-ios: define hidden i1 @_T08abitypes3FooC7negate3SbSbF(i1, %C8abitypes3Foo*) {{.*}} {
// i386-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(invert:)", align 4
// i386-ios: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 (%1*, i8*, i1)*)(%1* [[RECEIVER:%[0-9]+]], i8* [[SEL]], i1 zeroext %0)
// i386-ios: ret i1 [[NEG]]
// i386-ios: }
dynamic func negate3(_ b: Bool) -> Bool {
var g = Gadget()
return g.invert(b)
}
// x86_64-macosx: define hidden void @_T08abitypes3FooC10throwsTestySbKF(i1, %C8abitypes3Foo*, %swift.error**) {{.*}} {
// x86_64-macosx: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negateThrowing:error:)", align 8
// x86_64-macosx: call signext i8 bitcast (void ()* @objc_msgSend to i8 (%1*, i8*, i8, %2**)*)(%1* {{%[0-9]+}}, i8* [[SEL]], i8 signext {{%[0-9]+}}, %2** {{%[0-9]+}})
// x86_64-macosx: }
// x86_64-ios: define hidden void @_T08abitypes3FooC10throwsTestySbKF(i1, %C8abitypes3Foo*, %swift.error**) {{.*}} {
// x86_64-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negateThrowing:error:)", align 8
// x86_64-ios: call zeroext i1 bitcast (void ()* @objc_msgSend to i1 (%1*, i8*, i1, %2**)*)(%1* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext {{%[0-9]+}}, %2** {{%[0-9]+}})
// x86_64-ios: }
// i386-ios: define hidden void @_T08abitypes3FooC10throwsTestySbKF(i1, %C8abitypes3Foo*, %swift.error**) {{.*}} {
// i386-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negateThrowing:error:)", align 4
// i386-ios: call signext i8 bitcast (void ()* @objc_msgSend to i8 (%1*, i8*, i8, %2**)*)(%1* {{%[0-9]+}}, i8* [[SEL]], i8 signext {{%[0-9]+}}, %2** {{%[0-9]+}})
// i386-ios: }
dynamic func throwsTest(_ b: Bool) throws {
var g = Gadget()
try g.negateThrowing(b)
}
// x86_64-macosx: define hidden i32* @_T08abitypes3FooC24copyUnsafeMutablePointer{{[_0-9a-zA-Z]*}}FTo(i8*, i8*, i32*) unnamed_addr {{.*}} {
dynamic func copyUnsafeMutablePointer(_ p: UnsafeMutablePointer<Int32>) -> UnsafeMutablePointer<Int32> {
return p
}
// x86_64-macosx: define hidden i64 @_T08abitypes3FooC17returnNSEnumValue{{[_0-9a-zA-Z]*}}FTo(i8*, i8*) unnamed_addr {{.*}} {
dynamic func returnNSEnumValue() -> ByteCountFormatter.CountStyle {
return .file
}
// x86_64-macosx: define hidden zeroext i16 @_T08abitypes3FooC20returnOtherEnumValue{{[_0-9a-zA-Z]*}}FTo(i8*, i8*, i16 zeroext) unnamed_addr {{.*}} {
dynamic func returnOtherEnumValue(_ choice: ChooseTo) -> ChooseTo {
switch choice {
case .takeIt: return .leaveIt
case .leaveIt: return .takeIt
}
}
// x86_64-macosx: define hidden i32 @_T08abitypes3FooC10getRawEnum{{[_0-9a-zA-Z]*}}F(%C8abitypes3Foo*) {{.*}} {
// x86_64-macosx: define hidden i32 @_T08abitypes3FooC10getRawEnum{{[_0-9a-zA-Z]*}}FTo(i8*, i8*) unnamed_addr {{.*}} {
dynamic func getRawEnum() -> RawEnum {
return Intergalactic
}
var work : Work
init (work: Work) {
self.work = work
}
// x86_64-macosx: define hidden void @_T08abitypes3FooC13testArchetype{{[_0-9a-zA-Z]*}}FTo(i8*, i8*, i8*) unnamed_addr {{.*}} {
dynamic func testArchetype(_ work: Work) {
work.doStuff(1)
// x86_64-macosx: [[OBJCPTR:%.*]] = bitcast i8* %2 to %objc_object*
// x86_64-macosx: call void @_T08abitypes3FooC13testArchetype{{[_0-9a-zA-Z]*}}F(%objc_object* [[OBJCPTR]], %C8abitypes3Foo* %{{.*}})
}
dynamic func foo(_ x: @convention(block) (Int) -> Int) -> Int {
// FIXME: calling blocks is currently unimplemented
// return x(5)
return 1
}
// x86_64-macosx: define hidden void @_T08abitypes3FooC20testGenericTypeParam{{[_0-9a-zA-Z]*}}F(%objc_object*, %swift.type* %T, %C8abitypes3Foo*) {{.*}} {
func testGenericTypeParam<T: Pasta>(_ x: T) {
// x86_64-macosx: [[CAST:%.*]] = bitcast %objc_object* %0 to i8*
// x86_64-macosx: call void bitcast (void ()* @objc_msgSend to void (i8*, i8*)*)(i8* [[CAST]], i8* %{{.*}})
x.alDente()
}
// arm64-ios: define hidden void @_T08abitypes3FooC14callJustReturn{{[_0-9a-zA-Z]*}}F(%VSC9BigStruct* noalias nocapture sret, %CSo13StructReturns*, %VSC9BigStruct* noalias nocapture dereferenceable({{.*}}), %C8abitypes3Foo*) {{.*}} {
// arm64-ios: define hidden void @_T08abitypes3FooC14callJustReturn{{[_0-9a-zA-Z]*}}FTo(%VSC9BigStruct* noalias nocapture sret, i8*, i8*, [[OPAQUE:.*]]*, %VSC9BigStruct*) unnamed_addr {{.*}} {
//
// arm64-tvos: define hidden void @_T08abitypes3FooC14callJustReturn{{[_0-9a-zA-Z]*}}F(%VSC9BigStruct* noalias nocapture sret, %CSo13StructReturns*, %VSC9BigStruct* noalias nocapture dereferenceable({{.*}}), %C8abitypes3Foo*) {{.*}} {
// arm64-tvos: define hidden void @_T08abitypes3FooC14callJustReturn{{[_0-9a-zA-Z]*}}FTo(%VSC9BigStruct* noalias nocapture sret, i8*, i8*, [[OPAQUE:.*]]*, %VSC9BigStruct*) unnamed_addr {{.*}} {
dynamic func callJustReturn(_ r: StructReturns, with v: BigStruct) -> BigStruct {
return r.justReturn(v)
}
// Test that the makeOne() that we generate somewhere below doesn't
// use arm_aapcscc for armv7.
func callInline() -> Float {
return makeOne(3,5).second
}
}
// armv7-ios: define internal void @makeOne(%struct.One* noalias sret %agg.result, float %f, float %s)
// armv7s-ios: define internal void @makeOne(%struct.One* noalias sret %agg.result, float %f, float %s)
// armv7k-watchos: define internal %struct.One @makeOne(float %f, float %s)
// rdar://17631440 - Expand direct arguments that are coerced to aggregates.
// x86_64-macosx: define{{( protected)?}} float @_T08abitypes13testInlineAggSfSC6MyRectVF(%VSC6MyRect* noalias nocapture dereferenceable({{.*}})) {{.*}} {
// x86_64-macosx: [[COERCED:%.*]] = alloca %VSC6MyRect, align 8
// x86_64-macosx: store float %
// x86_64-macosx: store float %
// x86_64-macosx: store float %
// x86_64-macosx: store float %
// x86_64-macosx: [[CAST:%.*]] = bitcast %VSC6MyRect* [[COERCED]] to { <2 x float>, <2 x float> }*
// x86_64-macosx: [[T0:%.*]] = getelementptr inbounds { <2 x float>, <2 x float> }, { <2 x float>, <2 x float> }* [[CAST]], i32 0, i32 0
// x86_64-macosx: [[FIRST_HALF:%.*]] = load <2 x float>, <2 x float>* [[T0]], align 8
// x86_64-macosx: [[T0:%.*]] = getelementptr inbounds { <2 x float>, <2 x float> }, { <2 x float>, <2 x float> }* [[CAST]], i32 0, i32 1
// x86_64-macosx: [[SECOND_HALF:%.*]] = load <2 x float>, <2 x float>* [[T0]], align 8
// x86_64-macosx: [[RESULT:%.*]] = call float @MyRect_Area(<2 x float> [[FIRST_HALF]], <2 x float> [[SECOND_HALF]])
// x86_64-macosx: ret float [[RESULT]]
public func testInlineAgg(_ rect: MyRect) -> Float {
return MyRect_Area(rect)
}
// We need to allocate enough memory on the stack to hold the argument value we load.
// arm64-ios: define void @_T08abitypes14testBOOLStructyyF()
// arm64-ios: [[COERCED:%.*]] = alloca i64
// arm64-ios: [[STRUCTPTR:%.*]] = bitcast i64* [[COERCED]] to %VSC14FiveByteStruct
// arm64-ios: [[PTR0:%.*]] = getelementptr inbounds %VSC14FiveByteStruct, %VSC14FiveByteStruct* [[STRUCTPTR]], {{i.*}} 0, {{i.*}} 0
// arm64-ios: [[PTR1:%.*]] = getelementptr inbounds %V10ObjectiveC8ObjCBool, %V10ObjectiveC8ObjCBool* [[PTR0]], {{i.*}} 0, {{i.*}} 0
// arm64-ios: [[PTR2:%.*]] = getelementptr inbounds %Sb, %Sb* [[PTR1]], {{i.*}} 0, {{i.*}} 0
// arm64-ios: store i1 false, i1* [[PTR2]], align 8
// arm64-ios: [[ARG:%.*]] = load i64, i64* [[COERCED]]
// arm64-ios: call void bitcast (void ()* @objc_msgSend to void (i8*, i8*, i64)*)(i8* {{.*}}, i8* {{.*}}, i64 [[ARG]])
public func testBOOLStruct() {
let s = FiveByteStruct()
MyClass.mymethod(s)
}
|
apache-2.0
|
f9360ba18ee095cb757760633657154e
| 72.161002 | 371 | 0.606499 | 2.735402 | false | false | false | false |
wangzheng0822/algo
|
swift/09_queue/ArrayQueue.swift
|
1
|
3121
|
//
// Created by Jiandan on 2018/10/11.
// Copyright (c) 2018 Jiandan. All rights reserved.
//
import Foundation
/// 用数组实现的队列
struct ArrayQueue<Element>: Queue {
/// 数组
private var items: [Element]
/// 数组最大长度
private var capacity = 0
/// 队头下标
private var head = 0
/// 队尾下标
private var tail = 0
/// 构造方法
/// - parameter defaultElement: 默认元素
/// - parameter capacity: 数组长度
init(defaultElement: Element, capacity: Int) {
self.capacity = capacity
items = [Element](repeating: defaultElement, count: capacity)
}
// MARK: Protocol: Queue
var isEmpty: Bool { return head == tail }
var size: Int { return tail - head }
var peek: Element? { return isEmpty ? nil : items[head] }
// 没有数据搬移的实现,即实现了一个有界序列
// mutating func enqueue(newElement: Element) -> Bool {
// // 整个队列都占满了
// if tail == capacity {
// return false
// }
//
// items[tail] = newElement
// tail += 1
// return true
// }
// 有数据搬移的实现,即实现了一个无界序列
mutating func enqueue(newElement: Element) -> Bool {
// 如果 tail == capacity 表示队列末尾没有空间了
if tail == capacity {
// 整个队列都占满了
if head == 0 { return false }
// 数据搬移
for i in head ..< tail {
items[i - head] = items[i]
}
// 搬移完之后重新更新 head 和 tail
tail -= head
head = 0
}
items[tail] = newElement
tail += 1
return true
}
mutating func dequeue() -> Element? {
if isEmpty {
return nil
}
let item = items[head]
head += 1
return item
}
}
/// 使用2个数组实现无界队列,用到 Swift 中 Array 较多的方法
/// 来源:《iOS 面试之道》(故胤道长,唐巧)
struct ArrayQueue2<Element>: Queue {
/// 输入数组,主要负责入队
var inArray = [Element]()
/// 输出数组,主要负责出队
var outArray = [Element]()
var isEmpty: Bool { return inArray.isEmpty && outArray.isEmpty }
var size: Int { return inArray.count + outArray.count }
// 当 outArray 为空时,返回 inArray 首个元素,否则返回 outArray 末尾元素
var peek: Element? { return outArray.isEmpty ? inArray.first : outArray.last }
mutating func enqueue(newElement: Element) -> Bool {
// inArray 添加元素
inArray.append(newElement)
return true
}
mutating func dequeue() -> Element? {
if outArray.isEmpty {
// 将 inArray 倒序存入 outArray 中
outArray = inArray.reversed()
// 清空 inArray
inArray.removeAll()
}
// 弹出 outArray 最后一个元素
return outArray.popLast()
}
}
|
apache-2.0
|
c96cdfde41b169ec5b148b4cf675cff6
| 23.861111 | 82 | 0.537058 | 3.765778 | false | false | false | false |
Electrode-iOS/ELCodable
|
ELCodableTests/NestedErrorTesting.swift
|
1
|
3127
|
//
// NestedErrorTesting.swift
// ELCodable
//
// Created by Brandon Sneed on 1/12/16.
// Copyright © 2016 WalmartLabs. All rights reserved.
//
import XCTest
import ELCodable
import CoreLocation
// MARK: WMSNGAddress
struct WMSNGAddress: Equatable {
let street1: String
let street2: String?
let city: String
let state: String
let zip: String
let country: String
}
func ==(lhs: WMSNGAddress, rhs: WMSNGAddress) -> Bool {
return lhs.street1 == rhs.street1 &&
lhs.street2 == rhs.street2 &&
lhs.city == rhs.city &&
lhs.state == rhs.state &&
lhs.zip == rhs.zip &&
lhs.country == rhs.country
}
extension WMSNGAddress: ELCodable.Decodable {
static func decode(_ json: JSON?) throws -> WMSNGAddress {
return try WMSNGAddress(street1: json ==> "street1",
street2: json ==> "street2",
city: json ==> "cityjij",
state: json ==> "state",
zip: json ==> "zip",
country: json ==> "country")
}
func validate() throws -> WMSNGAddress {
// Possibly validate the data here
return self
}
}
// MARK: WMSNGStore
struct WMSNGStore: Equatable {
let storeId: String
let location: CLLocation
let phone: String
let description: String
let address: WMSNGAddress
}
func ==(lhs: WMSNGStore, rhs: WMSNGStore) -> Bool {
return lhs.storeId == rhs.storeId &&
lhs.location == rhs.location &&
lhs.phone == rhs.phone &&
lhs.description == rhs.description &&
lhs.address == rhs.address
}
extension WMSNGStore: ELCodable.Decodable {
static func decode(_ json: JSON?) throws -> WMSNGStore {
let store = try WMSNGStore(storeId: json ==> "storeNumber",
location: CLLocation(latitude: json ==> "latitude", longitude: json ==> "longitude"),
phone: json ==> "phone",
description: json ==> "description",
address: json ==> "address"
)
return store
}
func validate() throws -> WMSNGStore {
// Possibly validate the data here
return self
}
}
class NestedErrorTesting: 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 testNestedFailure() {
let json = JSON(bundleClass: NestedErrorTesting.self, filename: "NestedErrorTesting.json")
do {
let store = try WMSNGStore.decode(json)
print(store)
XCTFail("Expected decode call to throw error")
} catch DecodeError.emptyJSON {
print("JSON was empty.")
} catch DecodeError.notFound(let key) {
XCTAssertEqual("address", key)
} catch _ {
XCTFail("Unexpected error. Expected DecodeError.notFound.")
}
}
}
|
mit
|
90593e779549e7d135c08b37cae0c18c
| 26.910714 | 111 | 0.59309 | 4.168 | false | true | false | false |
FrancisBaileyH/Swift-Sociables
|
Sociables/SettingsViewController.swift
|
1
|
4727
|
//
// SettingsViewController.swift
// Socialables
//
// Created by Francis Bailey on 2015-05-03.
//
//
import UIKit
class SettingsViewController: UIViewController {
@IBOutlet weak var girlsDrinkMoreSwitch: UISwitch!
@IBOutlet weak var guysDrinkMoreSwitch: UISwitch!
@IBOutlet weak var deckSizeSlider: UISlider!
@IBOutlet weak var deckSizeLabel: UILabel!
let settings = Settings.sharedInstance
let rm = RuleManager.sharedInstance
var girlDrinksCardIsDefault: CardAndRuleType? = nil
var guyDrinksCardIsDefault: CardAndRuleType? = nil
override func viewDidLoad() {
let initialDeckSize = Float(settings.getDeckSize())
deckSizeSlider.value = initialDeckSize
deckSizeLabel.text = String(stringInterpolationSegment: Int(initialDeckSize))
let bias = settings.getBias()
if checkIfCustomValue() || bias == DeckBias.noBias {
switch bias {
case DeckBias.girlsDrinkMore:
girlsDrinkMoreSwitch.setOn(true, animated: false)
guysDrinkMoreSwitch.setOn(false, animated: false)
break
case DeckBias.guysDrinkMore:
girlsDrinkMoreSwitch.setOn(false, animated: false)
guysDrinkMoreSwitch.setOn(true, animated: false)
break
default:
girlsDrinkMoreSwitch.setOn(false, animated: false)
guysDrinkMoreSwitch.setOn(false, animated: false)
}
}
else {
setAllSwitchesToFalse()
showAlertIfNotDefaultOnSet()
}
}
/*
* Check to see if the cards required for making a gender drink more are default or not.
* If they aren't default we'll want to warn the user and prevent any action from occurring
* on these respective switches
*/
func checkIfCustomValue() -> Bool {
girlDrinksCardIsDefault = rm.getRule(rm.defaultGirlsDrinkCard)
guyDrinksCardIsDefault = rm.getRule(rm.defaultGuysDrinkCard)
if !girlDrinksCardIsDefault!.isDefault || !guyDrinksCardIsDefault!.isDefault {
return false
}
else {
return true
}
}
func setAllSwitchesToFalse() {
guysDrinkMoreSwitch.setOn(false, animated: true)
girlsDrinkMoreSwitch.setOn(false, animated: true)
settings.setBias(DeckBias.noBias, value: true)
}
@IBAction func girlsDrinkMoreSwitchChanged(sender: UISwitch) {
if sender.on {
if !checkIfCustomValue() {
setAllSwitchesToFalse()
showAlertIfNotDefaultOnSet()
return
}
guysDrinkMoreSwitch.setOn(false, animated: true)
settings.setBias(DeckBias.guysDrinkMore, value: false)
settings.setBias(DeckBias.girlsDrinkMore, value: true)
}
else {
settings.setBias(DeckBias.girlsDrinkMore, value: false)
}
}
@IBAction func guysDrinkMoreSwitchChanged(sender: UISwitch) {
if sender.on {
if !checkIfCustomValue() {
setAllSwitchesToFalse()
showAlertIfNotDefaultOnSet()
return
}
girlsDrinkMoreSwitch.setOn(false, animated: true)
settings.setBias(DeckBias.guysDrinkMore, value: true)
settings.setBias(DeckBias.girlsDrinkMore, value: false)
}
else {
settings.setBias(DeckBias.guysDrinkMore, value: false)
}
}
@IBAction func numberSliderDidChange(sender: UISlider) {
let roundedValue = Int(sender.value)
deckSizeLabel.text = String(stringInterpolationSegment: roundedValue)
settings.setDeckSize(roundedValue)
}
/*
* Show an alert when the 6 and 4 card have their own custom values
* as the game relies on those two cards to make girls drink more
* or make guys drink more.
*/
func showAlertIfNotDefaultOnSet() {
let warning = UIAlertController(title: "Custom Rule Found", message: "Cards 4 and 6 need to be set to their default values in order to use the girls/guys drink more setting.", preferredStyle: .Alert)
let OKAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
warning.addAction(OKAction)
self.presentViewController(warning, animated: true, completion: nil)
}
}
|
gpl-3.0
|
493a90129a2efb1a7dfd42474fa1dc89
| 28.72956 | 207 | 0.59615 | 4.708167 | false | false | false | false |
Poligun/NihonngoSwift
|
Nihonngo/WordListViewController.swift
|
1
|
3185
|
//
// WordListViewController.swift
// Nihonngo
//
// Created by ZhaoYuhan on 15/1/6.
// Copyright (c) 2015年 ZhaoYuhan. All rights reserved.
//
import UIKit
class WordListViewController: BaseViewController, UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate {
private var searchBar: UISearchBar!
private var tableView: UITableView!
private var words: [Word]!
var slideViewDelegate: SlideViewDelegate?
private lazy var wordViewController: WordViewController = {
let wordViewController = WordViewController()
return wordViewController
}()
private lazy var fetchWordViewController: FetchWordViewController = {
let fetchWordViewController = FetchWordViewController()
return fetchWordViewController
}()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "单词列表"
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "菜单", style: .Plain, target: self, action: "onMenuButtonClick:")
addRightBarButtonItem("在线查询", onClick: onAddButtonClick)
searchBar = addSearchBar(placeHolder: "输入待查单词或假名")
tableView = addTableView(heightStyle: .Fixed(44.0), cellClasses: WordCell.self)
addConstraints("V:|-0-[searchBar]-0-[tableView]-0-|", "H:|-0-[searchBar]-0-|", "H:|-0-[tableView]-0-|")
}
private func updateWords() {
words = searchBar.text == "" ? DataStore.sharedInstance.allWords : DataStore.sharedInstance.searchWords(searchBar.text)
tableView.reloadData()
}
override func viewWillAppear(animated: Bool) {
updateWords()
}
func onMenuButtonClick(sender: AnyObject) {
slideViewDelegate?.toggleLeftView()
}
func onAddButtonClick(sender: AnyObject) {
if searchBar.text != "" {
fetchWordViewController.setSearchText(searchBar.text)
}
navigationController?.pushViewController(fetchWordViewController, animated: true)
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
updateWords()
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
searchBar.text = ""
searchBar.resignFirstResponder()
updateWords()
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
onAddButtonClick(searchBar)
}
// TableView DataSource & Delegate
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return words.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(WordCell.defaultReuseIdentifier, forIndexPath: indexPath) as WordCell
cell.setWord(words[indexPath.row])
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
wordViewController.word = words[indexPath.row]
navigationController?.pushViewController(wordViewController, animated: true)
}
}
|
mit
|
f016cf0d4bc304791254d2422e4c8758
| 32.457447 | 132 | 0.68744 | 5.250417 | false | false | false | false |
gouyz/GYZBaking
|
baking/Classes/Tool/tool/GYZTool.swift
|
1
|
5036
|
//
// GYZTool.swift
// LazyHuiSellers
// 通用功能
// Created by gouyz on 2016/12/15.
// Copyright © 2016年 gouyz. All rights reserved.
//
import UIKit
import AudioToolbox
import MJRefresh
///小于运算符
func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool
{
switch (lhs, rhs)
{
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
///等于运算符
func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool
{
switch (lhs, rhs)
{
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
class GYZTool: NSObject {
///1.单例
static let shareTool = GYZTool()
private override init() {}
/// 播放声音
///这个只能播放不超过30秒的声音,它支持的文件格式有限,具体的说只有CAF、AIF和使用PCM或IMA/ADPCM数据的WAV文件
/// - Parameter sound: 声音文件名称
class func playAlertSound(sound:String)
{
//声音地址
guard let soundPath = Bundle.main.path(forResource: sound, ofType: nil) else { return }
guard let soundUrl = NSURL(string: soundPath) else { return }
//建立的systemSoundID对象
var soundID:SystemSoundID = 0
//赋值
AudioServicesCreateSystemSoundID(soundUrl, &soundID)
//播放声音
AudioServicesPlaySystemSound(soundID)
}
///MARK -添加上拉/下拉刷新
/// 添加下拉刷新
///
/// - Parameters:
/// - scorllView: 添加下拉刷新的视图
/// - pullRefreshCallBack: 刷新回调
class func addPullRefresh(scorllView : UIScrollView?,pullRefreshCallBack : MJRefreshComponentRefreshingBlock?){
if scorllView == nil || pullRefreshCallBack == nil {
return
}
// weak var weakScrollView = scorllView
let refreshHeader : MJRefreshNormalHeader = MJRefreshNormalHeader.init {
pullRefreshCallBack!()
// if weakScrollView?.mj_footer.isHidden == false {
// weakScrollView?.mj_footer.resetNoMoreData()
// }
}
scorllView?.mj_header = refreshHeader
}
/// 添加上拉刷新
///
/// - Parameters:
/// - scorllView: 添加上拉刷新的视图
/// - loadMoreCallBack: 刷新回调
class func addLoadMore(scorllView : UIScrollView?,loadMoreCallBack : MJRefreshComponentRefreshingBlock?){
if scorllView == nil || loadMoreCallBack == nil {
return
}
let loadMoreFooter = MJRefreshAutoNormalFooter.init {
loadMoreCallBack!()
}
//空数据时,设置文字为空
loadMoreFooter?.setTitle("", for: .idle)
loadMoreFooter?.setTitle("正在为您加载数据", for: .refreshing)
loadMoreFooter?.setTitle("没有更多了~", for: .noMoreData)
// loadMoreFooter?.isAutomaticallyRefresh = false
scorllView?.mj_footer = loadMoreFooter
}
/// 停止下拉刷新
class func endRefresh(scorllView : UIScrollView?){
scorllView?.mj_header.endRefreshing()
}
/// 停止上拉加载
class func endLoadMore(scorllView : UIScrollView?){
scorllView?.mj_footer.endRefreshing()
}
/// 提示没有更多数据的情况
class func noMoreData(scorllView : UIScrollView?){
scorllView?.mj_footer.endRefreshingWithNoMoreData()
}
/// 重置没有更多数据的情况
class func resetNoMoreData(scorllView : UIScrollView?){
scorllView?.mj_footer.resetNoMoreData()
}
/// 拨打电话
///
/// - Parameter phone: 电话号码
class func callPhone(phone: String){
//自动打开拨号页面并自动拨打电话UIApplication.shared.openURL(URL(string: "tel://10086")!)
//有提示
UIApplication.shared.openURL(URL(string: "telprompt://"+phone)!)
}
/// 退出登录时,移除用户信息
class func removeUserInfo(){
userDefaults.removeObject(forKey: kIsLoginTagKey)
userDefaults.removeObject(forKey: "userId")
userDefaults.removeObject(forKey: "phone")
userDefaults.removeObject(forKey: "username")
userDefaults.removeObject(forKey: "signing")
userDefaults.removeObject(forKey: "longitude")
userDefaults.removeObject(forKey: "latitude")
userDefaults.removeObject(forKey: "headImg")
}
///返回图片路径地址
///
/// - Parameter url:
/// - Returns:
class func createImgUrl(url: String?)->URL?{
if url == nil {
return nil
}
return URL.init(string: BaseRequestImgURL + url!)
}
///解析多图的URL
///
/// - Parameter url:
/// - Returns:
class func getImgUrls(url: String?)->[String]?{
if url == nil || (url?.isEmpty)! {
return nil
}
return url?.components(separatedBy: ";")
}
}
|
mit
|
c11722fd9704dab3b53155b14a99fd39
| 26.299401 | 115 | 0.589603 | 4.272727 | false | false | false | false |
danlozano/Requestr
|
Example/TinyApiClientExample/Endpoints.swift
|
1
|
1189
|
//
// Endpoints.swift
// TinyApiClientExample
//
// Created by Daniel Lozano Valdés on 11/30/16.
// Copyright © 2016 danielozano. All rights reserved.
//
import Foundation
enum Endpoints {
static let baseURL = "https://remotelyapi.herokuapp.com"
case login
case signup
case me
case user(userId: String)
case users
case userEvents
var fullPath: String {
let path: String
switch self {
case .login:
path = "/login"
case .signup:
path = "/signup"
case .me:
path = "/api/me"
case .user(let userId):
path = "/api/users/\(userId)"
case .users:
path = "/api/users"
case .userEvents:
path = "/api/users/events"
}
return Endpoints.baseURL + path
}
var rootKey: String? {
switch self {
case .login:
return nil
case .signup:
return nil
case .me:
return nil
case .user(_):
return nil
case .users:
return "users"
case .userEvents:
return "events"
}
}
}
|
mit
|
82dd0a4be6ac54daafcae93e8a552b0b
| 19.465517 | 60 | 0.504634 | 4.300725 | false | false | false | false |
badoo/Chatto
|
Chatto/sources/ChatController/ChatMessages/New/CollectionUpdateProvider.swift
|
1
|
4827
|
//
// The MIT License (MIT)
//
// Copyright (c) 2015-present Badoo Trading Limited.
//
// 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
// TODO: Rename
public final class CollectionUpdateProvider: CollectionUpdateProviderProtocol {
// TODO: Stop sharing configuration with adapter
public typealias Configuration = NewChatMessageCollectionAdapter.Configuration
// MARK: - Private properties
private let configuration: Configuration
private let chatItemPresenterFactory: ChatItemPresenterFactoryProtocol
private let chatMessagesViewModel: ChatMessagesViewModelProtocol
private let chatItemsDecorator: ChatItemsDecoratorProtocol
// MARK: - State
private var isFirstUpdate: Bool = true
private weak var collectionView: UICollectionView?
// MARK: - Instantiation
public init(configuration: Configuration,
chatItemsDecorator: ChatItemsDecoratorProtocol,
chatItemPresenterFactory: ChatItemPresenterFactoryProtocol,
chatMessagesViewModel: ChatMessagesViewModelProtocol) {
self.configuration = configuration
self.chatItemsDecorator = chatItemsDecorator
self.chatItemPresenterFactory = chatItemPresenterFactory
self.chatMessagesViewModel = chatMessagesViewModel
}
// MARK: - CellPresenterProviderProtocol
public func updateCollection(old: ChatItemCompanionCollection) -> ChatItemCompanionCollection {
let decoratedNewItems = self.chatItemsDecorator.decorateItems(self.chatMessagesViewModel.chatItems)
// TODO: Move this logic somewhere else
let companionItems: [ChatItemCompanion] = decoratedNewItems.map { decoratedChatItem in
ChatItemCompanion(uid: decoratedChatItem.uid,
chatItem: decoratedChatItem.chatItem,
presenter: self.presenter(for: decoratedChatItem, from: old),
decorationAttributes: decoratedChatItem.decorationAttributes)
}
return ChatItemCompanionCollection(items: companionItems)
}
public func setup(in collectionView: UICollectionView) {
self.collectionView = collectionView
if self.configuration.isRegisteringPresentersAutomatically {
self.chatItemPresenterFactory.configure(withCollectionView: collectionView)
}
}
// TODO: Subscribe for chat data source updates
private func didUpdateDataSource() {
guard !self.configuration.isRegisteringPresentersAutomatically
&& self.isFirstUpdate,
let collectionView = self.collectionView else { return }
self.chatItemPresenterFactory.configure(withCollectionView: collectionView)
self.isFirstUpdate = false
}
// MARK: - Private methods
private func presenter(for decoratedItem: DecoratedChatItem, from oldItems: ChatItemCompanionCollection) -> ChatItemPresenterProtocol {
/*
We use an assumption, that message having a specific messageId never changes its type.
If such changes has to be supported, then generation of changes has to suppport reloading items.
Otherwise, updateVisibleCells may try to update the existing cells with new presenters which aren't able to work with another types.
*/
guard let oldChatItemCompanion = oldItems[decoratedItem.uid] ?? oldItems[decoratedItem.chatItem.uid],
oldChatItemCompanion.chatItem.type == decoratedItem.chatItem.type,
oldChatItemCompanion.presenter.isItemUpdateSupported else {
return self.chatItemPresenterFactory.createChatItemPresenter(decoratedItem.chatItem)
}
oldChatItemCompanion.presenter.update(with: decoratedItem.chatItem)
return oldChatItemCompanion.presenter
}
}
|
mit
|
fec3a68db60fde76cf3a1653172eb3f9
| 43.694444 | 144 | 0.737725 | 5.554661 | false | true | false | false |
AlphaJian/PaperCalculator
|
PaperCalculator/PaperCalculator/Views/Create/EditSettingCell.swift
|
1
|
4193
|
//
// NoneSettingCell.swift
// PaperCalculator
//
// Created by appledev018 on 9/29/16.
// Copyright © 2016 apple. All rights reserved.
//
//
// QuestionTableViewCell.swift
// PaperCalculator
//
// Created by Jian Zhang on 9/28/16.
// Copyright © 2016 apple. All rights reserved.
//
import UIKit
class EditSettingCell: UITableViewCell {
var model = DataManager.shareManager.paperModel
var index = IndexPath()
var btnHandler : ButtonTouchUpBlock!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override init(style : UITableViewCellStyle, reuseIdentifier : String?)
{
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func initUI(questionNum: Int, markNum: Int, index : IndexPath){
self.frame.size.height = 150
self.index = index
for i in 0...questionNum - 1 {
let questionLabel = UILabel(frame: CGRect(x: 20, y: 20 + 70 * CGFloat(i) , width: 100, height: 50))
questionLabel.text = "第 \(i+1) 题"
questionLabel.textColor = lightBlue
self.contentView.addSubview(questionLabel)
let typeSwitch = UISwitch(frame: CGRect(x: 225, y: 25 + 70 * CGFloat(i), width: 50, height: 50))
typeSwitch.onTintColor = lightBlue
typeSwitch.transform.scaledBy(x: 0.75, y: 0.75)
typeSwitch.isOn = ((model.sectionQuestionArr[index.section] as SectionQuestionModel).cellQuestionArr[i] as CellQuestionModel).questionStyle == QuestionStyle.multiScore
typeSwitch.tag = i + 10
typeSwitch.addTarget(self, action: #selector(self.typeChanged(_:)), for: UIControlEvents.valueChanged)
self.contentView.addSubview(typeSwitch)
let markNumView = NumView(frame: CGRect(x: 100, y: 20 + 70 * CGFloat(i) , width: 100, height: 50))
markNumView.initUI(num: markNum)
markNumView.index = i
self.contentView.addSubview(markNumView)
let tempArr = (model.sectionQuestionArr[index.section] as SectionQuestionModel).cellQuestionArr
markNumView.changeNumHandler = {(num, index)-> Void in
(tempArr![index] as CellQuestionModel).score = Float(num)
(tempArr![index] as CellQuestionModel).realScore = Float(num)
}
}
let button = UIButton(type: .custom)
button.setTitle("确定", for: .normal)
button.titleLabel?.font = mediumFont
button.backgroundColor = lightRed
button.layer.cornerRadius = 10
button.frame = CGRect(x: 300, y: 20 + 70 * CGFloat(questionNum - 1), width: self.frame.height / 3, height: self.frame.height / 3)
button.addTarget(self, action: #selector(self.confirmTaped), for: UIControlEvents.touchUpInside)
self.contentView.addSubview(button)
}
func typeChanged(_ sender : UISwitch){
if sender.isOn {
((model.sectionQuestionArr[index.section] as SectionQuestionModel).cellQuestionArr[sender.tag - 10] as CellQuestionModel).questionStyle = QuestionStyle.multiScore
} else {
((model.sectionQuestionArr[index.section] as SectionQuestionModel).cellQuestionArr[sender.tag - 10] as CellQuestionModel).questionStyle = QuestionStyle.yesOrNo
}
}
func confirmTaped(){
(model.sectionQuestionArr[index.section] as SectionQuestionModel).editStatus = QuestionStatus.finish
if btnHandler != nil {
btnHandler()
}
}
func clearCell(){
for view in self.contentView.subviews {
view.removeFromSuperview()
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
gpl-3.0
|
f326834d7da65813fadfdd967f99b4b0
| 32.733871 | 179 | 0.613196 | 4.531961 | false | false | false | false |
AnthonyOliveri/bms-clientsdk-swift-push
|
NotificationInterceptor/NotificationService.swift
|
2
|
1248
|
//
// NotificationService.swift
// NotificationInterceptor
//
// Created by Jim Dickens on 12/13/16.
// Copyright © 2016 IBM Corp. All rights reserved.
//
#if swift(>=3.0)
import UserNotifications
import BMSPush
class NotificationService:BMSPushRichPushNotificationOptions {
var contentHandler: ((UNNotificationContent) -> Void)?
var bestAttemptContent: UNMutableNotificationContent?
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
BMSPushRichPushNotificationOptions.didReceive(request, withContentHandler: contentHandler)
}
override func serviceExtensionTimeWillExpire() {
// Called just before the extension will be terminated by the system.
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
contentHandler(bestAttemptContent)
}
}
}
#endif
|
apache-2.0
|
bc74b3ba5d7728cf4e3fe726c99a3ed2
| 35.676471 | 142 | 0.736167 | 5.566964 | false | false | false | false |
WhisperSystems/Signal-iOS
|
SignalServiceKit/src/Messages/Attachments/TSAttachmentStream+SDS.swift
|
1
|
4706
|
//
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
import GRDB
import SignalCoreKit
// NOTE: This file is generated by /Scripts/sds_codegen/sds_generate.py.
// Do not manually edit it, instead run `sds_codegen.sh`.
// MARK: - Typed Convenience Methods
@objc
public extension TSAttachmentStream {
// NOTE: This method will fail if the object has unexpected type.
class func anyFetchAttachmentStream(uniqueId: String,
transaction: SDSAnyReadTransaction) -> TSAttachmentStream? {
assert(uniqueId.count > 0)
guard let object = anyFetch(uniqueId: uniqueId,
transaction: transaction) else {
return nil
}
guard let instance = object as? TSAttachmentStream else {
owsFailDebug("Object has unexpected type: \(type(of: object))")
return nil
}
return instance
}
// NOTE: This method will fail if the object has unexpected type.
func anyUpdateAttachmentStream(transaction: SDSAnyWriteTransaction, block: (TSAttachmentStream) -> Void) {
anyUpdate(transaction: transaction) { (object) in
guard let instance = object as? TSAttachmentStream else {
owsFailDebug("Object has unexpected type: \(type(of: object))")
return
}
block(instance)
}
}
}
// MARK: - SDSSerializer
// The SDSSerializer protocol specifies how to insert and update the
// row that corresponds to this model.
class TSAttachmentStreamSerializer: SDSSerializer {
private let model: TSAttachmentStream
public required init(model: TSAttachmentStream) {
self.model = model
}
// MARK: - Record
func asRecord() throws -> SDSRecord {
let id: Int64? = nil
let recordType: SDSRecordType = .attachmentStream
let uniqueId: String = model.uniqueId
// Base class properties
let albumMessageId: String? = model.albumMessageId
let attachmentSchemaVersion: UInt = model.attachmentSchemaVersion
let attachmentType: TSAttachmentType = model.attachmentType
let byteCount: UInt32 = model.byteCount
let caption: String? = model.caption
let contentType: String = model.contentType
let encryptionKey: Data? = model.encryptionKey
let isDownloaded: Bool = model.isDownloaded
let serverId: UInt64 = model.serverId
let sourceFilename: String? = model.sourceFilename
// Subclass properties
let cachedAudioDurationSeconds: Double? = archiveOptionalNSNumber(model.cachedAudioDurationSeconds, conversion: { $0.doubleValue })
let cachedImageHeight: Double? = archiveOptionalNSNumber(model.cachedImageHeight, conversion: { $0.doubleValue })
let cachedImageWidth: Double? = archiveOptionalNSNumber(model.cachedImageWidth, conversion: { $0.doubleValue })
let creationTimestamp: Double? = archiveOptionalDate(model.creationTimestamp)
let digest: Data? = model.digest
let isUploaded: Bool? = model.isUploaded
let isValidImageCached: Bool? = archiveOptionalNSNumber(model.isValidImageCached, conversion: { $0.boolValue })
let isValidVideoCached: Bool? = archiveOptionalNSNumber(model.isValidVideoCached, conversion: { $0.boolValue })
let lazyRestoreFragmentId: String? = nil
let localRelativeFilePath: String? = model.localRelativeFilePath
let mediaSize: Data? = nil
let mostRecentFailureLocalizedText: String? = nil
let pointerType: TSAttachmentPointerType? = nil
let shouldAlwaysPad: Bool? = model.shouldAlwaysPad
let state: TSAttachmentPointerState? = nil
return AttachmentRecord(id: id, recordType: recordType, uniqueId: uniqueId, albumMessageId: albumMessageId, attachmentSchemaVersion: attachmentSchemaVersion, attachmentType: attachmentType, byteCount: byteCount, caption: caption, contentType: contentType, encryptionKey: encryptionKey, isDownloaded: isDownloaded, serverId: serverId, sourceFilename: sourceFilename, cachedAudioDurationSeconds: cachedAudioDurationSeconds, cachedImageHeight: cachedImageHeight, cachedImageWidth: cachedImageWidth, creationTimestamp: creationTimestamp, digest: digest, isUploaded: isUploaded, isValidImageCached: isValidImageCached, isValidVideoCached: isValidVideoCached, lazyRestoreFragmentId: lazyRestoreFragmentId, localRelativeFilePath: localRelativeFilePath, mediaSize: mediaSize, mostRecentFailureLocalizedText: mostRecentFailureLocalizedText, pointerType: pointerType, shouldAlwaysPad: shouldAlwaysPad, state: state)
}
}
|
gpl-3.0
|
3998e957ef5b661a25d0330004860c07
| 49.06383 | 913 | 0.711432 | 5.126362 | false | false | false | false |
sammy0025/SST-Announcer
|
SST Announcer/View Controllers/MainTableViewController.swift
|
1
|
13171
|
//
// MainTableViewController.swift
// SST Announcer
//
// Created by Pan Ziyue on 22/11/16.
// Copyright © 2016 FourierIndustries. All rights reserved.
//
import UIKit
import SGNavigationProgress
import JGProgressHUD
class MainTableViewController: UITableViewController {
// MARK: - Variables
// MARK: UI Assistants
/// Tracks the state of whether or not to collapse the detail view controller
fileprivate var collapseDetailViewController = true
/// Progress tracking for UI only, loading will not actually be cancelled
fileprivate var progressCancelled = false
/// Computed property to check if the search controller is active
fileprivate var searchControllerActive: Bool {
return searchController.isActive && searchController.searchBar.text!.characters.count > 0
}
// MARK: Feeder related variables
fileprivate var feeder = Feeder()
fileprivate var filteredFeeds: [FeedItem] = []
/// A `FeedItem` object that is pushed from push notifications, automatically
/// retrieving it from AppDelegate
fileprivate var pushedFeedItem: FeedItem?
// MARK: UI
fileprivate var searchController: UISearchController = {
let searchCtrl = UISearchController(searchResultsController: nil)
searchCtrl.hidesNavigationBarDuringPresentation = false
searchCtrl.dimsBackgroundDuringPresentation = false
searchCtrl.searchBar.barStyle = .default
return searchCtrl
}()
let pushHud: JGProgressHUD = {
let hud = JGProgressHUD(style: .dark)!
hud.interactionType = .blockTouchesOnHUDView
hud.textLabel.text = "Opening Push Notification..."
return hud
}()
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Initialize necessary push notification delegates
// swiftlint:disable:next force_cast
let splitViewController = self.splitViewController! as! SplitViewController
splitViewController.pushDelegate = self
// UI
splitViewController.delegate = self
splitViewController.preferredDisplayMode = .automatic
// Set navigation bar to the search bar and set delegates
navigationItem.titleView = searchController.searchBar
//searchController.delegate = self
searchController.searchResultsUpdater = self
//searchController.searchBar.delegate = self
// Add refresh control
refreshControl = UIRefreshControl()
// swiftlint:disable:next line_length
refreshControl?.addTarget(self, action: #selector(refreshTriggered(sender:)), for: .valueChanged)
// Start loading feeds asynchronously
feeder.delegate = self
feeder.getCachedFeeds()
feeder.requestFeedsAsynchronous()
// Add peek and pop
if #available(iOS 9.0, *) {
if traitCollection.forceTouchCapability == .available {
registerForPreviewing(with: self, sourceView: view)
}
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
progressCancelled = true
navigationController!.cancelSGProgress()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Objective-C selectors and helpers
fileprivate func displayError(_ error: AnnouncerError) {
DispatchQueue.main.async {
let errorHud = JGProgressHUD(style: .dark)!
errorHud.indicatorView = JGProgressHUDErrorIndicatorView()
errorHud.interactionType = .blockTouchesOnHUDView
switch error.errorType {
case .networkError:
errorHud.textLabel.text = "Network error occured"
errorHud.detailTextLabel.text = error.localizedDescription
case .parseError:
errorHud.textLabel.text = "Parsing error occured"
case .unwrapError:
errorHud.textLabel.text = "Internal error occured"
default:
errorHud.textLabel.text = "Unknown error occured"
let errorMessage = "Feed failed parsing and switched to default case"
let error = AnnouncerError(type: .unknownError, errorDescription: errorMessage)
error.relayTelemetry()
}
errorHud.show(in: self.splitViewController!.view)
errorHud.dismiss(afterDelay: 2)
}
}
@objc private func refreshTriggered(sender: Any) {
feeder.requestFeedsAsynchronous()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchControllerActive {
return filteredFeeds.count
}
return feeder.feeds.count
}
// swiftlint:disable:next line_length
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// swiftlint:disable:next line_length
guard let cell = tableView.dequeueReusableCell(withIdentifier: "postcell", for: indexPath) as? PostTableViewCell else {
fatalError("Unable to cast tableView's cell as a PostTableViewCell!")
}
// Configure the cell...
var currentFeedObject: FeedItem!
if searchControllerActive {
currentFeedObject = filteredFeeds[indexPath.row]
} else {
currentFeedObject = feeder.feeds[indexPath.row]
}
if currentFeedObject.title.characters.count < 1 {
cell.titleLabel.text = "<No Title>"
} else {
cell.titleLabel.text = currentFeedObject.title
}
cell.dateLabel.text = currentFeedObject.date.decodeToTimeAgo()
cell.descriptionLabel.text = currentFeedObject.strippedHtmlContent
cell.dateWidthConstraint.constant = cell.dateLabel.intrinsicContentSize.width
cell.readIndicator.isHidden = currentFeedObject.read
return cell
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
self.splitViewController?.view.endEditing(false)
if segue.identifier == "presentPostFromMain" {
if let navController = segue.destination as? UINavigationController {
guard let postViewController = navController.topViewController as? PostViewController else {
fatalError("Unable to unwrap navController topview as PostViewController")
}
if let selectedIndexPath = tableView.indexPathForSelectedRow {
if searchControllerActive {
let selectedPost = filteredFeeds[selectedIndexPath.row]
postViewController.feedObject = selectedPost
} else {
let selectedPost = feeder.feeds[selectedIndexPath.row]
postViewController.feedObject = selectedPost
selectedPost.read = true
DispatchQueue.main.async {
self.tableView.reloadRows(at: [selectedIndexPath], with: .none)
}
// Refresh cache as the user has read a post
feeder.setCachedFeeds()
}
// Conditionally pass the current navigation controller to the secondary view
let viewIsCR = splitViewController!.traitCollection.isCR
let viewIsCC = splitViewController!.traitCollection.isCC
if viewIsCR || viewIsCC {
postViewController.originalNavigationController = navigationController
}
}
}
}
}
}
// MARK: - UISplitViewControllerDelegate
extension MainTableViewController: UISplitViewControllerDelegate {
// swiftlint:disable:next line_length
func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController: UIViewController, onto primaryViewController: UIViewController) -> Bool {
return collapseDetailViewController
}
}
// MARK: - SplitViewControllerPushDelegate
extension MainTableViewController: SplitViewControllerPushDelegate {
/*
Please take note: there is a complicated chain of data passing here and I will explain it here
This is the messaging mechanism for passing data from the push notification to the
MainTableViewController
AppDelegate > SplitViewController > SplitViewControllerPushDelegate > MainTableViewController
Reason: This piece of code is run on a seperate thread that is different from the Main Thread.
As a result, I cannot synchronously pass the data by setting some global property
(which is bad practice in the first place)
As such, a more complex messaging system was devised, based mostly on property observers and
protocol/delegates was made to ensure relative robustness compaired to a global state.
Steps:
1. AppDelegate retrieves the feed item, assigns it as a property of the SplitViewController
2. SplitViewController has a property observer on pushedFeedItem, which triggers a delegate call
3. The MainTableViewController receives this delegate call, and initiates the segue <-
*/
func feedPushed() {
// swiftlint:disable:next force_cast
pushedFeedItem = (self.splitViewController as! SplitViewController).pushedFeedItem
// Show HUD
pushHud.show(in: self.splitViewController!.view)
if !feeder.loading {
// Reload from web just in case
feeder.requestFeedsAsynchronous()
}
}
}
// MARK: - FeederDelegate
extension MainTableViewController: FeederDelegate {
func feedLoadedPercent(_ percent: Float) {
if !progressCancelled {
let percentageInHundred = percent * 100
DispatchQueue.main.async {
self.navigationController!.setSGProgressPercentage(percentageInHundred)
}
}
}
func feedLoadedFromCache() {
}
func feedFinishedParsing(withFeedArray feedArray: [FeedItem]?, error: Error?) {
progressCancelled = false
DispatchQueue.main.async {
if self.refreshControl!.isRefreshing {
self.refreshControl!.endRefreshing()
}
if self.pushedFeedItem != nil {
self.pushHud.dismiss()
}
}
if let error = error as? AnnouncerError {
// Display error here
displayError(error)
} else {
DispatchQueue.main.async {
self.tableView.reloadData()
// Display push notification, if there is a push notification
if let feedItem = self.pushedFeedItem {
// Cycle through all feeds to find and select that post
var successfullyOpenedPush = false
for (index, element) in self.feeder.feeds.elements.enumerated() {
if element.link == feedItem.link {
successfullyOpenedPush = true
let indexPath = IndexPath(row: index, section: 0)
self.tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
self.performSegue(withIdentifier: "presentPostFromMain", sender: self)
}
}
if !successfullyOpenedPush {
// Show error
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
let errorHud = JGProgressHUD(style: .dark)!
errorHud.indicatorView = JGProgressHUDErrorIndicatorView()
errorHud.textLabel.text = "Unable to open push"
errorHud.interactionType = .blockTouchesOnHUDView
errorHud.show(in: self.splitViewController!.view)
errorHud.dismiss(afterDelay: 2)
}
}
}
self.pushedFeedItem = nil //reset the variable
}
}
}
}
// MARK: - UISearch-related delegates
extension MainTableViewController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
filter(forSearchText: searchController.searchBar.text!)
}
private func filter(forSearchText searchText: String) {
filteredFeeds = feeder.feeds.filter { feed in
return feed.title.lowercased().contains(searchText.lowercased())
}.elements
tableView.reloadData()
}
}
// MARK: - UIViewcontrollerPreviewingDelegate
@available(iOS 9.0, *) //only available on iOS 9 and above
extension MainTableViewController: UIViewControllerPreviewingDelegate {
// swiftlint:disable line_length
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
guard let indexPath = tableView.indexPathForRow(at: location) else { return nil }
guard let cell = tableView.cellForRow(at: indexPath) else { return nil }
guard let detailVcNavController = storyboard!.instantiateViewController(withIdentifier: "PostNavigationController") as? UINavigationController else { return nil }
guard let detailVc = detailVcNavController.topViewController as? PostViewController else { return nil }
if searchControllerActive {
detailVc.feedObject = filteredFeeds[indexPath.row]
} else {
detailVc.feedObject = feeder.feeds[indexPath.row]
}
let viewIsCR = splitViewController!.traitCollection.isCR
let viewIsCC = splitViewController!.traitCollection.isCC
if viewIsCR || viewIsCC {
detailVc.originalNavigationController = navigationController
}
previewingContext.sourceRect = cell.frame
return detailVcNavController
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
show(viewControllerToCommit, sender: self)
}
// swiftlint:enable line_length
}
|
gpl-2.0
|
7563816e0fe38ef0247e753962554fbd
| 35.381215 | 189 | 0.717464 | 5.110594 | false | false | false | false |
asurinsaka/swift_examples_2.1
|
QRCode/QRCode/AztecImageView.swift
|
1
|
1818
|
//
// AztecImageView.swift
// QRCode
//
// Created by larryhou on 23/12/2015.
// Copyright © 2015 larryhou. All rights reserved.
//
import Foundation
import UIKit
@IBDesignable
class AztecImageView:UIImageView
{
private static let DEFAULT_MESSAGE = "larryhou"
private var ib_inputMessage = AztecImageView.DEFAULT_MESSAGE
private var ib_inputCompactStyle = false
@IBInspectable
var inputMessage:String
{
get {return ib_inputMessage}
set
{
ib_inputMessage = newValue == "" ? AztecImageView.DEFAULT_MESSAGE : newValue
drawAztecImage()
}
}
@IBInspectable
var inputCompactStyle:Bool
{
get {return ib_inputCompactStyle}
set
{
ib_inputCompactStyle = newValue
drawAztecImage()
}
}
func drawAztecImage()
{
let filter = CIFilter(name: "CIAztecCodeGenerator")
let data = NSString(string: inputMessage).dataUsingEncoding(NSUTF8StringEncoding)
filter?.setValue(data, forKey: "inputMessage")
filter?.setValue(inputCompactStyle, forKey: "inputCompactStyle")
let image = (filter?.outputImage)!
UIGraphicsBeginImageContext(frame.size)
let context = UIGraphicsGetCurrentContext()
CGContextSetInterpolationQuality(context, .None)
let cgImage = CIContext().createCGImage(image, fromRect: image.extent)
CGContextDrawImage(context, CGContextGetClipBoundingBox(context), cgImage)
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.image = scaledImage
}
override func prepareForInterfaceBuilder()
{
drawAztecImage()
}
}
|
mit
|
68f8a47076e5c298102716c92596e3cc
| 25.333333 | 89 | 0.637314 | 5.423881 | false | false | false | false |
wangyun-hero/sinaweibo-with-swift
|
sinaweibo/Classes/View/Discover/Controller/WYDiscoverTableViewController.swift
|
1
|
3420
|
//
// WYDiscoverTableViewController.swift
// sinaweibo
//
// Created by 王云 on 16/8/29.
// Copyright © 2016年 王云. All rights reserved.
//
import UIKit
class WYDiscoverTableViewController: WYVisitorViewController {
override func viewDidLoad() {
super.viewDidLoad()
if userLogin == false {
visitorView.setvisitorViewInfo(imageName: "visitordiscover_image_message", message: "登录后,最新、最热微博尽在掌握,不再会与实事潮流擦肩而过")
return
}
setupUI()
}
func setupUI () {
//创建一个WYDiscoverSearchView类型的button
let searchView = WYDiscoverSearchView.searchView()
searchView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 30)
//添加到discovervc的view上
navigationItem.titleView = searchView
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> 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, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .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, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> 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 prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
78a3e55636ef548f499d861ce78f721d
| 30.40566 | 136 | 0.656353 | 5.036309 | false | false | false | false |
sgl0v/MSTumblrMenu
|
MSTumblrMenu/MSTumblrMenuViewController.swift
|
1
|
6046
|
//
// MSTumblrMenuViewController.swift
// MSTumblrMenu
//
// Created by Maksym Shcheglov on 09/07/15.
// Copyright (c) 2015 Maksym Shcheglov. All rights reserved.
//
import UIKit
protocol MSTumblrMenuViewControllerDataSource: NSObjectProtocol {
func tumblrMenuViewController(tumblrMenuViewController: MSTumblrMenuViewController, numberOfRowsInSection section: Int) -> Int
func numberOfSectionsInTumblrMenuViewController(tumblrMenuViewController: MSTumblrMenuViewController) -> Int
func tumblrMenuViewController(tumblrMenuViewController: MSTumblrMenuViewController, itemImageForRowAtIndexPath indexPath: NSIndexPath) -> UIImage?
func tumblrMenuViewController(tumblrMenuViewController: MSTumblrMenuViewController, itemTitleForRowAtIndexPath indexPath: NSIndexPath) -> String?
}
protocol MSTumblrMenuViewControllerDelegate: NSObjectProtocol {
func tumblrMenuViewController(tumblrMenuViewController: MSTumblrMenuViewController, didSelectRowAtIndexPath indexPath: NSIndexPath)
}
/**
Defines the menu animation type.
- None: No animattion.
- Show: Animate the menu items appearance.
- Hide: Animate the menu items appearance.
*/
enum MSTumblrMenuAnimation: UInt {
case None, Show, Hide
}
/**
The `MSTumblrMenuViewController` class represents a view controller whose content consists of a tumblr menu.
*/
class MSTumblrMenuViewController: UICollectionViewController {
weak var dataSource: MSTumblrMenuViewControllerDataSource?
weak var delegate: MSTumblrMenuViewControllerDelegate?
private static let kMenuCellIdentifier = "MenuCellIdentifier"
private let menuTransitioningDelegate = MSTumblrMenuTransitioningDelegate()
private var animationType = MSTumblrMenuAnimation.None
override init(collectionViewLayout layout: UICollectionViewLayout) {
super.init(collectionViewLayout: layout)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
self.collectionView?.backgroundColor = UIColor(red: 45.0/255.0, green: 68.0/255.0, blue: 94.0/255.0, alpha: 1.0)
self.modalPresentationStyle = .Custom
self.transitioningDelegate = self.menuTransitioningDelegate
}
override func viewDidLoad() {
self.collectionView?.registerClass(MSTumblrMenuCell.self, forCellWithReuseIdentifier: MSTumblrMenuViewController.kMenuCellIdentifier)
}
func show() {
self.animationType = .Show
self.collectionView!.reloadData()
}
func hide() {
self.animationType = .Hide
self.collectionView!.reloadData()
}
func completeAnimation() {
self.animationType = .None
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.collectionView!.reloadData()
}
// MARK: UICollectionViewControllerDataSource methods
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return self.dataSource!.numberOfSectionsInTumblrMenuViewController(self)
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.dataSource!.tumblrMenuViewController(self, numberOfRowsInSection: section)
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let menuCell = collectionView.dequeueReusableCellWithReuseIdentifier(MSTumblrMenuViewController.kMenuCellIdentifier, forIndexPath: indexPath) as! MSTumblrMenuCell
menuCell.image = self.dataSource?.tumblrMenuViewController(self, itemImageForRowAtIndexPath: indexPath)
menuCell.title = self.dataSource?.tumblrMenuViewController(self, itemTitleForRowAtIndexPath: indexPath)
menuCell.addAnimation(animation(forCell: menuCell, indexPath:indexPath))
return menuCell
}
// MARK: UICollectionViewControllerDelegate methods
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
self.delegate?.tumblrMenuViewController(self, didSelectRowAtIndexPath: indexPath)
}
// MARK: Private
private func animation(forCell cell: MSTumblrMenuCell, indexPath: NSIndexPath) -> MSTumblrMenuCellAnimation? {
let delayInterval = MSTumblrMenuCellAnimationConstants.delay
let numberOfSections = self.dataSource!.numberOfSectionsInTumblrMenuViewController(self)
let numberOfRows = self.dataSource!.tumblrMenuViewController(self, numberOfRowsInSection: indexPath.section)
var delayInSeconds = Double(indexPath.section) * Double(numberOfRows) * delayInterval
if (indexPath.row == 0) {
delayInSeconds += delayInterval
} else if (indexPath.row == numberOfRows - 1) {
delayInSeconds += 2.0 * delayInterval
}
let offset = CGRectGetHeight(self.collectionView!.bounds) / 2
switch self.animationType {
case .Show:
return MSTumblrMenuCellAnimation(delay: delayInSeconds, initialAction: { cell in
cell.layer.transform = CATransform3DMakeTranslation(0, offset + CGFloat(indexPath.section) * 200.0, 0)
cell.layer.opacity = 0.0
}, animationAction: { cell in
cell.layer.transform = CATransform3DIdentity
cell.layer.opacity = 1.0
})
case .Hide:
return MSTumblrMenuCellAnimation(delay: delayInSeconds, initialAction: { cell in
cell.layer.transform = CATransform3DIdentity
cell.layer.opacity = 1.0
}, animationAction: { cell in
cell.layer.transform = CATransform3DMakeTranslation(0, -(offset + CGFloat(numberOfSections - indexPath.section) * 200.0), 0)
cell.layer.opacity = 0.0
})
default:
return nil
}
}
}
|
mit
|
7551cf4d010d18b28efd0efb1a3e06ec
| 40.129252 | 170 | 0.724942 | 5.31283 | false | false | false | false |
anpavlov/swiftperl
|
Tests/LinuxMain.swift
|
1
|
318
|
import XCTest
@testable import PerlTests
var tests = [XCTestCaseEntry]()
tests += [testCase(EmbedTests.allTests)]
tests += [testCase(ConvertFromPerlTests.allTests)]
tests += [testCase(ConvertToPerlTests.allTests)]
tests += [testCase(ObjectTests.allTests)]
tests += [testCase(BenchmarkTests.allTests)]
XCTMain(tests)
|
mit
|
1902881c42537300b98e30f585e90623
| 27.909091 | 50 | 0.779874 | 3.741176 | false | true | false | false |
mownier/pyrobase
|
PyrobaseTests/PyroEventSourceSessionProviderTest.swift
|
1
|
1625
|
//
// PyroEventSourceSessionProviderTest.swift
// Pyrobase
//
// Created by Mounir Ybanez on 23/06/2017.
// Copyright © 2017 Ner. All rights reserved.
//
import XCTest
@testable import Pyrobase
class PyroEventSourceSessionProviderTest: XCTestCase {
func testCreate() {
let provider = PyroEventSourceSessionProvider.create()
XCTAssertEqual(provider.headers.count, 1)
let accept = provider.headers["Accept"]
XCTAssertNotNil(accept)
XCTAssertEqual(accept!, "text/event-stream")
}
func testCreateSession() {
let delegate = URLSessionDataDelegateMock()
let provider = PyroEventSourceSessionProvider.create()
var session = provider.createSession(for: delegate, lastEventID: "")
XCTAssertNotNil(session.configuration.httpAdditionalHeaders)
XCTAssertEqual(session.configuration.httpAdditionalHeaders as! [String: String], provider.headers)
XCTAssertEqual(session.configuration.timeoutIntervalForRequest, TimeInterval(INT_MAX))
XCTAssertEqual(session.configuration.timeoutIntervalForResource, TimeInterval(INT_MAX))
XCTAssertTrue(session.delegate is URLSessionDataDelegateMock)
XCTAssertNil(session.configuration.httpAdditionalHeaders!["Last-Event-Id"])
let lastEventId = "12345"
session = provider.createSession(for: delegate, lastEventID: lastEventId)
XCTAssertNotNil(session.configuration.httpAdditionalHeaders!["Last-Event-Id"])
XCTAssertEqual(session.configuration.httpAdditionalHeaders!["Last-Event-Id"] as! String, lastEventId)
}
}
|
mit
|
fcc09a2f592c90be315cac9cc79a7e1c
| 40.641026 | 109 | 0.727217 | 5.171975 | false | true | false | false |
hejunbinlan/LTMorphingLabel
|
LTMorphingLabel/LTMorphingLabel+Sparkle.swift
|
5
|
5347
|
//
// LTMorphingLabel+Sparkle.swift
// https://github.com/lexrus/LTMorphingLabel
//
// The MIT License (MIT)
// Copyright (c) 2015 Lex Tang, http://lexrus.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the “Software”), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
extension LTMorphingLabel {
private func maskedImageForCharLimbo(charLimbo: LTCharacterLimbo, withProgress progress: CGFloat) -> (UIImage, CGRect) {
let maskedHeight = charLimbo.rect.size.height * max(0.01, progress)
let maskedSize = CGSizeMake( charLimbo.rect.size.width, maskedHeight)
UIGraphicsBeginImageContextWithOptions(maskedSize, false, UIScreen.mainScreen().scale)
let rect = CGRectMake(0, 0, charLimbo.rect.size.width, maskedHeight)
String(charLimbo.char).drawInRect(rect, withAttributes: [
NSFontAttributeName: self.font,
NSForegroundColorAttributeName: self.textColor
])
let newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
let newRect = CGRectMake(
charLimbo.rect.origin.x,
charLimbo.rect.origin.y,
charLimbo.rect.size.width,
maskedHeight)
return (newImage, newRect)
}
func SparkleLoad() {
startClosures["Sparkle\(LTMorphingPhaseStart)"] = {
self.emitterView.removeAllEmitters()
}
progressClosures["Sparkle\(LTMorphingPhaseManipulateProgress)"] = {
(index: Int, progress: Float, isNewChar: Bool) in
if !isNewChar {
return min(1.0, max(0.0, progress))
}
let j = Float(sin(Float(index))) * 1.5
return min(1.0, max(0.0001, progress + self.morphingCharacterDelay * j))
}
effectClosures["Sparkle\(LTMorphingPhaseDisappear)"] = {
(char:Character, index: Int, progress: Float) in
return LTCharacterLimbo(
char: char,
rect: self.previousRects[index],
alpha: CGFloat(1.0 - progress),
size: self.font.pointSize,
drawingProgress: 0.0)
}
effectClosures["Sparkle\(LTMorphingPhaseAppear)"] = {
(char:Character, index: Int, progress: Float) in
if char != " " {
let rect = self.newRects[index]
let emitterPosition = CGPointMake(
rect.origin.x + rect.size.width / 2.0,
CGFloat(progress) * rect.size.height * 0.9 + rect.origin.y)
self.emitterView.createEmitter("c\(index)", duration: self.morphingDuration) {
(layer, cell) in
layer.emitterSize = CGSizeMake(rect.size.width , 1)
layer.renderMode = kCAEmitterLayerOutline
cell.emissionLongitude = CGFloat(M_PI / 2.0)
cell.scale = self.font.pointSize / 300.0
cell.scaleSpeed = self.font.pointSize / 300.0 * -1.5
cell.color = self.textColor.CGColor
cell.birthRate = Float(self.font.pointSize) * Float(arc4random_uniform(7) + 3)
}.update {
(layer, cell) in
layer.emitterPosition = emitterPosition
}.play()
}
return LTCharacterLimbo(
char: char,
rect: self.newRects[index],
alpha: CGFloat(self.morphingProgress),
size: self.font.pointSize,
drawingProgress: CGFloat(progress)
)
}
drawingClosures["Sparkle\(LTMorphingPhaseDraw)"] = {
(charLimbo: LTCharacterLimbo) in
if charLimbo.drawingProgress > 0.0 {
let (charImage, rect) = self.maskedImageForCharLimbo(charLimbo, withProgress: charLimbo.drawingProgress)
charImage.drawInRect(rect)
return true
}
return false
}
skipFramesClosures["Sparkle\(LTMorphingPhaseSkipFrames)"] = {
return 1
}
}
}
|
mit
|
6b391fb7f21ba75e0752f25b98f9f70b
| 39.44697 | 124 | 0.585503 | 4.98041 | false | false | false | false |
Tuslareb/JBDatePicker
|
JBDatePicker/Classes/JBDatePickerContentVC.swift
|
1
|
13972
|
//
// JBDatePickerContentVC.swift
// JBDatePicker
//
// Created by Joost van Breukelen on 09-10-16.
// Copyright © 2016 Joost van Breukelen. All rights reserved.
//
import UIKit
class JBDatePickerContentVC: UIViewController, UIScrollViewDelegate {
// MARK: - Properties
unowned let datePickerView: JBDatePickerView
let scrollView: UIScrollView
var presentedMonthView: MonthView
var scrollDirection: JBScrollDirection = .none
private var monthViews = [MonthViewIdentifier : MonthView]()
///flag that helps us preventing presentation while another presentation is still going on
private var isPresenting = false
private var currentPage = 1
private var pageChanged: Bool {
get {
return currentPage == 1 ? false : true
}
}
private var scrollViewBounds: CGRect {
return scrollView.bounds
}
// MARK: - Initialization
init(datePickerView: JBDatePickerView, frame: CGRect, presentedDate: Date) {
self.datePickerView = datePickerView
self.scrollView = UIScrollView(frame: frame)
//create the current Monthview for the current date and fill it with weekviews.
presentedMonthView = MonthView(datePickerView: datePickerView, date: presentedDate, isPresented: true)
presentedMonthView.createWeekViews()
super.init(nibName: nil, bundle: nil)
//setup scrollView. Give it a contentsize of 3 times the width because it will hold 3 monthViews
scrollView.contentSize = CGSize(width: frame.width * 3, height: frame.height)
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.layer.masksToBounds = true
scrollView.isPagingEnabled = true
scrollView.delegate = self
addInitialMonthViews(for: presentedMonthView.date)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Adding of MonthViews
/**
Fills the scrollView of the contentController
with the initial three monthViews
- Parameter date: the Date object to pass
*/
private func addInitialMonthViews(for date: Date) {
//add the three monthViews to the scrollview
addMonthView(presentedMonthView, withIdentifier: .presented)
addMonthView(getPreviousMonthView(for: date), withIdentifier: .previous)
addMonthView(getNextMonthView(for: date), withIdentifier: .next)
}
/**
Adds the given monthView to the contentControllers scrollView and updates
the given monthViews frame origin to place it in the correct position.
- Parameter monthView: the MonthView to be added
- Parameter identifier: can be .previous, .presented or .next
*/
private func addMonthView(_ monthView: MonthView, withIdentifier identifier: MonthViewIdentifier) {
monthView.frame.origin = CGPoint(x: scrollView.bounds.width * CGFloat(identifier.rawValue), y: 0)
monthViews[identifier] = monthView
scrollView.addSubview(monthView)
}
///returns the previous monthView for a given date
private func getPreviousMonthView(for date: Date) -> MonthView {
let cal = Calendar.current
var comps = cal.dateComponents([.month, .year], from: date)
comps.month! -= 1
let firstDateOfPreviousMonth = cal.date(from: comps)!
let previousMonthView = MonthView(datePickerView: datePickerView, date: firstDateOfPreviousMonth, isPresented: false)
//this is what gives new new monthView it's initial frame
previousMonthView.frame = scrollView.frame
previousMonthView.createWeekViews()
return previousMonthView
}
///returns the next monthView for a given date
private func getNextMonthView(for date: Date) -> MonthView {
let cal = Calendar.current
var comps = cal.dateComponents([.month, .year], from: date)
comps.month! += 1
let firstDateOfNextMonth = cal.date(from: comps)!
let nextMonthView = MonthView(datePickerView: datePickerView, date: firstDateOfNextMonth, isPresented: false)
//this is what gives new new monthView it's initial frame
nextMonthView.frame = scrollView.frame
nextMonthView.createWeekViews()
return nextMonthView
}
// MARK: - Reloading and replacing of MonthViews
/**
Updates the frame of the scrollView and reloads the monthViews present
When called, scrolls to presented monthView
- Parameter frame: the frame to update to
- Note: is only called on initial load of datePicker
*/
func updateScrollViewFrame(_ frame: CGRect) {
if frame != .zero {
scrollView.frame = frame
scrollView.contentSize = CGSize(width: frame.size.width * 3, height: frame.size.height)
}
let monthViewFrame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
for monthView in monthViews.values {
monthView.reloadSubViewsWithFrame(monthViewFrame)
}
reloadMonthViews()
if let presentedMonthView = monthViews[.presented] {
//scroll to presented month
scrollView.scrollRectToVisible(presentedMonthView.frame, animated: false)
}
}
/**
For each monthView this method updates the origin, then removes the monthView from the scrollView
and adds them again.
*/
private func reloadMonthViews() {
for (identifier, monthView) in monthViews {
monthView.frame.origin.x = CGFloat(identifier.rawValue) * scrollView.frame.width
//this will not deinitialize, because there's still a reference to this monthView object
monthView.removeFromSuperview()
scrollView.addSubview(monthView)
}
}
/**
Replaces the identifier of a monthView with another identifier, so it's gets another role. The presented monthView will, for example, become the next monthView. The frame origin of the monthView involved will also be adjusted and scrolled into position if needed.
- Parameter monthView: the monthView involved
- Parameter identifier: the new identifier that the monthView will get
- Parameter shouldScrollToPosition: a boolean that determines if the monthView's frame should scroll into position or not
*/
private func replaceMonthViewIdentifier(_ monthView: MonthView, with identifier: MonthViewIdentifier, shouldScrollToPosition: Bool) {
//adjust frame to the frame that comes with the new identifier (the new role)
var monthViewFrame = monthView.frame
monthViewFrame.origin.x = monthViewFrame.width * CGFloat(identifier.rawValue)
monthView.frame = monthViewFrame
//update the monthViews dictionary
monthViews[identifier] = monthView
//scroll the new 'presented' monthView into the presented position.
//this will also cause the currentPage to be set to 1 again by the didScroll delegate method
if shouldScrollToPosition {
scrollView.scrollRectToVisible(monthViewFrame, animated: false)
}
}
// MARK: - Scrolling MonthViews
private func scrolledToPreviousMonth() {
guard let previousMonthView = monthViews[.previous], let presentedMonthView = monthViews[.presented] else { return }
//remove next monthView, this will be replaced by presented monthView
monthViews[.next]?.removeFromSuperview()
//replace previous monthView identifier with 'presented' identifier and set isPresented value
replaceMonthViewIdentifier(previousMonthView, with: .presented, shouldScrollToPosition: true)
previousMonthView.isPresented = true
//replace presented monthView identifier with 'next' identifier and set isPresented value
replaceMonthViewIdentifier(presentedMonthView, with: .next, shouldScrollToPosition: false)
presentedMonthView.isPresented = false
//add new monthView which will become the new 'previous' monthView
addMonthView(getPreviousMonthView(for: previousMonthView.date), withIdentifier: .previous)
}
private func scrolledToNextMonth() {
guard let nextMonthView = monthViews[.next], let presentedMonthView = monthViews[.presented] else { return }
//remove previous monthView, this will be replaced by presented monthView
monthViews[.previous]?.removeFromSuperview()
//replace next monthView identifier with 'presented' identifier and set isPresented value
replaceMonthViewIdentifier(nextMonthView, with: .presented, shouldScrollToPosition: true)
nextMonthView.isPresented = true
//replace presented monthView identifier with 'previous' identifier and set isPresented value
replaceMonthViewIdentifier(presentedMonthView, with: .previous, shouldScrollToPosition: false)
nextMonthView.isPresented = false
//add new monthView which will become the new 'next' monthView
addMonthView(getNextMonthView(for: nextMonthView.date), withIdentifier: .next)
}
// MARK: - UIScrollViewDelegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let page = Int(floor((scrollView.contentOffset.x -
scrollView.frame.width / 2) / scrollView.frame.width) + 1)
if currentPage != page {
currentPage = page
}
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
//decide in which direction the user did scroll
if decelerate {
let rightBorderOfScrollView = scrollView.frame.width
if scrollView.contentOffset.x <= rightBorderOfScrollView {
scrollDirection = .toPrevious
} else {
scrollDirection = .toNext
}
}
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if pageChanged {
switch scrollDirection {
case .toNext: scrolledToNextMonth()
case .toPrevious: scrolledToPreviousMonth()
case .none: break
}
}
scrollDirection = .none
}
// MARK: - Presenting of monthViews
func presentNextView() {
if !isPresenting {
guard let previous = monthViews[.previous], let presented = monthViews[.presented], let next = monthViews[.next] else { return }
isPresenting = true
UIView.animate(withDuration: 0.5, delay: 0, options: UIViewAnimationOptions(), animations: {
//animate positions of monthViews
previous.frame.origin.x -= self.scrollView.frame.width
presented.frame.origin.x -= self.scrollView.frame.width
next.frame.origin.x -= self.scrollView.frame.width
}, completion: {_ in
//replace identifiers
self.replaceMonthViewIdentifier(presented, with: .previous, shouldScrollToPosition: false)
self.replaceMonthViewIdentifier(next, with: .presented, shouldScrollToPosition: false)
self.presentedMonthView = next
//set isPresented value
previous.isPresented = false
self.presentedMonthView.isPresented = true
//remove previous monthView
previous.removeFromSuperview()
//create and insert new 'next' monthView
self.addMonthView(self.getNextMonthView(for: next.date), withIdentifier: .next)
self.isPresenting = false
})
}
}
func presentPreviousView() {
if !isPresenting {
guard let previous = monthViews[.previous], let presented = monthViews[.presented], let next = monthViews[.next] else { return }
isPresenting = true
UIView.animate(withDuration: 0.5, delay: 0, options: UIViewAnimationOptions(), animations: {
//animate positions of monthViews
previous.frame.origin.x += self.scrollView.frame.width
presented.frame.origin.x += self.scrollView.frame.width
next.frame.origin.x += self.scrollView.frame.width
}, completion: {_ in
//replace identifiers
self.replaceMonthViewIdentifier(presented, with: .next, shouldScrollToPosition: false)
self.replaceMonthViewIdentifier(previous, with: .presented, shouldScrollToPosition: false)
self.presentedMonthView = previous
//set isPresented value
next.isPresented = false
self.presentedMonthView.isPresented = true
//remove previous monthView
next.removeFromSuperview()
//create and insert new 'previous' monthView
self.addMonthView(self.getPreviousMonthView(for: previous.date), withIdentifier: .previous)
self.isPresenting = false
})
}
}
}
|
mit
|
945a7c3b6e74ee8da5d01ce94a4d9389
| 37.276712 | 268 | 0.630377 | 5.848054 | false | false | false | false |
dws741119/Tos
|
TOS/TOS/beadSpriteNode.swift
|
1
|
958
|
import SpriteKit
class beadSpriteNode : SKSpriteNode {
var tag:Int = 0
var type:Int = 0
var finalPosition:CGPoint = CGPointZero
class func createBead (#column:Int,row:Int) -> beadSpriteNode {
let beadColor = ["bead_yellow","bead_green","bead_puple","bead_blue","bead_red","bead_gray"]
let chooseType = Int( arc4random() % 4)
let beadTexture = SKTexture(imageNamed:beadColor[chooseType])
let bead = beadSpriteNode(texture: beadTexture)
bead.anchorPoint = CGPoint(x: 0.5, y: 0.0)
bead.startPosition(column: column, row: row)
bead.finalPosition(column: column, row: row)
bead.type = chooseType
return bead
}
func startPosition (#column:Int,row:Int) {
self.position = CGPoint(x: column * 53 + 28, y: row * 53 + 266)
}
func finalPosition (#column:Int,row:Int) {
self.finalPosition = CGPoint(x: column * 53 + 28, y: row * 53)
}
}
|
mit
|
ce31a409c2ce5d5414edea6a3fc464fa
| 33.25 | 100 | 0.626305 | 3.409253 | false | false | false | false |
tj---/ServiceHealth
|
HealthStatus/SettingsFetcher.swift
|
1
|
1991
|
//
// SettingsFetcher.swift
// HealthStatus
//
// Created by Trilok Jain on 12/6/14.
// Copyright (c) 2014 Trilok Jain. All rights reserved.
//
import Foundation
@objc class SettingsFetcher: Fetcher
{
let settings_storage = "._service_health_preferences.plist"
var settings: Settings = Settings()
init(callBack: (() -> Void), fUrl: NSString)
{
super.init(callBack: callBack, fetchUrl: fUrl);
settings = Utils.readFromFile(self.settings_storage)
}
func writePreferences()
{
Utils.writeToFile(settings, fileName: settings_storage)
}
func syncPreferences()
{
var localSettings = Utils.readFromFile(self.settings_storage) as Settings
if(self.settings.providers.count == 0)
{
self.settings = localSettings
}
else if(localSettings.providers.count > 0)
{
for fProvider in settings.providers
{
for lProvider in localSettings.providers
{
if(lProvider.serviceName == fProvider.serviceName)
{
fProvider.enabled = lProvider.enabled
}
}
}
}
}
override func doOnSuccess(jsonResult: Dictionary<String, AnyObject>!)
{
self.settings = (nil != jsonResult) ? self.parseJson(jsonResult) : Settings()
self.syncPreferences()
super.updateCallBack()
}
func parseJson(json: Dictionary<String, AnyObject>) -> Settings
{
var settings = Settings()
var services = json["services"] as Array<Dictionary<String, AnyObject>>
for service in services
{
var serviceSetting = Service(sName: service["serviceName"] as NSString!)
serviceSetting.serviceId = service["serviceId"] as NSString!
settings.addProvider(serviceSetting)
}
return settings
}
}
|
mit
|
fcde1568df9dcfe2f505795de9d571af
| 27.457143 | 85 | 0.58011 | 4.729216 | false | false | false | false |
alessiobrozzi/firefox-ios
|
ReadingList/ReadingListClientRecord.swift
|
16
|
2136
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
public struct ReadingListClientRecord: Equatable {
public let clientMetadata: ReadingListClientMetadata
public let serverMetadata: ReadingListServerMetadata?
public let url: String
public let title: String
public let addedBy: String
public let unread: Bool
public let archived: Bool
public let favorite: Bool
/// Initializer for when a record is loaded from a database row
public init?(row: [String: Any]) {
guard let clientMetadata = ReadingListClientMetadata(row: row) else {
return nil
}
guard let url = row["url"] as? String,
let title = row["title"] as? String,
let addedBy = row["added_by"] as? String,
let unread = row["unread"] as? Bool else {
return nil
}
self.clientMetadata = clientMetadata
self.serverMetadata = ReadingListServerMetadata(row: row)
self.url = url
self.title = title
self.addedBy = addedBy
self.unread = unread
self.archived = row["archived"] as? Bool ?? false
self.favorite = row["favorite"] as? Bool ?? false
}
public var json: AnyObject {
get {
let json = NSMutableDictionary()
json["url"] = url
json["title"] = title
json["added_by"] = addedBy
json["unread"] = unread
json["archived"] = archived
json["favorite"] = favorite
return json
}
}
}
public func ==(lhs: ReadingListClientRecord, rhs: ReadingListClientRecord) -> Bool {
return lhs.clientMetadata == rhs.clientMetadata
&& lhs.serverMetadata == rhs.serverMetadata
&& lhs.url == rhs.url
&& lhs.title == rhs.title
&& lhs.addedBy == rhs.addedBy
&& lhs.unread == rhs.unread
&& lhs.archived == rhs.archived
&& lhs.favorite == rhs.favorite
}
|
mpl-2.0
|
24c39fa577c84b81107aad2224a46c53
| 30.880597 | 84 | 0.603464 | 4.623377 | false | false | false | false |
huahuasj/ios-charts
|
Charts/Classes/Charts/BarLineChartViewBase.swift
|
3
|
57076
|
//
// BarLineChartViewBase.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics.CGBase
import UIKit.UIGestureRecognizer
/// Base-class of LineChart, BarChart, ScatterChart and CandleStickChart.
public class BarLineChartViewBase: ChartViewBase, UIGestureRecognizerDelegate
{
/// the maximum number of entried to which values will be drawn
internal var _maxVisibleValueCount = 100
/// flag that indicates if auto scaling on the y axis is enabled
private var _autoScaleMinMaxEnabled = false
private var _autoScaleLastLowestVisibleXIndex: Int!
private var _autoScaleLastHighestVisibleXIndex: Int!
private var _pinchZoomEnabled = false
private var _doubleTapToZoomEnabled = true
private var _dragEnabled = true
private var _scaleXEnabled = true
private var _scaleYEnabled = true
/// the color for the background of the chart-drawing area (everything behind the grid lines).
public var gridBackgroundColor = UIColor(red: 240/255.0, green: 240/255.0, blue: 240/255.0, alpha: 1.0)
public var borderColor = UIColor.blackColor()
public var borderLineWidth: CGFloat = 1.0
/// flag indicating if the grid background should be drawn or not
public var drawGridBackgroundEnabled = true
/// Sets drawing the borders rectangle to true. If this is enabled, there is no point drawing the axis-lines of x- and y-axis.
public var drawBordersEnabled = false
/// the object representing the labels on the y-axis, this object is prepared
/// in the pepareYLabels() method
internal var _leftAxis: ChartYAxis!
internal var _rightAxis: ChartYAxis!
/// the object representing the labels on the x-axis
internal var _xAxis: ChartXAxis!
internal var _leftYAxisRenderer: ChartYAxisRenderer!
internal var _rightYAxisRenderer: ChartYAxisRenderer!
internal var _leftAxisTransformer: ChartTransformer!
internal var _rightAxisTransformer: ChartTransformer!
internal var _xAxisRenderer: ChartXAxisRenderer!
private var _tapGestureRecognizer: UITapGestureRecognizer!
private var _doubleTapGestureRecognizer: UITapGestureRecognizer!
private var _pinchGestureRecognizer: UIPinchGestureRecognizer!
private var _panGestureRecognizer: UIPanGestureRecognizer!
/// flag that indicates if a custom viewport offset has been set
private var _customViewPortEnabled = false
public override init(frame: CGRect)
{
super.init(frame: frame);
}
public required init(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder);
}
deinit
{
stopDeceleration();
}
internal override func initialize()
{
super.initialize();
_leftAxis = ChartYAxis(position: .Left);
_rightAxis = ChartYAxis(position: .Right);
_xAxis = ChartXAxis();
_leftAxisTransformer = ChartTransformer(viewPortHandler: _viewPortHandler);
_rightAxisTransformer = ChartTransformer(viewPortHandler: _viewPortHandler);
_leftYAxisRenderer = ChartYAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: _leftAxis, transformer: _leftAxisTransformer);
_rightYAxisRenderer = ChartYAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: _rightAxis, transformer: _rightAxisTransformer);
_xAxisRenderer = ChartXAxisRenderer(viewPortHandler: _viewPortHandler, xAxis: _xAxis, transformer: _leftAxisTransformer);
_tapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("tapGestureRecognized:"));
_doubleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("doubleTapGestureRecognized:"));
_doubleTapGestureRecognizer.numberOfTapsRequired = 2;
_pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: Selector("pinchGestureRecognized:"));
_panGestureRecognizer = UIPanGestureRecognizer(target: self, action: Selector("panGestureRecognized:"));
_pinchGestureRecognizer.delegate = self;
_panGestureRecognizer.delegate = self;
self.addGestureRecognizer(_tapGestureRecognizer);
self.addGestureRecognizer(_doubleTapGestureRecognizer);
self.addGestureRecognizer(_pinchGestureRecognizer);
self.addGestureRecognizer(_panGestureRecognizer);
_doubleTapGestureRecognizer.enabled = _doubleTapToZoomEnabled;
_pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled;
_panGestureRecognizer.enabled = _dragEnabled;
}
public override func drawRect(rect: CGRect)
{
super.drawRect(rect);
if (_dataNotSet)
{
return;
}
let context = UIGraphicsGetCurrentContext();
calcModulus();
if (_xAxisRenderer !== nil)
{
_xAxisRenderer!.calcXBounds(chart: self, xAxisModulus: _xAxis.axisLabelModulus);
}
if (renderer !== nil)
{
renderer!.calcXBounds(chart: self, xAxisModulus: _xAxis.axisLabelModulus);
}
// execute all drawing commands
drawGridBackground(context: context);
if (_leftAxis.isEnabled)
{
_leftYAxisRenderer?.computeAxis(yMin: _leftAxis.axisMinimum, yMax: _leftAxis.axisMaximum);
}
if (_rightAxis.isEnabled)
{
_rightYAxisRenderer?.computeAxis(yMin: _rightAxis.axisMinimum, yMax: _rightAxis.axisMaximum);
}
_xAxisRenderer?.renderAxisLine(context: context);
_leftYAxisRenderer?.renderAxisLine(context: context);
_rightYAxisRenderer?.renderAxisLine(context: context);
if (_autoScaleMinMaxEnabled)
{
let lowestVisibleXIndex = self.lowestVisibleXIndex,
highestVisibleXIndex = self.highestVisibleXIndex;
if (_autoScaleLastLowestVisibleXIndex == nil || _autoScaleLastLowestVisibleXIndex != lowestVisibleXIndex ||
_autoScaleLastHighestVisibleXIndex == nil || _autoScaleLastHighestVisibleXIndex != highestVisibleXIndex)
{
calcMinMax();
calculateOffsets();
_autoScaleLastLowestVisibleXIndex = lowestVisibleXIndex;
_autoScaleLastHighestVisibleXIndex = highestVisibleXIndex;
}
}
// make sure the graph values and grid cannot be drawn outside the content-rect
CGContextSaveGState(context);
CGContextClipToRect(context, _viewPortHandler.contentRect);
if (_xAxis.isDrawLimitLinesBehindDataEnabled)
{
_xAxisRenderer?.renderLimitLines(context: context);
}
if (_leftAxis.isDrawLimitLinesBehindDataEnabled)
{
_leftYAxisRenderer?.renderLimitLines(context: context);
}
if (_rightAxis.isDrawLimitLinesBehindDataEnabled)
{
_rightYAxisRenderer?.renderLimitLines(context: context);
}
_xAxisRenderer?.renderGridLines(context: context);
_leftYAxisRenderer?.renderGridLines(context: context);
_rightYAxisRenderer?.renderGridLines(context: context);
renderer?.drawData(context: context);
if (!_xAxis.isDrawLimitLinesBehindDataEnabled)
{
_xAxisRenderer?.renderLimitLines(context: context);
}
if (!_leftAxis.isDrawLimitLinesBehindDataEnabled)
{
_leftYAxisRenderer?.renderLimitLines(context: context);
}
if (!_rightAxis.isDrawLimitLinesBehindDataEnabled)
{
_rightYAxisRenderer?.renderLimitLines(context: context);
}
// if highlighting is enabled
if (highlightEnabled && highlightIndicatorEnabled && valuesToHighlight())
{
renderer?.drawHighlighted(context: context, indices: _indicesToHightlight);
}
// Removes clipping rectangle
CGContextRestoreGState(context);
renderer!.drawExtras(context: context);
_xAxisRenderer.renderAxisLabels(context: context);
_leftYAxisRenderer.renderAxisLabels(context: context);
_rightYAxisRenderer.renderAxisLabels(context: context);
renderer!.drawValues(context: context);
_legendRenderer.renderLegend(context: context);
// drawLegend();
drawMarkers(context: context);
drawDescription(context: context);
}
internal func prepareValuePxMatrix()
{
_rightAxisTransformer.prepareMatrixValuePx(chartXMin: _chartXMin, deltaX: _deltaX, deltaY: CGFloat(_rightAxis.axisRange), chartYMin: _rightAxis.axisMinimum);
_leftAxisTransformer.prepareMatrixValuePx(chartXMin: _chartXMin, deltaX: _deltaX, deltaY: CGFloat(_leftAxis.axisRange), chartYMin: _leftAxis.axisMinimum);
}
internal func prepareOffsetMatrix()
{
_rightAxisTransformer.prepareMatrixOffset(_rightAxis.isInverted);
_leftAxisTransformer.prepareMatrixOffset(_leftAxis.isInverted);
}
public override func notifyDataSetChanged()
{
if (_dataNotSet)
{
return;
}
calcMinMax();
_leftAxis?._defaultValueFormatter = _defaultValueFormatter;
_rightAxis?._defaultValueFormatter = _defaultValueFormatter;
_leftYAxisRenderer?.computeAxis(yMin: _leftAxis.axisMinimum, yMax: _leftAxis.axisMaximum);
_rightYAxisRenderer?.computeAxis(yMin: _rightAxis.axisMinimum, yMax: _rightAxis.axisMaximum);
_xAxisRenderer?.computeAxis(xValAverageLength: _data.xValAverageLength, xValues: _data.xVals);
if (_legend !== nil)
{
_legendRenderer?.computeLegend(_data);
}
calculateOffsets();
setNeedsDisplay();
}
internal override func calcMinMax()
{
if (_autoScaleMinMaxEnabled)
{
_data.calcMinMax(start: lowestVisibleXIndex, end: highestVisibleXIndex);
}
var minLeft = _data.getYMin(.Left);
var maxLeft = _data.getYMax(.Left);
var minRight = _data.getYMin(.Right);
var maxRight = _data.getYMax(.Right);
var leftRange = abs(maxLeft - (_leftAxis.isStartAtZeroEnabled ? 0.0 : minLeft));
var rightRange = abs(maxRight - (_rightAxis.isStartAtZeroEnabled ? 0.0 : minRight));
// in case all values are equal
if (leftRange == 0.0)
{
maxLeft = maxLeft + 1.0;
if (!_leftAxis.isStartAtZeroEnabled)
{
minLeft = minLeft - 1.0;
}
}
if (rightRange == 0.0)
{
maxRight = maxRight + 1.0;
if (!_rightAxis.isStartAtZeroEnabled)
{
minRight = minRight - 1.0;
}
}
var topSpaceLeft = leftRange * Float(_leftAxis.spaceTop);
var topSpaceRight = rightRange * Float(_rightAxis.spaceTop);
var bottomSpaceLeft = leftRange * Float(_leftAxis.spaceBottom);
var bottomSpaceRight = rightRange * Float(_rightAxis.spaceBottom);
_chartXMax = Float(_data.xVals.count - 1);
_deltaX = CGFloat(abs(_chartXMax - _chartXMin));
_leftAxis.axisMaximum = !isnan(_leftAxis.customAxisMax) ? _leftAxis.customAxisMax : (maxLeft + topSpaceLeft);
_rightAxis.axisMaximum = !isnan(_rightAxis.customAxisMax) ? _rightAxis.customAxisMax : (maxRight + topSpaceRight);
_leftAxis.axisMinimum = !isnan(_leftAxis.customAxisMin) ? _leftAxis.customAxisMin : (minLeft - bottomSpaceLeft);
_rightAxis.axisMinimum = !isnan(_rightAxis.customAxisMin) ? _rightAxis.customAxisMin : (minRight - bottomSpaceRight);
// consider starting at zero (0)
if (_leftAxis.isStartAtZeroEnabled)
{
_leftAxis.axisMinimum = 0.0;
}
if (_rightAxis.isStartAtZeroEnabled)
{
_rightAxis.axisMinimum = 0.0;
}
_leftAxis.axisRange = abs(_leftAxis.axisMaximum - _leftAxis.axisMinimum);
_rightAxis.axisRange = abs(_rightAxis.axisMaximum - _rightAxis.axisMinimum);
}
internal override func calculateOffsets()
{
if (!_customViewPortEnabled)
{
var offsetLeft = CGFloat(0.0);
var offsetRight = CGFloat(0.0);
var offsetTop = CGFloat(0.0);
var offsetBottom = CGFloat(0.0);
// setup offsets for legend
if (_legend !== nil && _legend.isEnabled)
{
if (_legend.position == .RightOfChart
|| _legend.position == .RightOfChartCenter)
{
offsetRight += min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) + _legend.xOffset * 2.0;
}
if (_legend.position == .LeftOfChart
|| _legend.position == .LeftOfChartCenter)
{
offsetLeft += min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) + _legend.xOffset * 2.0;
}
else if (_legend.position == .BelowChartLeft
|| _legend.position == .BelowChartRight
|| _legend.position == .BelowChartCenter)
{
var yOffset = _legend.textHeightMax * 2.0; // It's possible that we do not need this offset anymore as it is available through the extraOffsets
offsetBottom += min(_legend.neededHeight + yOffset, _viewPortHandler.chartHeight * _legend.maxSizePercent);
}
}
// offsets for y-labels
if (leftAxis.needsOffset)
{
offsetLeft += leftAxis.requiredSize().width;
}
if (rightAxis.needsOffset)
{
offsetRight += rightAxis.requiredSize().width;
}
if (xAxis.isEnabled && xAxis.isDrawLabelsEnabled)
{
var xlabelheight = xAxis.labelHeight * 2.0;
// offsets for x-labels
if (xAxis.labelPosition == .Bottom)
{
offsetBottom += xlabelheight;
}
else if (xAxis.labelPosition == .Top)
{
offsetTop += xlabelheight;
}
else if (xAxis.labelPosition == .BothSided)
{
offsetBottom += xlabelheight;
offsetTop += xlabelheight;
}
}
offsetTop += self.extraTopOffset;
offsetRight += self.extraRightOffset;
offsetBottom += self.extraBottomOffset;
offsetLeft += self.extraLeftOffset;
var minOffset = CGFloat(10.0);
_viewPortHandler.restrainViewPort(
offsetLeft: max(minOffset, offsetLeft),
offsetTop: max(minOffset, offsetTop),
offsetRight: max(minOffset, offsetRight),
offsetBottom: max(minOffset, offsetBottom));
}
prepareOffsetMatrix();
prepareValuePxMatrix();
}
/// calculates the modulus for x-labels and grid
internal func calcModulus()
{
if (_xAxis === nil || !_xAxis.isEnabled)
{
return;
}
if (!_xAxis.isAxisModulusCustom)
{
_xAxis.axisLabelModulus = Int(ceil((CGFloat(_data.xValCount) * _xAxis.labelWidth) / (_viewPortHandler.contentWidth * _viewPortHandler.touchMatrix.a)));
}
if (_xAxis.axisLabelModulus < 1)
{
_xAxis.axisLabelModulus = 1;
}
}
public override func getMarkerPosition(#entry: ChartDataEntry, dataSetIndex: Int) -> CGPoint
{
var xPos = CGFloat(entry.xIndex);
if (self.isKindOfClass(BarChartView))
{
var bd = _data as! BarChartData;
var space = bd.groupSpace;
var j = _data.getDataSetByIndex(dataSetIndex)!.entryIndex(entry: entry, isEqual: true);
var x = CGFloat(j * (_data.dataSetCount - 1) + dataSetIndex) + space * CGFloat(j) + space / 2.0;
xPos += x;
}
// position of the marker depends on selected value index and value
var pt = CGPoint(x: xPos, y: CGFloat(entry.value) * _animator.phaseY);
getTransformer(_data.getDataSetByIndex(dataSetIndex)!.axisDependency).pointValueToPixel(&pt);
return pt;
}
/// draws the grid background
internal func drawGridBackground(#context: CGContext)
{
if (drawGridBackgroundEnabled || drawBordersEnabled)
{
CGContextSaveGState(context);
}
if (drawGridBackgroundEnabled)
{
// draw the grid background
CGContextSetFillColorWithColor(context, gridBackgroundColor.CGColor);
CGContextFillRect(context, _viewPortHandler.contentRect);
}
if (drawBordersEnabled)
{
CGContextSetLineWidth(context, borderLineWidth);
CGContextSetStrokeColorWithColor(context, borderColor.CGColor);
CGContextStrokeRect(context, _viewPortHandler.contentRect);
}
if (drawGridBackgroundEnabled || drawBordersEnabled)
{
CGContextRestoreGState(context);
}
}
/// Returns the Transformer class that contains all matrices and is
/// responsible for transforming values into pixels on the screen and
/// backwards.
public func getTransformer(which: ChartYAxis.AxisDependency) -> ChartTransformer
{
if (which == .Left)
{
return _leftAxisTransformer;
}
else
{
return _rightAxisTransformer;
}
}
// MARK: - Gestures
private enum GestureScaleAxis
{
case Both
case X
case Y
}
private var _isDragging = false;
private var _isScaling = false;
private var _gestureScaleAxis = GestureScaleAxis.Both;
private var _closestDataSetToTouch: ChartDataSet!;
private var _panGestureReachedEdge: Bool = false;
private weak var _outerScrollView: UIScrollView?;
/// the last highlighted object
private var _lastHighlighted: ChartHighlight!;
private var _lastPanPoint = CGPoint() /// This is to prevent using setTranslation which resets velocity
private var _decelerationLastTime: NSTimeInterval = 0.0
private var _decelerationDisplayLink: CADisplayLink!
private var _decelerationVelocity = CGPoint()
@objc private func tapGestureRecognized(recognizer: UITapGestureRecognizer)
{
if (_dataNotSet)
{
return;
}
if (recognizer.state == UIGestureRecognizerState.Ended)
{
var h = getHighlightByTouchPoint(recognizer.locationInView(self));
if (h === nil || h!.isEqual(_lastHighlighted))
{
self.highlightValue(highlight: nil, callDelegate: true);
_lastHighlighted = nil;
}
else
{
_lastHighlighted = h;
self.highlightValue(highlight: h, callDelegate: true);
}
}
}
@objc private func doubleTapGestureRecognized(recognizer: UITapGestureRecognizer)
{
if (_dataNotSet)
{
return;
}
if (recognizer.state == UIGestureRecognizerState.Ended)
{
if (!_dataNotSet && _doubleTapToZoomEnabled)
{
var location = recognizer.locationInView(self);
location.x = location.x - _viewPortHandler.offsetLeft;
if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted)
{
location.y = -(location.y - _viewPortHandler.offsetTop);
}
else
{
location.y = -(self.bounds.size.height - location.y - _viewPortHandler.offsetBottom);
}
self.zoom(1.4, scaleY: 1.4, x: location.x, y: location.y);
}
}
}
@objc private func pinchGestureRecognized(recognizer: UIPinchGestureRecognizer)
{
if (recognizer.state == UIGestureRecognizerState.Began)
{
stopDeceleration();
if (!_dataNotSet && (_pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled))
{
_isScaling = true;
if (_pinchZoomEnabled)
{
_gestureScaleAxis = .Both;
}
else
{
var x = abs(recognizer.locationInView(self).x - recognizer.locationOfTouch(1, inView: self).x);
var y = abs(recognizer.locationInView(self).y - recognizer.locationOfTouch(1, inView: self).y);
if (x > y)
{
_gestureScaleAxis = .X;
}
else
{
_gestureScaleAxis = .Y;
}
}
}
}
else if (recognizer.state == UIGestureRecognizerState.Ended || recognizer.state == UIGestureRecognizerState.Cancelled)
{
if (_isScaling)
{
_isScaling = false;
}
}
else if (recognizer.state == UIGestureRecognizerState.Changed)
{
if (_isScaling)
{
var location = recognizer.locationInView(self);
location.x = location.x - _viewPortHandler.offsetLeft;
if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted)
{
location.y = -(location.y - _viewPortHandler.offsetTop);
}
else
{
location.y = -(_viewPortHandler.chartHeight - location.y - _viewPortHandler.offsetBottom);
}
var scaleX = (_gestureScaleAxis == .Both || _gestureScaleAxis == .X) && _scaleXEnabled ? recognizer.scale : 1.0;
var scaleY = (_gestureScaleAxis == .Both || _gestureScaleAxis == .Y) && _scaleYEnabled ? recognizer.scale : 1.0;
var matrix = CGAffineTransformMakeTranslation(location.x, location.y);
matrix = CGAffineTransformScale(matrix, scaleX, scaleY);
matrix = CGAffineTransformTranslate(matrix,
-location.x, -location.y);
matrix = CGAffineTransformConcat(_viewPortHandler.touchMatrix, matrix);
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true);
if (delegate !== nil)
{
delegate?.chartScaled?(self, scaleX: scaleX, scaleY: scaleY);
}
recognizer.scale = 1.0;
}
}
}
@objc private func panGestureRecognized(recognizer: UIPanGestureRecognizer)
{
if (recognizer.state == UIGestureRecognizerState.Began)
{
stopDeceleration();
if ((!_dataNotSet && _dragEnabled && !self.hasNoDragOffset) || !self.isFullyZoomedOut)
{
_isDragging = true;
_closestDataSetToTouch = getDataSetByTouchPoint(recognizer.locationOfTouch(0, inView: self));
var translation = recognizer.translationInView(self);
if (!performPanChange(translation: translation))
{
if (_outerScrollView !== nil)
{
// We can stop dragging right now, and let the scroll view take control
_outerScrollView = nil;
_isDragging = false;
}
}
else
{
if (_outerScrollView !== nil)
{
// Prevent the parent scroll view from scrolling
_outerScrollView?.scrollEnabled = false;
}
}
_lastPanPoint = recognizer.translationInView(self);
}
}
else if (recognizer.state == UIGestureRecognizerState.Changed)
{
if (_isDragging)
{
var originalTranslation = recognizer.translationInView(self);
var translation = CGPoint(x: originalTranslation.x - _lastPanPoint.x, y: originalTranslation.y - _lastPanPoint.y);
performPanChange(translation: translation);
_lastPanPoint = originalTranslation;
}
else if (isHighlightPerDragEnabled)
{
var h = getHighlightByTouchPoint(recognizer.locationInView(self));
if ((h === nil && _lastHighlighted !== nil) ||
(h !== nil && _lastHighlighted === nil) ||
(h !== nil && _lastHighlighted !== nil && !h!.isEqual(_lastHighlighted)))
{
_lastHighlighted = h;
self.highlightValue(highlight: h, callDelegate: true);
}
}
}
else if (recognizer.state == UIGestureRecognizerState.Ended || recognizer.state == UIGestureRecognizerState.Cancelled)
{
if (_isDragging)
{
if (recognizer.state == UIGestureRecognizerState.Ended && isDragDecelerationEnabled)
{
stopDeceleration();
_decelerationLastTime = CACurrentMediaTime();
_decelerationVelocity = recognizer.velocityInView(self);
_decelerationDisplayLink = CADisplayLink(target: self, selector: Selector("decelerationLoop"));
_decelerationDisplayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes);
}
_isDragging = false;
}
if (_outerScrollView !== nil)
{
_outerScrollView?.scrollEnabled = true;
_outerScrollView = nil;
}
}
}
private func performPanChange(var #translation: CGPoint) -> Bool
{
if (isAnyAxisInverted && _closestDataSetToTouch !== nil
&& getAxis(_closestDataSetToTouch.axisDependency).isInverted)
{
if (self is HorizontalBarChartView)
{
translation.x = -translation.x;
}
else
{
translation.y = -translation.y;
}
}
var originalMatrix = _viewPortHandler.touchMatrix;
var matrix = CGAffineTransformMakeTranslation(translation.x, translation.y);
matrix = CGAffineTransformConcat(originalMatrix, matrix);
matrix = _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true);
if (delegate !== nil)
{
delegate?.chartTranslated?(self, dX: translation.x, dY: translation.y);
}
// Did we managed to actually drag or did we reach the edge?
return matrix.tx != originalMatrix.tx || matrix.ty != originalMatrix.ty;
}
public func stopDeceleration()
{
if (_decelerationDisplayLink !== nil)
{
_decelerationDisplayLink.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes);
_decelerationDisplayLink = nil;
}
}
@objc private func decelerationLoop()
{
var currentTime = CACurrentMediaTime();
_decelerationVelocity.x *= self.dragDecelerationFrictionCoef;
_decelerationVelocity.y *= self.dragDecelerationFrictionCoef;
var timeInterval = CGFloat(currentTime - _decelerationLastTime);
var distance = CGPoint(
x: _decelerationVelocity.x * timeInterval,
y: _decelerationVelocity.y * timeInterval
);
if (!performPanChange(translation: distance))
{
// We reached the edge, stop
_decelerationVelocity.x = 0.0;
_decelerationVelocity.y = 0.0;
}
_decelerationLastTime = currentTime;
if (abs(_decelerationVelocity.x) < 0.001 && abs(_decelerationVelocity.y) < 0.001)
{
stopDeceleration();
}
}
public override func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool
{
if (!super.gestureRecognizerShouldBegin(gestureRecognizer))
{
return false;
}
if (gestureRecognizer == _panGestureRecognizer)
{
if (_dataNotSet || !_dragEnabled || !self.hasNoDragOffset ||
(self.isFullyZoomedOut && !self.isHighlightPerDragEnabled))
{
return false;
}
}
else if (gestureRecognizer == _pinchGestureRecognizer)
{
if (_dataNotSet || (!_pinchZoomEnabled && !_scaleXEnabled && !_scaleYEnabled))
{
return false;
}
}
return true;
}
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool
{
if ((gestureRecognizer.isKindOfClass(UIPinchGestureRecognizer) &&
otherGestureRecognizer.isKindOfClass(UIPanGestureRecognizer)) ||
(gestureRecognizer.isKindOfClass(UIPanGestureRecognizer) &&
otherGestureRecognizer.isKindOfClass(UIPinchGestureRecognizer)))
{
return true;
}
if (gestureRecognizer.isKindOfClass(UIPanGestureRecognizer) &&
otherGestureRecognizer.isKindOfClass(UIPanGestureRecognizer) && (
gestureRecognizer == _panGestureRecognizer
))
{
var scrollView = self.superview;
while (scrollView !== nil && !scrollView!.isKindOfClass(UIScrollView))
{
scrollView = scrollView?.superview;
}
var foundScrollView = scrollView as? UIScrollView;
if (foundScrollView !== nil && !foundScrollView!.scrollEnabled)
{
foundScrollView = nil;
}
var scrollViewPanGestureRecognizer: UIGestureRecognizer!;
if (foundScrollView !== nil)
{
for scrollRecognizer in foundScrollView!.gestureRecognizers as! [UIGestureRecognizer]
{
if (scrollRecognizer.isKindOfClass(UIPanGestureRecognizer))
{
scrollViewPanGestureRecognizer = scrollRecognizer as! UIPanGestureRecognizer;
break;
}
}
}
if (otherGestureRecognizer === scrollViewPanGestureRecognizer)
{
_outerScrollView = foundScrollView;
return true;
}
}
return false;
}
/// MARK: Viewport modifiers
/// Zooms in by 1.4f, into the charts center. center.
public func zoomIn()
{
var matrix = _viewPortHandler.zoomIn(x: self.bounds.size.width / 2.0, y: -(self.bounds.size.height / 2.0));
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true);
}
/// Zooms out by 0.7f, from the charts center. center.
public func zoomOut()
{
var matrix = _viewPortHandler.zoomOut(x: self.bounds.size.width / 2.0, y: -(self.bounds.size.height / 2.0));
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true);
}
/// Zooms in or out by the given scale factor. x and y are the coordinates
/// (in pixels) of the zoom center.
///
/// :param: scaleX if < 1f --> zoom out, if > 1f --> zoom in
/// :param: scaleY if < 1f --> zoom out, if > 1f --> zoom in
/// :param: x
/// :param: y
public func zoom(scaleX: CGFloat, scaleY: CGFloat, x: CGFloat, y: CGFloat)
{
var matrix = _viewPortHandler.zoom(scaleX: scaleX, scaleY: scaleY, x: x, y: -y);
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true);
}
/// Resets all zooming and dragging and makes the chart fit exactly it's bounds.
public func fitScreen()
{
var matrix = _viewPortHandler.fitScreen();
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true);
}
/// Sets the minimum scale value to which can be zoomed out. 1f = fitScreen
public func setScaleMinima(scaleX: CGFloat, scaleY: CGFloat)
{
_viewPortHandler.setMinimumScaleX(scaleX);
_viewPortHandler.setMinimumScaleY(scaleY);
}
/// Sets the size of the area (range on the x-axis) that should be maximum
/// visible at once. If this is e.g. set to 10, no more than 10 values on the
/// x-axis can be viewed at once without scrolling.
public func setVisibleXRange(xRange: CGFloat)
{
var xScale = _deltaX / (xRange);
_viewPortHandler.setMinimumScaleX(xScale);
}
/// Sets the size of the area (range on the y-axis) that should be maximum visible at once.
///
/// :param: yRange
/// :param: axis - the axis for which this limit should apply
public func setVisibleYRange(yRange: CGFloat, axis: ChartYAxis.AxisDependency)
{
var yScale = getDeltaY(axis) / yRange;
_viewPortHandler.setMinimumScaleY(yScale);
}
/// Moves the left side of the current viewport to the specified x-index.
public func moveViewToX(xIndex: Int)
{
if (_viewPortHandler.hasChartDimens)
{
var pt = CGPoint(x: CGFloat(xIndex), y: 0.0);
getTransformer(.Left).pointValueToPixel(&pt);
_viewPortHandler.centerViewPort(pt: pt, chart: self);
}
else
{
_sizeChangeEventActions.append({[weak self] () in self?.moveViewToX(xIndex); });
}
}
/// Centers the viewport to the specified y-value on the y-axis.
///
/// :param: yValue
/// :param: axis - which axis should be used as a reference for the y-axis
public func moveViewToY(yValue: CGFloat, axis: ChartYAxis.AxisDependency)
{
if (_viewPortHandler.hasChartDimens)
{
var valsInView = getDeltaY(axis) / _viewPortHandler.scaleY;
var pt = CGPoint(x: 0.0, y: yValue + valsInView / 2.0);
getTransformer(axis).pointValueToPixel(&pt);
_viewPortHandler.centerViewPort(pt: pt, chart: self);
}
else
{
_sizeChangeEventActions.append({[weak self] () in self?.moveViewToY(yValue, axis: axis); });
}
}
/// This will move the left side of the current viewport to the specified x-index on the x-axis, and center the viewport to the specified y-value on the y-axis.
///
/// :param: xIndex
/// :param: yValue
/// :param: axis - which axis should be used as a reference for the y-axis
public func moveViewTo(#xIndex: Int, yValue: CGFloat, axis: ChartYAxis.AxisDependency)
{
if (_viewPortHandler.hasChartDimens)
{
var valsInView = getDeltaY(axis) / _viewPortHandler.scaleY;
var pt = CGPoint(x: CGFloat(xIndex), y: yValue + valsInView / 2.0);
getTransformer(axis).pointValueToPixel(&pt);
_viewPortHandler.centerViewPort(pt: pt, chart: self);
}
else
{
_sizeChangeEventActions.append({[weak self] () in self?.moveViewTo(xIndex: xIndex, yValue: yValue, axis: axis); });
}
}
/// This will move the center of the current viewport to the specified x-index and y-value.
///
/// :param: xIndex
/// :param: yValue
/// :param: axis - which axis should be used as a reference for the y-axis
public func centerViewTo(#xIndex: Int, yValue: CGFloat, axis: ChartYAxis.AxisDependency)
{
if (_viewPortHandler.hasChartDimens)
{
var valsInView = getDeltaY(axis) / _viewPortHandler.scaleY;
var xsInView = CGFloat(xAxis.values.count) / _viewPortHandler.scaleX;
var pt = CGPoint(x: CGFloat(xIndex) - xsInView / 2.0, y: yValue + valsInView / 2.0);
getTransformer(axis).pointValueToPixel(&pt);
_viewPortHandler.centerViewPort(pt: pt, chart: self);
}
else
{
_sizeChangeEventActions.append({[weak self] () in self?.centerViewTo(xIndex: xIndex, yValue: yValue, axis: axis); });
}
}
/// Sets custom offsets for the current ViewPort (the offsets on the sides of the actual chart window). Setting this will prevent the chart from automatically calculating it's offsets. Use resetViewPortOffsets() to undo this.
public func setViewPortOffsets(#left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat)
{
_customViewPortEnabled = true;
if (NSThread.isMainThread())
{
self._viewPortHandler.restrainViewPort(offsetLeft: left, offsetTop: top, offsetRight: right, offsetBottom: bottom);
prepareOffsetMatrix();
prepareValuePxMatrix();
}
else
{
dispatch_async(dispatch_get_main_queue(), {
self.setViewPortOffsets(left: left, top: top, right: right, bottom: bottom);
});
}
}
/// Resets all custom offsets set via setViewPortOffsets(...) method. Allows the chart to again calculate all offsets automatically.
public func resetViewPortOffsets()
{
_customViewPortEnabled = false;
calculateOffsets();
}
// MARK: - Accessors
/// Returns the delta-y value (y-value range) of the specified axis.
public func getDeltaY(axis: ChartYAxis.AxisDependency) -> CGFloat
{
if (axis == .Left)
{
return CGFloat(leftAxis.axisRange);
}
else
{
return CGFloat(rightAxis.axisRange);
}
}
/// Returns the position (in pixels) the provided Entry has inside the chart view
public func getPosition(e: ChartDataEntry, axis: ChartYAxis.AxisDependency) -> CGPoint
{
var vals = CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.value));
getTransformer(axis).pointValueToPixel(&vals);
return vals;
}
/// the number of maximum visible drawn values on the chart
/// only active when setDrawValues() is enabled
public var maxVisibleValueCount: Int
{
get
{
return _maxVisibleValueCount;
}
set
{
_maxVisibleValueCount = newValue;
}
}
/// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling).
public var dragEnabled: Bool
{
get
{
return _dragEnabled;
}
set
{
if (_dragEnabled != newValue)
{
_dragEnabled = newValue;
}
}
}
/// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling).
public var isDragEnabled: Bool
{
return dragEnabled;
}
/// is scaling enabled? (zooming in and out by gesture) for the chart (this does not affect dragging).
public func setScaleEnabled(enabled: Bool)
{
if (_scaleXEnabled != enabled || _scaleYEnabled != enabled)
{
_scaleXEnabled = enabled;
_scaleYEnabled = enabled;
_pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled;
}
}
public var scaleXEnabled: Bool
{
get
{
return _scaleXEnabled
}
set
{
if (_scaleXEnabled != newValue)
{
_scaleXEnabled = newValue;
_pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled;
}
}
}
public var scaleYEnabled: Bool
{
get
{
return _scaleYEnabled
}
set
{
if (_scaleYEnabled != newValue)
{
_scaleYEnabled = newValue;
_pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled;
}
}
}
public var isScaleXEnabled: Bool { return scaleXEnabled; }
public var isScaleYEnabled: Bool { return scaleYEnabled; }
/// flag that indicates if double tap zoom is enabled or not
public var doubleTapToZoomEnabled: Bool
{
get
{
return _doubleTapToZoomEnabled;
}
set
{
if (_doubleTapToZoomEnabled != newValue)
{
_doubleTapToZoomEnabled = newValue;
_doubleTapGestureRecognizer.enabled = _doubleTapToZoomEnabled;
}
}
}
/// :returns: true if zooming via double-tap is enabled false if not.
/// :default: true
public var isDoubleTapToZoomEnabled: Bool
{
return doubleTapToZoomEnabled;
}
/// flag that indicates if highlighting per dragging over a fully zoomed out chart is enabled
public var highlightPerDragEnabled = true
/// If set to true, highlighting per dragging over a fully zoomed out chart is enabled
/// You might want to disable this when using inside a UIScrollView
/// :default: true
public var isHighlightPerDragEnabled: Bool
{
return highlightPerDragEnabled;
}
/// if set to true, the highlight indicator (lines for linechart, dark bar for barchart) will be drawn upon selecting values.
public var highlightIndicatorEnabled = true
/// If set to true, the highlight indicator (vertical line for LineChart and
/// ScatterChart, dark bar overlay for BarChart) that gives visual indication
/// that an Entry has been selected will be drawn upon selecting values. This
/// does not depend on the MarkerView.
/// :default: true
public var isHighlightIndicatorEnabled: Bool
{
return highlightIndicatorEnabled;
}
/// :returns: true if drawing the grid background is enabled, false if not.
/// :default: true
public var isDrawGridBackgroundEnabled: Bool
{
return drawGridBackgroundEnabled;
}
/// :returns: true if drawing the borders rectangle is enabled, false if not.
/// :default: false
public var isDrawBordersEnabled: Bool
{
return drawBordersEnabled;
}
/// Returns the Highlight object (contains x-index and DataSet index) of the selected value at the given touch point inside the Line-, Scatter-, or CandleStick-Chart.
public func getHighlightByTouchPoint(var pt: CGPoint) -> ChartHighlight!
{
if (_dataNotSet || _data === nil)
{
println("Can't select by touch. No data set.");
return nil;
}
var valPt = CGPoint();
valPt.x = pt.x;
valPt.y = 0.0;
// take any transformer to determine the x-axis value
_leftAxisTransformer.pixelToValue(&valPt);
var xTouchVal = valPt.x;
var base = floor(xTouchVal);
var touchOffset = _deltaX * 0.025;
// touch out of chart
if (xTouchVal < -touchOffset || xTouchVal > _deltaX + touchOffset)
{
return nil;
}
if (base < 0.0)
{
base = 0.0;
}
if (base >= _deltaX)
{
base = _deltaX - 1.0;
}
var xIndex = Int(base);
// check if we are more than half of a x-value or not
if (xTouchVal - base > 0.5)
{
xIndex = Int(base + 1.0);
}
var valsAtIndex = getYValsAtIndex(xIndex);
var leftdist = ChartUtils.getMinimumDistance(valsAtIndex, val: Float(pt.y), axis: .Left);
var rightdist = ChartUtils.getMinimumDistance(valsAtIndex, val: Float(pt.y), axis: .Right);
if (_data!.getFirstRight() === nil)
{
rightdist = FLT_MAX;
}
if (_data!.getFirstLeft() === nil)
{
leftdist = FLT_MAX;
}
var axis: ChartYAxis.AxisDependency = leftdist < rightdist ? .Left : .Right;
var dataSetIndex = ChartUtils.closestDataSetIndex(valsAtIndex, value: Float(pt.y), axis: axis);
if (dataSetIndex == -1)
{
return nil;
}
return ChartHighlight(xIndex: xIndex, dataSetIndex: dataSetIndex);
}
/// Returns an array of SelInfo objects for the given x-index. The SelInfo
/// objects give information about the value at the selected index and the
/// DataSet it belongs to.
public func getYValsAtIndex(xIndex: Int) -> [ChartSelInfo]
{
var vals = [ChartSelInfo]();
var pt = CGPoint();
for (var i = 0, count = _data.dataSetCount; i < count; i++)
{
var dataSet = _data.getDataSetByIndex(i);
if (dataSet === nil)
{
continue;
}
// extract all y-values from all DataSets at the given x-index
var yVal = dataSet!.yValForXIndex(xIndex);
pt.y = CGFloat(yVal);
getTransformer(dataSet!.axisDependency).pointValueToPixel(&pt);
if (!isnan(pt.y))
{
vals.append(ChartSelInfo(value: Float(pt.y), dataSetIndex: i, dataSet: dataSet!));
}
}
return vals;
}
/// Returns the x and y values in the chart at the given touch point
/// (encapsulated in a PointD). This method transforms pixel coordinates to
/// coordinates / values in the chart. This is the opposite method to
/// getPixelsForValues(...).
public func getValueByTouchPoint(var #pt: CGPoint, axis: ChartYAxis.AxisDependency) -> CGPoint
{
getTransformer(axis).pixelToValue(&pt);
return pt;
}
/// Transforms the given chart values into pixels. This is the opposite
/// method to getValueByTouchPoint(...).
public func getPixelForValue(x: Float, y: Float, axis: ChartYAxis.AxisDependency) -> CGPoint
{
var pt = CGPoint(x: CGFloat(x), y: CGFloat(y));
getTransformer(axis).pointValueToPixel(&pt);
return pt;
}
/// returns the y-value at the given touch position (must not necessarily be
/// a value contained in one of the datasets)
public func getYValueByTouchPoint(#pt: CGPoint, axis: ChartYAxis.AxisDependency) -> CGFloat
{
return getValueByTouchPoint(pt: pt, axis: axis).y;
}
/// returns the Entry object displayed at the touched position of the chart
public func getEntryByTouchPoint(pt: CGPoint) -> ChartDataEntry!
{
var h = getHighlightByTouchPoint(pt);
if (h !== nil)
{
return _data!.getEntryForHighlight(h!);
}
return nil;
}
///returns the DataSet object displayed at the touched position of the chart
public func getDataSetByTouchPoint(pt: CGPoint) -> BarLineScatterCandleChartDataSet!
{
var h = getHighlightByTouchPoint(pt);
if (h !== nil)
{
return _data.getDataSetByIndex(h.dataSetIndex) as! BarLineScatterCandleChartDataSet!;
}
return nil;
}
/// Returns the lowest x-index (value on the x-axis) that is still visible on he chart.
public var lowestVisibleXIndex: Int
{
var pt = CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom);
getTransformer(.Left).pixelToValue(&pt);
return (pt.x <= 0.0) ? 0 : Int(pt.x + 1.0);
}
/// Returns the highest x-index (value on the x-axis) that is still visible on the chart.
public var highestVisibleXIndex: Int
{
var pt = CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom);
getTransformer(.Left).pixelToValue(&pt);
return (Int(pt.x) >= _data.xValCount) ? _data.xValCount - 1 : Int(pt.x);
}
/// returns the current x-scale factor
public var scaleX: CGFloat
{
if (_viewPortHandler === nil)
{
return 1.0;
}
return _viewPortHandler.scaleX;
}
/// returns the current y-scale factor
public var scaleY: CGFloat
{
if (_viewPortHandler === nil)
{
return 1.0;
}
return _viewPortHandler.scaleY;
}
/// if the chart is fully zoomed out, return true
public var isFullyZoomedOut: Bool { return _viewPortHandler.isFullyZoomedOut; }
/// Returns the left y-axis object. In the horizontal bar-chart, this is the
/// top axis.
public var leftAxis: ChartYAxis
{
return _leftAxis;
}
/// Returns the right y-axis object. In the horizontal bar-chart, this is the
/// bottom axis.
public var rightAxis: ChartYAxis { return _rightAxis; }
/// Returns the y-axis object to the corresponding AxisDependency. In the
/// horizontal bar-chart, LEFT == top, RIGHT == BOTTOM
public func getAxis(axis: ChartYAxis.AxisDependency) -> ChartYAxis
{
if (axis == .Left)
{
return _leftAxis;
}
else
{
return _rightAxis;
}
}
/// Returns the object representing all x-labels, this method can be used to
/// acquire the XAxis object and modify it (e.g. change the position of the
/// labels)
public var xAxis: ChartXAxis
{
return _xAxis;
}
/// flag that indicates if pinch-zoom is enabled. if true, both x and y axis can be scaled with 2 fingers, if false, x and y axis can be scaled separately
public var pinchZoomEnabled: Bool
{
get
{
return _pinchZoomEnabled;
}
set
{
if (_pinchZoomEnabled != newValue)
{
_pinchZoomEnabled = newValue;
_pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled;
}
}
}
/// returns true if pinch-zoom is enabled, false if not
/// :default: false
public var isPinchZoomEnabled: Bool { return pinchZoomEnabled; }
/// Set an offset in dp that allows the user to drag the chart over it's
/// bounds on the x-axis.
public func setDragOffsetX(offset: CGFloat)
{
_viewPortHandler.setDragOffsetX(offset);
}
/// Set an offset in dp that allows the user to drag the chart over it's
/// bounds on the y-axis.
public func setDragOffsetY(offset: CGFloat)
{
_viewPortHandler.setDragOffsetY(offset);
}
/// :returns: true if both drag offsets (x and y) are zero or smaller.
public var hasNoDragOffset: Bool { return _viewPortHandler.hasNoDragOffset; }
public var xAxisRenderer: ChartXAxisRenderer { return _xAxisRenderer; }
public var leftYAxisRenderer: ChartYAxisRenderer { return _leftYAxisRenderer; }
public var rightYAxisRenderer: ChartYAxisRenderer { return _rightYAxisRenderer; }
public override var chartYMax: Float
{
return max(leftAxis.axisMaximum, rightAxis.axisMaximum);
}
public override var chartYMin: Float
{
return min(leftAxis.axisMinimum, rightAxis.axisMinimum);
}
/// Returns true if either the left or the right or both axes are inverted.
public var isAnyAxisInverted: Bool
{
return _leftAxis.isInverted || _rightAxis.isInverted;
}
/// flag that indicates if auto scaling on the y axis is enabled.
/// if yes, the y axis automatically adjusts to the min and max y values of the current x axis range whenever the viewport changes
public var autoScaleMinMaxEnabled: Bool
{
get { return _autoScaleMinMaxEnabled; }
set { _autoScaleMinMaxEnabled = newValue; }
}
/// returns true if auto scaling on the y axis is enabled.
/// :default: false
public var isAutoScaleMinMaxEnabled : Bool { return autoScaleMinMaxEnabled; }
/// Sets a minimum width to the specified y axis.
public func setYAxisMinWidth(which: ChartYAxis.AxisDependency, width: CGFloat)
{
if (which == .Left)
{
_leftAxis.minWidth = width;
}
else
{
_rightAxis.minWidth = width;
}
}
/// Returns the (custom) minimum width of the specified Y axis.
/// :default 0.0
public func getYAxisMinWidth(which: ChartYAxis.AxisDependency) -> CGFloat
{
if (which == .Left)
{
return _leftAxis.minWidth;
}
else
{
return _rightAxis.minWidth;
}
}
/// Sets a maximum width to the specified y axis.
/// Zero (0.0) means there's no maximum width
public func setYAxisMaxWidth(which: ChartYAxis.AxisDependency, width: CGFloat)
{
if (which == .Left)
{
_leftAxis.maxWidth = width;
}
else
{
_rightAxis.maxWidth = width;
}
}
/// Returns the (custom) maximum width of the specified Y axis.
/// Zero (0.0) means there's no maximum width
/// :default 0.0 (no maximum specified)
public func getYAxisMaxWidth(which: ChartYAxis.AxisDependency) -> CGFloat
{
if (which == .Left)
{
return _leftAxis.maxWidth;
}
else
{
return _rightAxis.maxWidth;
}
}
/// Returns the width of the specified y axis.
public func getYAxisWidth(which: ChartYAxis.AxisDependency) -> CGFloat
{
if (which == .Left)
{
return _leftAxis.requiredSize().width;
}
else
{
return _rightAxis.requiredSize().width;
}
}
}
/// Default formatter that calculates the position of the filled line.
internal class BarLineChartFillFormatter: NSObject, ChartFillFormatter
{
private weak var _chart: BarLineChartViewBase!;
internal init(chart: BarLineChartViewBase)
{
_chart = chart;
}
internal func getFillLinePosition(#dataSet: LineChartDataSet, data: LineChartData, chartMaxY: Float, chartMinY: Float) -> CGFloat
{
var fillMin = CGFloat(0.0);
if (dataSet.yMax > 0.0 && dataSet.yMin < 0.0)
{
fillMin = 0.0;
}
else
{
if (!_chart.getAxis(dataSet.axisDependency).isStartAtZeroEnabled)
{
var max: Float, min: Float;
if (data.yMax > 0.0)
{
max = 0.0;
}
else
{
max = chartMaxY;
}
if (data.yMin < 0.0)
{
min = 0.0;
}
else
{
min = chartMinY;
}
fillMin = CGFloat(dataSet.yMin >= 0.0 ? min : max);
}
else
{
fillMin = 0.0;
}
}
return fillMin;
}
}
|
apache-2.0
|
5bea9cbe1dc011ccb69a2d5c93558dea
| 33.633495 | 229 | 0.577633 | 5.566761 | false | false | false | false |
csujedihy/Flicks
|
Pods/Cosmos/Cosmos/CosmosLocalizedRating.swift
|
2
|
3030
|
import Foundation
/**
Returns the word "Rating" in user's language. It is used for voice-over in accessibility mode.
*/
struct CosmosLocalizedRating {
static var defaultText = "Rating"
static var localizedRatings = [
"ar": "تصنيف",
"bg": "Рейтинг",
"cy": "Sgôr",
"da": "Rating",
"de": "Bewertung",
"el": "Βαθμολογία",
"en": defaultText,
"es": "Valorar",
"et": "Reiting",
"fi": "Luokitus",
"fr": "De note",
"he": "דירוג",
"hi": "रेटिंग",
"hr": "Ocjena",
"hu": "Értékelés",
"id": "Peringkat",
"it": "Voto",
"ko": "등급",
"lt": "Reitingas",
"lv": "Vērtējums",
"nl": "Rating",
"no": "Vurdering",
"pl": "Ocena",
"pt": "Classificação",
"ro": "Evaluare",
"ru": "Рейтинг",
"sk": "Hodnotenie",
"sl": "Ocena",
"sr": "Рејтинг",
"sw": "Rating",
"th": "การจัดอันดับ",
"tr": "Oy verin",
"cs": "Hodnocení",
"uk": "Рейтинг",
"vi": "Đánh giá",
"zh": "评分"
]
static var ratingTranslation: String {
let languages = preferredLanguages(NSLocale.preferredLanguages())
return ratingInPreferredLanguage(languages)
}
/**
Returns the word "Rating" in user's language.
- parameter language: ISO 639-1 language code. Example: 'en'.
*/
static func translation(language: String) -> String? {
return localizedRatings[language]
}
/**
Returns translation using the preferred language.
- parameter preferredLanguages: Array of preferred language codes (ISO 639-1). The first element is most preferred.
- parameter localizedText: Dictionary with translations for the languages. The keys are ISO 639-1 language codes and values are the text.
- parameter fallbackTranslation: The translation text used if no translation found for the preferred languages.
- returns: Translation for the preferred language.
*/
static func translationInPreferredLanguage(preferredLanguages: [String],
localizedText: [String: String],
fallbackTranslation: String) -> String {
for language in preferredLanguages {
if let translatedText = translation(language) {
return translatedText
}
}
return fallbackTranslation
}
static func ratingInPreferredLanguage(preferredLanguages: [String]) -> String {
return translationInPreferredLanguage(preferredLanguages,
localizedText: localizedRatings,
fallbackTranslation: defaultText)
}
static func preferredLanguages(preferredLocales: [String]) -> [String] {
return preferredLocales.map { element in
let dashSeparated = element.componentsSeparatedByString("-")
if dashSeparated.count > 1 { return dashSeparated[0] }
let underscoreSeparated = element.componentsSeparatedByString("_")
if underscoreSeparated.count > 1 { return underscoreSeparated[0] }
return element
}
}
}
|
gpl-3.0
|
686ab7363e8fa61e0031d4efe4cf370d
| 25.6 | 139 | 0.639098 | 3.770619 | false | false | false | false |
Holmusk/HMRequestFramework-iOS
|
HMRequestFramework/database/coredata/model/HMCDSection+DataSource.swift
|
1
|
2493
|
//
// HMCDSection+DataSource.swift
// HMRequestFramework
//
// Created by Hai Pham on 8/26/17.
// Copyright © 2017 Holmusk. All rights reserved.
//
import Differentiator
/// Instead of asking HMCDSection to implement AnimatableSectionModelType, we
/// can delegate that to a subtype. This is because the FRC requires the section
/// objects to be of Any generics at first when delegate methods are called.
public struct HMCDAnimatableSection<V: Equatable & IdentifiableType> {
public let indexTitle: String?
public let name: String
public let numberOfObjects: Int
public let objects: [V]
public init(indexTitle: String?,
name: String,
numberOfObjects: Int,
objects: [V]) {
self.indexTitle = indexTitle
self.name = name
self.numberOfObjects = numberOfObjects
self.objects = Array(objects)
}
}
extension HMCDAnimatableSection: HMCDSectionType {}
extension HMCDAnimatableSection: AnimatableSectionModelType {
public typealias Item = V
public typealias Identity = String
public var items: [Item] {
return objects
}
public var identity: Identity {
return name
}
public init(original: HMCDAnimatableSection, items: [Item]) {
self.init(indexTitle: original.indexTitle,
name: original.name,
numberOfObjects: original.numberOfObjects,
objects: items)
}
/// Convenience method to map to an animatable section.
///
/// - Parameter f: Mapper function.
/// - Returns: A HMCDAnimatableSection instance.
public func mapObjects<V2>(_ f: ([V]) throws -> [V2]?) -> HMCDAnimatableSection<V2> {
return mapObjects(f, HMCDAnimatableSection<V2>.self)
}
}
extension HMCDSection {
/// Get a reload section model.
///
/// - Returns: A SectionModel instance.
public func reloadModel() -> SectionModel<String,V> {
return SectionModel(model: name, items: objects)
}
}
extension HMCDSection where V: Equatable, V: IdentifiableType {
/// Get an animatable section model.
///
/// - Returns: A AnimatableSectionModel instance.
public func animatableModel() -> AnimatableSectionModel<String,V> {
return AnimatableSectionModel(model: name, items: objects)
}
public func animatableSection() -> HMCDAnimatableSection<V> {
return HMCDAnimatableSection(self)
}
}
|
apache-2.0
|
d702e27062b4559405dd166dce351118
| 29.024096 | 89 | 0.654093 | 4.693032 | false | false | false | false |
BonifyByForteil/react-native-piwik
|
ios/MatomoTracker/Event/Visitor.swift
|
1
|
1494
|
//
// Visitor.swift
// PiwikTracker
//
// Created by Cornelius Horstmann on 26.02.17.
// Copyright © 2017 PIWIK. All rights reserved.
//
import Foundation
struct Visitor {
/// Unique ID per visitor (device in this case). Should be
/// generated upon first start and never changed after.
/// api-key: _id
let id: String
/// A unique visitor ID, possuble to override by the SDK user.
/// api-key: cid
let forcedId: String?
/// An optional user identifier such as email or username.
/// api-key: uid
let userId: String?
}
extension Visitor {
static func current(in matomoUserDefaults: MatomoUserDefaults) -> Visitor {
var matomoUserDefaults = matomoUserDefaults
let id: String
if let existingId = matomoUserDefaults.clientId {
id = existingId
} else {
let newId = newVisitorID()
matomoUserDefaults.clientId = newId
id = newId
}
let forcedVisitorId = matomoUserDefaults.forcedVisitorId
let userId = matomoUserDefaults.visitorUserId
return Visitor(id: id, forcedId: forcedVisitorId, userId: userId)
}
static func newVisitorID() -> String {
let uuid = UUID().uuidString
let sanitizedUUID = uuid.replacingOccurrences(of: "-", with: "")
let start = sanitizedUUID.startIndex
let end = sanitizedUUID.index(start, offsetBy: 16)
return String(sanitizedUUID[start..<end])
}
}
|
mit
|
c1b7ed91dfd76b4069873d4d3ba3fa69
| 29.469388 | 79 | 0.637642 | 4.496988 | false | false | false | false |
Limon-O-O/Convex
|
Convex/TableViewController.swift
|
1
|
3238
|
//
// TableViewController.swift
// Example
//
// Created by Limon on 3/19/16.
// Copyright © 2016 Convex. All rights reserved.
//
import UIKit
public struct Constant {
public static let TabbarItemsTitleKey = "tabBarItemTitle"
public static let TabbarItemsImageKey = "tabBarItemImage"
public static let TabbarItemsSelectedImageKey = "tabBarItemSelectedImage"
}
public protocol PlusButton {
var multiplerInCenterY: CGFloat { get set }
var indexOfPlusButtonInTabBar: Int { get set }
}
public class TabBarController: UITabBarController {
public var tabBarItemsAttributes: [[String: String]]?
public override var viewControllers: [UIViewController]? {
didSet {
setViewControllers()
}
}
static weak var plusButton: UIButton?
static var tabbarItemsCount: Int = 0
private init() {
super.init(nibName: nil, bundle: nil)
}
public convenience init<T: UIButton where T: PlusButton>(button: T) {
TabBarController.plusButton = button
self.init()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func viewDidLoad() {
super.viewDidLoad()
toolBarSetup()
}
/// 利用 KVC 把系统的 tabBar 类型改为自定义类型
private func toolBarSetup() {
setValue(TabBar(), forKey: "tabBar")
}
private func setViewControllers() {
guard let unwrappedTabBarItemsAttributes = tabBarItemsAttributes, unwrappedViewControllers = viewControllers
where !unwrappedTabBarItemsAttributes.isEmpty && !unwrappedViewControllers.isEmpty && unwrappedTabBarItemsAttributes.count == unwrappedViewControllers.count else {
return
}
viewControllers?.forEach {
$0.willMoveToParentViewController(nil)
$0.view.removeFromSuperview()
$0.removeFromParentViewController()
}
TabBarController.tabbarItemsCount = unwrappedViewControllers.count
for (index, viewController) in unwrappedViewControllers.enumerate() {
guard let title = unwrappedTabBarItemsAttributes[index][Constant.TabbarItemsTitleKey], normalImageName = unwrappedTabBarItemsAttributes[index][Constant.TabbarItemsImageKey], selectedImageName = unwrappedTabBarItemsAttributes[index][Constant.TabbarItemsSelectedImageKey] else {
return
}
addOneChildViewController(viewController, title: title, normalImageName: normalImageName, selectedImageName: selectedImageName)
}
}
private func addOneChildViewController(viewController: UIViewController, title: String, normalImageName: String, selectedImageName: String) {
viewController.tabBarItem.title = title
let normalImage = UIImage(named: normalImageName)
normalImage?.imageWithRenderingMode(.AlwaysOriginal)
viewController.tabBarItem.image = normalImage
let selectedImage = UIImage(named: selectedImageName)
normalImage?.imageWithRenderingMode(.AlwaysOriginal)
viewController.tabBarItem.image = selectedImage
addChildViewController(viewController)
}
}
|
mit
|
9f8668e0e2a98a637474773e2e6dd060
| 32.757895 | 288 | 0.702838 | 5.53886 | false | false | false | false |
greycats/Greycats.swift
|
Greycats/Graphics/Path.swift
|
1
|
2773
|
//
// Path.swift
// Greycats
//
// Created by Rex Sheng on 8/1/16.
// Copyright (c) 2016 Interactive Labs. All rights reserved.
//
// This is useful when you want to create a Button in IB, but also want to set the image part as a BezierPath.
import UIKit
public protocol Graphic {
func image(_ selected: Bool, tintColor: UIColor) -> CGImage?
init()
}
public protocol SVG: Graphic {
var path: UIBezierPath { get }
}
public protocol GraphicDesignable {
var graphicClass: String? { get set }
var graphic: Graphic? { get }
}
extension GraphicDesignable {
public var graphic: Graphic? {
if let value = graphicClass,
let instance = NSClassFromString(value) as? Graphic.Type {
return instance.init()
}
return nil
}
}
@IBDesignable
open class GraphicButton: UIButton, GraphicDesignable {
@IBInspectable public var graphicClass: String? {
didSet {
setImageToGraphic()
}
}
override open func tintColorDidChange() {
super.tintColorDidChange()
setImageToGraphic()
}
fileprivate func setImageToGraphic() {
if let instance = self.graphic {
if let image = instance.image(true, tintColor: tintColor) {
setImage(UIImage(cgImage: image, scale: UIScreen.main.scale, orientation: .up), for: .selected)
}
if let image = instance.image(false, tintColor: tintColor) {
setImage(UIImage(cgImage: image, scale: UIScreen.main.scale, orientation: .up), for: UIControl.State())
}
}
}
}
public protocol HasDefaultGraphic: AnyObject {
func defaultTintColor() -> UIColor?
var image: UIImage? { get set }
}
extension HasDefaultGraphic where Self: GraphicDesignable {
fileprivate func setImageToGraphic() {
if let graphic = self.graphic {
if let image = graphic.image(false, tintColor: defaultTintColor() ?? UIColor.white) {
self.image = UIImage(cgImage: image, scale: UIScreen.main.scale, orientation: .up)
}
}
}
}
extension UIBarButtonItem: HasDefaultGraphic {
public func defaultTintColor() -> UIColor? {
return tintColor
}
}
extension UIImageView: HasDefaultGraphic {
public func defaultTintColor() -> UIColor? {
return tintColor
}
}
@IBDesignable
public class GraphicBarButtonItem: UIBarButtonItem, GraphicDesignable {
@IBInspectable public var graphicClass: String? {
didSet {
setImageToGraphic()
}
}
}
@IBDesignable
public class GraphicImageView: UIImageView, GraphicDesignable {
@IBInspectable public var graphicClass: String? {
didSet {
setImageToGraphic()
}
}
}
|
mit
|
aca8d408f2de77e4d00f4600dedf7bf1
| 25.409524 | 119 | 0.640462 | 4.508943 | false | false | false | false |
Ibrahimohib/PDA
|
PDA/PDA/ViewController.swift
|
1
|
1408
|
//
// ViewController.swift
// PDA
//
// Created by Mohib Ibrahim on 11/2/16.
// Copyright © 2016 xula.edu. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBAction func goalsButton(_ sender: Any) {
}
@IBOutlet var goalsText: UILabel!
@IBAction func calcButton(_ sender: Any) {
}
@IBAction func toolsButton(_ sender: Any) {
}
@IBOutlet var toolsButtonOut: UIButton!
@IBOutlet var calcButtonOut: UIButton!
@IBOutlet var calcText: UILabel!
@IBOutlet var toolsText: UILabel!
@IBOutlet var toolsrealOut: UIButton!
override func viewDidLoad() {
self.view.layoutIfNeeded()
super.viewDidLoad()
goalsText.clipsToBounds = true
calcText.clipsToBounds = true
toolsText.clipsToBounds = true
toolsButtonOut.clipsToBounds = true
calcButtonOut.clipsToBounds = true
toolsrealOut.clipsToBounds = true
goalsText.layer.cornerRadius = 0
calcText.layer.cornerRadius = 20
toolsText.layer.cornerRadius = 20
toolsButtonOut.layer.cornerRadius = 30
calcButtonOut.layer.cornerRadius = 30
toolsrealOut.layer.cornerRadius = 30
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
aa4d322eff71346c3d8092504845b6be
| 25.055556 | 58 | 0.648188 | 4.583062 | false | false | false | false |
sourcebitsllc/Asset-Generator-Mac
|
XCAssetGenerator/AssetType.swift
|
1
|
5090
|
//
// XCAssetsImage.swift
// XCAssetGenerator
//
// Created by Bader on 4/3/15.
// Copyright (c) 2015 Bader Alabdulrazzaq. All rights reserved.
//
import Foundation
enum AssetType {
case Image
case Icon
case LaunchImage
static func type(#path: Path) -> AssetType {
return type(name: path.lastPathComponent)
}
static func type(#name: String) -> AssetType {
if isIcon(name) {
return .Icon
} else if isLaunchImage(name) {
return .LaunchImage
} else {
return .Image
}
}
static func isIcon(name: String) -> Bool {
return name.hasPrefix("AppIcon") || name.hasPrefix("Icon") || isMacIcon(name)
}
static func isMacIcon(name: String) -> Bool {
return name.hasPrefix("icon_")
}
static func isLaunchImage(name: String) -> Bool {
return name.hasPrefix("LaunchImage") || name.hasPrefix("Default")
}
}
struct AssetMetaData {
let attributes: AssetAttribute
let type: AssetType
private init(path: Path,type: AssetType) {
self.type = type
switch self.type {
case .Image:
self.attributes = AssetAttributeProcessor.withAsset(path)
case .Icon:
self.attributes = AssetAttributeProcessor.withIcon(path)
case .LaunchImage:
self.attributes = AssetAttributeProcessor.withLaunchImage(path)
}
}
static func create(path: Path) -> AssetMetaData {
let type = AssetType.type(path: path)
return AssetMetaData(path: path, type: type)
}
static func create(asset: Asset) -> AssetMetaData {
return create(asset.fullPath)
}
typealias AssetComparator = (XCAssetsJSON -> Bool)
var comparator: AssetComparator {
let attribute = attributes
switch type {
case .Image:
return { dict in
let sameIdiom = dict[XCAssetsJSONKeys.Idiom] as! String? == attribute.idiom
let sameScale = dict[XCAssetsJSONKeys.Scale] as! String? == attribute.scale
return sameIdiom && sameScale
}
case .Icon:
return { dict in
let sameIdiom = dict[XCAssetsJSONKeys.Idiom] as! String? == attribute.idiom
let sameScale = dict[XCAssetsJSONKeys.Scale] as! String? == attribute.scale
let sameSize = dict[XCAssetsJSONKeys.Size] as! String? == attribute.size
return sameIdiom && sameScale && sameSize
}
case .LaunchImage:
return { dict in
let sameIdiom = dict[XCAssetsJSONKeys.Idiom] as! String? == attribute.idiom
let sameScale = dict[XCAssetsJSONKeys.Scale] as! String? == attribute.scale
let sameSubtype = dict[XCAssetsJSONKeys.Subtype] as! String? == attribute.subtype
let sameOrientation = dict[XCAssetsJSONKeys.Orientation] as! String? == attribute.orientation
return sameIdiom && sameScale && sameOrientation && sameSubtype
}
}
}
}
struct Asset: Printable {
let type: AssetType
let ancestor: Path
let fullPath: Path
var name: Path {
return fullPath.lastPathComponent
}
var description: String {
return fullPath
}
/// Return path relative to its ancestor.
/// Basically fullPath - ancestor
var relativePath: Path {
return fullPath.remove([ancestor])
}
// MARK: - Initializers
init(fullPath path: Path, ancestor: Path) {
self.fullPath = path
self.ancestor = ancestor
self.type = AssetType.type(path: path)
}
// MARK: - Properties
var enclosingSet: Path {
switch type {
case .Image:
return stripKeywords(fullPath) + ".imageset"
case .Icon:
return "AppIcon.appiconset"
case .LaunchImage:
return "LaunchImage.launchimage"
}
}
// MARK: -
///
/// Removes the various keywords used in Asset Generator.
///
/// scale: @1x, @2x, @3x
/// idiom: ~iphone, ~ipad
/// extention: .png, .jpg, etc.
private func stripKeywords(path: Path) -> Path {
var name = path.lastPathComponent.stringByDeletingPathExtension.remove([GenerationKeywords.PPI2x,
GenerationKeywords.PPI3x,
GenerationKeywords.PPI1x,
GenerationKeywords.iPhone,
GenerationKeywords.iPad,
GenerationKeywords.Mac ])
return name
}
}
enum Device {
case iPhone
case iPad
case Universal
case Mac
case Watch
case NotYetKnownLol
}
|
mit
|
40254e3085a48673ce3c07803e7dd2dc
| 29.848485 | 109 | 0.549705 | 4.838403 | false | false | false | false |
v2panda/DaysofSwift
|
swift2.3/My-Spotlt/My-Spotlt/ViewController.swift
|
1
|
5187
|
//
// ViewController.swift
// My-Spotlt
//
// Created by Panda on 16/3/15.
// Copyright © 2016年 v2panda. All rights reserved.
//
import UIKit
import CoreSpotlight
import MobileCoreServices
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
@IBOutlet weak var tblMovies: UITableView!
var moviesinfo : NSMutableArray!
var selectedMovieIndex : Int!
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Movies"
loadMoviesInfo()
configureTableView()
setupSearchableContent()
}
func loadMoviesInfo () {
if let path = NSBundle.mainBundle().pathForResource("MoviesData", ofType: "plist") {
moviesinfo = NSMutableArray(contentsOfFile: path)
}
}
func configureTableView() {
tblMovies.dataSource = self
tblMovies.delegate = self
tblMovies.tableFooterView = UIView(frame: CGRectZero)
tblMovies.registerNib(UINib(nibName: "MovieSummaryCell", bundle: nil), forCellReuseIdentifier: "idCellMovieSummary")
}
// 设置Search核心代码
func setupSearchableContent() {
var searchableItems = [CSSearchableItem]()
for i in 0...(moviesinfo.count - 1) {
let movie = moviesinfo[i] as! [String: String]
let searchableItemAttributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeText as String)
// set the title
searchableItemAttributeSet.title = movie["Title"]!
// set the image
let imagePathParts = movie["Image"]!.componentsSeparatedByString(".")
searchableItemAttributeSet.thumbnailURL = NSBundle.mainBundle().URLForResource(imagePathParts[0], withExtension: imagePathParts[1])
// set the description
searchableItemAttributeSet.contentDescription = movie["Description"]!
var keywords = [String]()
let movieCategories = movie["Category"]!.componentsSeparatedByString(", ")
for movieCategory in movieCategories {
keywords.append(movieCategory)
}
let stars = movie["Stars"]!.componentsSeparatedByString(", ")
for star in stars {
keywords.append(star)
}
searchableItemAttributeSet.keywords = keywords
let searchableItem = CSSearchableItem(uniqueIdentifier: "PDA.My-Spotlt.\(i)", domainIdentifier: "movies", attributeSet: searchableItemAttributeSet)
searchableItems.append(searchableItem)
CSSearchableIndex.defaultSearchableIndex().indexSearchableItems(searchableItems) { (error) -> Void in
if error != nil {
print(error?.localizedDescription)
}
}
}
}
override func restoreUserActivityState(activity: NSUserActivity) {
if activity.activityType == CSSearchableItemActionType {
if let userInfo = activity.userInfo {
let selectedMovie = userInfo[CSSearchableItemActivityIdentifier] as! String
selectedMovieIndex = Int(selectedMovie.componentsSeparatedByString(".").last!)
performSegueWithIdentifier("idSegueShowMovieDetails", sender: self)
}
}
}
//MARK - UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if moviesinfo != nil {
return moviesinfo.count
}
return 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("idCellMovieSummary", forIndexPath: indexPath) as! MovieSummaryCell
let currentMovieInfo = moviesinfo[indexPath.row] as! [String : String]
cell.IbTitle.text = currentMovieInfo["Title"]!
cell.IbDesctiption.text = currentMovieInfo["Description"]!
cell.IbRating.text = currentMovieInfo["Rating"]!
cell.imgMovieImage.image = UIImage(named: currentMovieInfo["Image"]!)
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 100
}
//MARK - UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
selectedMovieIndex = indexPath.row
performSegueWithIdentifier("idSegueShowMovieDetails", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let identifier = segue.identifier {
if identifier == "idSegueShowMovieDetails" {
let movieDetailsViewController = segue.destinationViewController as! DetailViewController
movieDetailsViewController.movieInfo = moviesinfo[selectedMovieIndex] as! [String:String]
}
}
}
}
|
mit
|
14cf6d39690f62ec08ec343776ba66ec
| 35.422535 | 159 | 0.633217 | 5.830891 | false | false | false | false |
mercadopago/px-ios
|
MercadoPagoSDK/MercadoPagoSDK/Core/PXDeviceSize.swift
|
1
|
835
|
import UIKit
public class PXDeviceSize {
// Breakpoints took from https://developer.apple.com/design/human-interface-guidelines/ios/visual-design/adaptivity-and-layout/
static let smallBreakpoint: CGFloat = 568
static let regularBreakpoint: CGFloat = 736
static let largeBreakpoint: CGFloat = 812
static let extraLargeBreakpoint: CGFloat = 926
enum Sizes {
case small
case regular
case large
case extraLarge
}
static func getDeviceSize(deviceHeight: CGFloat) -> Sizes {
if deviceHeight <= smallBreakpoint {
return .small
} else if deviceHeight <= regularBreakpoint {
return .regular
} else if deviceHeight <= largeBreakpoint {
return .large
} else {
return .extraLarge
}
}
}
|
mit
|
07ad6eb4ea80cd133423281d82e23b40
| 27.793103 | 131 | 0.638323 | 4.82659 | false | false | false | false |
waterskier2007/Toast-Swift
|
Example/ViewController.swift
|
1
|
9634
|
//
// ViewController.swift
// Toast-Swift
//
// Copyright (c) 2017 Charles Scalesse.
//
// 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
class ViewController: UITableViewController {
fileprivate var showingActivity = false
fileprivate struct ReuseIdentifiers {
static let switchCellId = "switchCell"
static let exampleCellId = "exampleCell"
}
// MARK: - Constructors
override init(style: UITableViewStyle) {
super.init(style: style)
self.title = "Toast-Swift"
}
required init?(coder aDecoder: NSCoder) {
fatalError("not used")
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: ReuseIdentifiers.exampleCellId)
}
// MARK: - Events
@objc
private func handleTapToDismissToggled() {
ToastManager.shared.isTapToDismissEnabled = !ToastManager.shared.isTapToDismissEnabled
}
@objc
private func handleQueueToggled() {
ToastManager.shared.isQueueEnabled = !ToastManager.shared.isQueueEnabled
}
}
// MARK: - UITableViewDelegate & DataSource Methods
extension ViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 2
} else {
return 11
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60.0
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40.0
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return "SETTINGS"
} else {
return "EXAMPLES"
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
var cell = tableView.dequeueReusableCell(withIdentifier: ReuseIdentifiers.switchCellId)
if indexPath.row == 0 {
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: ReuseIdentifiers.switchCellId)
let tapToDismissSwitch = UISwitch()
tapToDismissSwitch.onTintColor = .darkBlue
tapToDismissSwitch.isOn = ToastManager.shared.isTapToDismissEnabled
tapToDismissSwitch.addTarget(self, action: #selector(ViewController.handleTapToDismissToggled), for: .valueChanged)
cell?.accessoryView = tapToDismissSwitch
cell?.selectionStyle = .none
cell?.textLabel?.font = UIFont.systemFont(ofSize: 16.0)
}
cell?.textLabel?.text = "Tap to dismiss"
} else {
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: ReuseIdentifiers.switchCellId)
let queueSwitch = UISwitch()
queueSwitch.onTintColor = .darkBlue
queueSwitch.isOn = ToastManager.shared.isQueueEnabled
queueSwitch.addTarget(self, action: #selector(ViewController.handleQueueToggled), for: .valueChanged)
cell?.accessoryView = queueSwitch
cell?.selectionStyle = .none
cell?.textLabel?.font = UIFont.systemFont(ofSize: 16.0)
}
cell?.textLabel?.text = "Queue toast"
}
return cell!
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: ReuseIdentifiers.exampleCellId, for: indexPath)
cell.textLabel?.numberOfLines = 2
cell.textLabel?.font = UIFont.systemFont(ofSize: 16.0)
cell.accessoryType = .disclosureIndicator
switch indexPath.row {
case 0: cell.textLabel?.text = "Make toast"
case 1: cell.textLabel?.text = "Make toast on top for 3 seconds"
case 2: cell.textLabel?.text = "Make toast with a title"
case 3: cell.textLabel?.text = "Make toast with an image"
case 4: cell.textLabel?.text = "Make toast with a title, image, and completion closure"
case 5: cell.textLabel?.text = "Make toast with a custom style"
case 6: cell.textLabel?.text = "Show a custom view as toast"
case 7: cell.textLabel?.text = "Show an image as toast at point\n(110, 110)"
case 8: cell.textLabel?.text = showingActivity ? "Hide toast activity" : "Show toast activity"
case 9: cell.textLabel?.text = "Hide toast"
case 10: cell.textLabel?.text = "Hide all toasts"
default: cell.textLabel?.text = nil
}
return cell
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard indexPath.section > 0 else { return }
tableView.deselectRow(at: indexPath, animated: true)
switch indexPath.row {
case 0:
// Make Toast
self.navigationController?.view.makeToast("This is a piece of toast")
case 1:
// Make toast with a duration and position
self.navigationController?.view.makeToast("This is a piece of toast on top for 3 seconds", duration: 3.0, position: .top)
case 2:
// Make toast with a title
self.navigationController?.view.makeToast("This is a piece of toast with a title", duration: 2.0, position: .top, title: "Toast Title", image: nil)
case 3:
// Make toast with an image
self.navigationController?.view.makeToast("This is a piece of toast with an image", duration: 2.0, position: .center, title: nil, image: UIImage(named: "toast.png"))
case 4:
// Make toast with an image, title, and completion closure
self.navigationController?.view.makeToast("This is a piece of toast with a title, image, and completion closure", duration: 2.0, position: .bottom, title: "Toast Title", image: UIImage(named: "toast.png")) { didTap in
if didTap {
print("completion from tap")
} else {
print("completion without tap")
}
}
case 5:
// Make toast with a custom style
var style = ToastStyle()
style.messageFont = UIFont(name: "Zapfino", size: 14.0)!
style.messageColor = UIColor.red
style.messageAlignment = .center
style.backgroundColor = UIColor.yellow
self.navigationController?.view.makeToast("This is a piece of toast with a custom style", duration: 3.0, position: .bottom, style: style)
case 6:
// Show a custom view as toast
let customView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 80.0, height: 400.0))
customView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin]
customView.backgroundColor = .lightBlue
self.navigationController?.view.showToast(customView, duration: 2.0, position: .center)
case 7:
// Show an image view as toast, on center at point (110,110)
let toastView = UIImageView(image: UIImage(named: "toast.png"))
self.navigationController?.view.showToast(toastView, duration: 2.0, point: CGPoint(x: 110.0, y: 110.0))
case 8:
// Make toast activity
if !showingActivity {
self.navigationController?.view.makeToastActivity(.center)
} else {
self.navigationController?.view.hideToastActivity()
}
showingActivity = !showingActivity
tableView.reloadData()
case 9:
// Hide toast
self.navigationController?.view.hideToast()
case 10:
// Hide all toasts
self.navigationController?.view.hideAllToasts()
default:
break
}
}
}
|
mit
|
c1a2fcb7757e4e7006d8ea1cab8e4d12
| 41.440529 | 229 | 0.609819 | 5.025561 | false | false | false | false |
instilio/INSImageView
|
Example/INSImageViewExample/INSImageViewExample/ViewController.swift
|
1
|
3225
|
//
// ViewController.swift
// INSImageViewExample
//
// Created by Patrick on 9/12/2015.
// Copyright © 2015 instil. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
private let imageView = INSImageView(image: UIImage(named: "pineapple"))
private let contentModeLabel = UILabel()
private var contentModeIndex = 0;
private let contentModes = [
0: "UIViewContentModeScaleToFill",
1: "UIViewContentModeScaleAspectFit",
2: "UIViewContentModeScaleAspectFill",
3: "UIViewContentModeRedraw",
4: "UIViewContentModeCenter",
5: "UIViewContentModeTop",
6: "UIViewContentModeBottom",
7: "UIViewContentModeLeft",
8: "UIViewContentModeRight",
9: "UIViewContentModeTopLeft",
10: "UIViewContentModeTopRight",
11: "UIViewContentModeBottomLeft",
12: "UIViewContentModeBottomRight"]
override func viewDidLoad() {
super.viewDidLoad()
// imageView
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.clipsToBounds = true
view.addSubview(imageView)
// contentModeLabel
contentModeLabel.translatesAutoresizingMaskIntoConstraints = false
contentModeLabel.textAlignment = .Center
contentModeLabel.textColor = UIColor.init(white: 0.2, alpha: 1.0)
contentModeLabel.backgroundColor = UIColor.init(white: 0.9, alpha: 0.4)
view.addSubview(contentModeLabel)
updateContentModeLabel()
NSLayoutConstraint.activateConstraints([
// imageView
imageView.topAnchor .constraintEqualToAnchor(view.topAnchor),
imageView.leadingAnchor .constraintEqualToAnchor(view.leadingAnchor),
imageView.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor),
imageView.bottomAnchor .constraintEqualToAnchor(view.bottomAnchor),
// contentModeLabel
contentModeLabel.heightAnchor .constraintEqualToConstant(60),
contentModeLabel.leadingAnchor .constraintEqualToAnchor(view.leadingAnchor),
contentModeLabel.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor),
contentModeLabel.bottomAnchor .constraintEqualToAnchor(view.bottomAnchor),
])
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: "animate", userInfo: nil, repeats: true)
}
@objc private func animate() {
UIView.animateWithDuration(1,
animations: {
self.imageView.contentMode = self.nextContentMode()
}
)
}
private func nextContentMode() -> UIViewContentMode {
contentModeIndex++;
if contentModeIndex > 12 {
contentModeIndex = 0;
}
updateContentModeLabel()
return UIViewContentMode(rawValue: contentModeIndex)!
}
private func updateContentModeLabel() {
contentModeLabel.text = contentModes[contentModeIndex]
}
}
|
mit
|
d428c474656dc739c8141b73e0fc1e6c
| 34.043478 | 114 | 0.654156 | 5.686067 | false | false | false | false |
chrispix/swift-poloniex-portfolio
|
Sources/poloniex/PoloniexRequest.swift
|
1
|
1112
|
import Foundation
import crypto
struct PoloniexRequest {
let body: String
let hash: String
let keys: APIKeys
var bodyData: Data {
return body.data(using: .utf8)!
}
var urlRequest: URLRequest {
var request = URLRequest(url: tradingURL)
request.setValue(keys.key, forHTTPHeaderField: "Key")
request.setValue(hash, forHTTPHeaderField: "Sign")
request.httpBody = bodyData
request.httpMethod = "POST"
return request
}
let tradingURL = URL(string: "https://poloniex.com/tradingApi")!
init(params: [String: String], keys: APIKeys) {
self.keys = keys
let nonce = Int64(Date().timeIntervalSince1970 * 1000)
var queryItems = [URLQueryItem]()
for (key, value) in params {
queryItems.append(URLQueryItem(name: key, value: value))
}
queryItems.append(URLQueryItem(name: "nonce", value: "\(nonce)"))
var components = URLComponents()
components.queryItems = queryItems
let body = components.query!
let hash = body.hmac(algorithm: HMACAlgorithm.SHA512, key: keys.secret)
self.body = body
self.hash = hash
}
}
|
mit
|
30b0bc5816cfbfd0acc35ee9e3f51fa6
| 27.512821 | 75 | 0.677158 | 4.028986 | false | false | false | false |
rodrigoff/hackingwithswift
|
project3/Project3/ViewController.swift
|
1
|
1536
|
//
// ViewController.swift
// Project3
//
// Created by Rodrigo F. Fernandes on 7/20/17.
// Copyright © 2017 Rodrigo F. Fernandes. All rights reserved.
//
import UIKit
class ViewController: UITableViewController {
var pictures = [String]()
override func viewDidLoad() {
super.viewDidLoad()
title = "Storm Viewer"
let fm = FileManager.default
let path = Bundle.main.resourcePath!
let items = try! fm.contentsOfDirectory(atPath: path)
for item in items {
if item.hasPrefix("nssl") {
pictures.append(item)
}
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return pictures.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Picture", for: indexPath)
cell.textLabel?.text = pictures[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let vc = storyboard?.instantiateViewController(withIdentifier: "Detail") as? DetailViewController {
vc.selectedImage = pictures[indexPath.row]
navigationController?.pushViewController(vc, animated: true)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
mit
|
a560d7b64e1a9764495500c95f5fbeb6
| 27.425926 | 110 | 0.636482 | 5.185811 | false | false | false | false |
teacurran/alwaysawake-ios
|
Pods/p2.OAuth2/Sources/Base/OAuth2ClientCredentialsReddit.swift
|
3
|
2342
|
//
// OAuth2ClientCredentialsReddit.swift
// OAuth2
//
// Created by Pascal Pfiffner on 3/20/16.
// Copyright © 2016 Pascal Pfiffner. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/**
Enables Reddit's special client credentials flow for installed apps.
This flow will specify `https://oauth.reddit.com/grants/installed_client` as grant type and also supply a `device_id`, which you must set
during configuration or by setting the `deviceId` property.
https://github.com/reddit/reddit/wiki/OAuth2#application-only-oauth
*/
public class OAuth2ClientCredentialsReddit: OAuth2ClientCredentials {
public override class var grantType: String {
return "https://oauth.reddit.com/grants/installed_client"
}
/// An identifier of the device requesting the token. You should generate and save a unique ID on your client. DO NOT use any personally
/// identifiable information (including non-user-resettable information, such as Android's TelephonyManager.getDeviceId() or iOS's IDFA).
public var deviceId: String?
/**
The special Reddit client credentials flow for installed apps adds the `device_id` key to the settings dictionary.
- parameter settings: The authorization settings
*/
public override init(settings: OAuth2JSON) {
deviceId = settings["device_id"] as? String
super.init(settings: settings)
clientConfig.clientSecret = ""
}
/** Add `device_id` parameter to the request created by the superclass. */
override func tokenRequest(params: OAuth2StringDict? = nil) throws -> OAuth2AuthRequest {
guard let device = deviceId else {
throw OAuth2Error.Generic("You must configure this flow with a `device_id` (via settings) or manually assign `deviceId`")
}
let req = try super.tokenRequest(params)
req.params["device_id"] = device
return req
}
}
|
apache-2.0
|
0e72cf9a1ad67b90575951026726c05e
| 36.15873 | 138 | 0.747544 | 3.954392 | false | false | false | false |
rnystrom/GitHawk
|
Classes/PullRequestReviews/PullRequestReviewReplyModel.swift
|
1
|
720
|
//
// PullRequestReviewReplyModel.swift
// Freetime
//
// Created by Ryan Nystrom on 1/29/18.
// Copyright © 2018 Ryan Nystrom. All rights reserved.
//
import Foundation
import IGListKit
final class PullRequestReviewReplyModel: ListDiffable {
let replyID: Int
init(replyID: Int) {
self.replyID = replyID
}
// MARK: ListDiffable
func diffIdentifier() -> NSObjectProtocol {
return "reply-\(replyID)" as NSObjectProtocol
}
func isEqual(toDiffableObject object: ListDiffable?) -> Bool {
if self === object { return true }
guard let object = object as? PullRequestReviewReplyModel else { return false }
return replyID == object.replyID
}
}
|
mit
|
cf9c0e0f28a9b57d8f0c3bfa9eef3ce3
| 21.46875 | 87 | 0.667594 | 4.438272 | false | false | false | false |
webim/webim-client-sdk-ios
|
Example/WebimClientLibrary/Models/FilePicker.swift
|
1
|
13248
|
//
// FilePicker.swift
// WebimClientLibrary_Example
//
// Created by Eugene Ilyin on 21.10.2019.
// Copyright © 2019 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 UIKit
import MobileCoreServices
import AVFoundation
import CloudKit
import AVKit
import Photos
import PhotosUI
public protocol FilePickerDelegate: AnyObject {
func didSelect(image: UIImage?, imageURL: URL?)
func didSelect(file: Data?, fileURL: URL?)
}
open class FilePicker: NSObject {
// MARK: - Private properties
private let imagePickerController: UIImagePickerController
private let documentPickerController: UIDocumentPickerViewController
private let alertDialogHandler: UIAlertHandler
private weak var presentationController: UIViewController?
private weak var delegate: FilePickerDelegate?
// MARK: - Methods
public init(presentationController: UIViewController,
delegate: FilePickerDelegate) {
self.imagePickerController = UIImagePickerController()
self.documentPickerController = UIDocumentPickerViewController(
documentTypes: [
String(kUTTypeJPEG),
String(kUTTypeRTF),
String(kUTTypeGIF),
String(kUTTypePlainText),
String(kUTTypePDF),
String(kUTTypeMP3),
String(kUTTypeMPEG4),
String(kUTTypeData),
String(kUTTypeArchive)
],
in: .import
)
self.alertDialogHandler = UIAlertHandler(delegate: presentationController)
super.init()
self.presentationController = presentationController
self.delegate = delegate
self.imagePickerController.delegate = self
self.imagePickerController.allowsEditing = false
self.imagePickerController.mediaTypes = ["public.image"]
if #available(iOS 11.0, *) {
self.documentPickerController.delegate = self
self.documentPickerController.allowsMultipleSelection = false
}
}
public func showSendFileMenu(from sourceView: UIView) {
let fileMenuSheet = UIAlertController(
title: nil,
message: nil,
preferredStyle: .actionSheet
)
let cameraAction = UIAlertAction(
title: "Camera".localized,
style: .default,
handler: { _ in
let cameraAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: .video)
switch cameraAuthorizationStatus {
case .notDetermined:
self.requesetCameraPermission()
case .authorized:
self.presentCamera()
case .restricted, .denied:
self.showAlertForCameraAccess()
@unknown default:
// Handle possibly added (in future) values
break
}
}
)
let photoLibraryAction = UIAlertAction(
title: "Photo Library".localized,
style: .default,
handler: { _ in
self.showPhotoLibrary()
}
)
let fileAction = UIAlertAction(
title: "File".localized,
style: .default,
handler: { _ in
self.presentationController?.present(
self.documentPickerController,
animated: true)
}
)
let cancelAction = UIAlertAction(
title: "Cancel".localized,
style: .cancel
)
fileMenuSheet.addAction(cameraAction)
fileMenuSheet.addAction(photoLibraryAction)
fileMenuSheet.addAction(cancelAction)
/// Files App was presented in iOS 11.0
if #available(iOS 11.0, *) {
fileMenuSheet.addAction(fileAction)
}
// Workaround for iPads
if UIDevice.current.userInterfaceIdiom == .pad {
fileMenuSheet.popoverPresentationController?.sourceView = sourceView
fileMenuSheet.popoverPresentationController?.sourceRect = sourceView.bounds
fileMenuSheet.popoverPresentationController?.permittedArrowDirections = [.down, .up]
}
self.presentationController?.present(fileMenuSheet, animated: true)
}
private func showPhotoLibrary() {
var status: PHAuthorizationStatus
if #available(iOS 14, *) {
status = PHPhotoLibrary.authorizationStatus(for: .readWrite)
} else {
status = PHPhotoLibrary.authorizationStatus()
}
switch status {
case .notDetermined:
self.requesetPhotoPermission()
case .authorized, .limited:
self.presentPhoto()
case .restricted, .denied:
self.showAlertForPhotoAccess()
@unknown default:
// Handle possibly added (in future) values
break
}
}
private func requesetPhotoPermission() {
PHPhotoLibrary.requestAuthorization { status in
if #available(iOS 14, *) {
if status == .limited {
self.presentPhoto()
}
}
if status == .authorized {
self.presentPhoto()
}
}
}
private func presentPhoto() {
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
DispatchQueue.main.async {
self.showImagePicker()
}
} else {
let ac = UIAlertController(
title: "Please Allow Access".localized,
message: "Need photo access".localized,
preferredStyle: .alert
)
let okAction = UIAlertAction(
title: "OK".localized,
style: .cancel
)
ac.addAction(okAction)
self.presentationController?.present(ac, animated: true)
}
}
private func showAlertForPhotoAccess() {
let ac = UIAlertController(
title: "Please Allow Access".localized,
message: "Need photo access".localized,
preferredStyle: .alert
)
guard let settingsAppURL = URL(string: UIApplication.openSettingsURLString) else { return }
let showAppSettingsAction = UIAlertAction(
title: "Settings".localized,
style: .default,
handler: { _ in
UIApplication.shared.open(
settingsAppURL,
options: [:])
}
)
let cancelAction = UIAlertAction(
title: "Cancel".localized,
style: .cancel
)
ac.addAction(showAppSettingsAction)
ac.addAction(cancelAction)
self.presentationController?.present(ac, animated: true)
}
private func showImagePicker() {
self.imagePickerController.sourceType = .photoLibrary
self.presentationController?.present(
self.imagePickerController,
animated: true
)
}
// MARK: - Private methods
private func pickerControllerImage(
_ controller: UIImagePickerController,
didSelect image: UIImage? = nil,
withURL imageURL: URL? = nil
) {
controller.dismiss(animated: true, completion: nil)
self.delegate?.didSelect(image: image, imageURL: imageURL)
}
private func pickerControllerDocument(
_ controller: UIDocumentPickerViewController,
didSelect file: Data? = nil,
withURL documentURL: URL? = nil
) {
controller.dismiss(animated: true, completion: nil)
self.delegate?.didSelect(file: file, fileURL: documentURL)
}
private func requesetCameraPermission() {
AVCaptureDevice.requestAccess(for: .video) { (access) in
guard access == true else { return }
self.presentCamera()
}
}
private func presentCamera() {
DispatchQueue.main.async {
if UIImagePickerController.isSourceTypeAvailable(.camera) {
self.imagePickerController.sourceType = .camera
self.presentationController?.present(self.imagePickerController, animated: true)
} else {
let ac = UIAlertController(
title: "Camera is not available".localized,
message: nil,
preferredStyle: .alert
)
let okAction = UIAlertAction(
title: "OK".localized,
style: .cancel
)
ac.addAction(okAction)
self.presentationController?.present(ac, animated: true)
}
}
}
private func showAlertForCameraAccess() {
guard let settingsAppURL = URL(string: UIApplication.openSettingsURLString) else { return }
let ac = UIAlertController(
title: "Need camera access".localized,
message: "Webim Demo needs permission to access your camera so you can send photos to chat.".localized,
preferredStyle: .alert
)
let showAppSettingsAction = UIAlertAction(
title: "Open app settings".localized,
style: .default,
handler: { _ in
UIApplication.shared.open(
settingsAppURL,
options: [:])
}
)
let cancelAction = UIAlertAction(
title: "Cancel".localized,
style: .cancel
)
ac.addAction(showAppSettingsAction)
ac.addAction(cancelAction)
self.presentationController?.present(ac, animated: true)
}
}
// MARK: - UIImagePickerController extensions
extension FilePicker: UIImagePickerControllerDelegate {
public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
self.pickerControllerImage(picker)
}
public func imagePickerController(
_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]
) {
guard let image = info[.originalImage] as? UIImage else {
return self.pickerControllerImage(picker)
}
guard let imageURL = info[.referenceURL] as? URL else {
return self.pickerControllerImage(picker, didSelect: image)
}
self.pickerControllerImage(
picker,
didSelect: image,
withURL: imageURL
)
}
}
extension FilePicker: UIDocumentMenuDelegate, UIDocumentPickerDelegate {
public func documentPicker(
_ picker: UIDocumentPickerViewController,
didPickDocumentsAt urls: [URL]
) {
guard let fileURL = urls.first else {
return self.pickerControllerDocument(picker)
}
do {
let data = try Data(contentsOf: fileURL)
self.pickerControllerDocument(
picker,
didSelect: data,
withURL: fileURL
)
} catch {
alertDialogHandler.showFileLoadingFailureDialog(withError: error)
}
}
public func documentMenu(
_ documentMenu: UIDocumentMenuViewController,
didPickDocumentPicker documentPicker: UIDocumentPickerViewController
) {
// TODO: Check what for this method is responsible
documentPicker.delegate = self
self.presentationController?.present(documentPicker, animated: true)
}
public func documentPickerWasCancelled(_ picker: UIDocumentPickerViewController) {
print("view was cancelled")
self.pickerControllerDocument(picker)
}
}
extension FilePicker: UINavigationControllerDelegate { }
|
mit
|
e7209fc87aaee925fa223efdb61c1e55
| 32.879795 | 115 | 0.591002 | 5.810088 | false | false | false | false |
stevehe-campray/BSBDJ
|
BSBDJ/BSBDJ/AppDelegate.swift
|
1
|
3711
|
//
// AppDelegate.swift
// BSBDJ
//
// Created by hejingjin on 16/3/14.
// Copyright © 2016年 baisibudejie. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate ,UITabBarControllerDelegate{
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
window = UIWindow(frame:UIScreen.mainScreen().bounds)
window?.backgroundColor = UIColor.whiteColor()
let rootvc = BSBRootViewController()
rootvc.delegate = self
window?.rootViewController = rootvc
window?.makeKeyAndVisible()
let key = "CFBundleShortVersionString"
let currentversion = NSBundle.mainBundle().infoDictionary?[key] as!NSString
var sandboxversion = NSUserDefaults.standardUserDefaults().stringForKey(key)
if sandboxversion == nil {
NSUserDefaults.standardUserDefaults().setObject("", forKey: key)
NSUserDefaults.standardUserDefaults().synchronize()
}
sandboxversion = NSUserDefaults.standardUserDefaults().stringForKey(key);
print(!currentversion .isEqualToString(sandboxversion!))
if (!currentversion .isEqualToString(sandboxversion!)) {
let gudieview = BSBGudieView.gudieview()
gudieview.frame = (window?.bounds)!
self.window?.addSubview(gudieview);
NSUserDefaults.standardUserDefaults().setObject(currentversion, forKey: key)
NSUserDefaults.standardUserDefaults().synchronize()
}
// Override point for customization after application launch.
return true
}
//点击2次
func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
NSNotificationCenter.defaultCenter().postNotificationName("tabarselect", object: nil, userInfo: nil)
}
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:.
}
}
|
mit
|
f63006a8ec572b574d8a5a2632d02281
| 43.60241 | 285 | 0.715019 | 5.70416 | false | false | false | false |
akoi/healthkit-poc
|
healthkit-poc/Services/HealthItemProvider.swift
|
1
|
1309
|
//
// HealthItemService.swift
// healthkit-poc
//
import HealthKit
class HealthItemProvider {
class var sharedInstance : HealthItemProvider {
struct Static {
static let instance : HealthItemProvider = HealthItemProvider()
}
return Static.instance
}
func findByIdentifier(identifier: String)-> HealthItem? {
return healthItems.filter { $0.hkIdentifier == identifier }.first
}
func findByName(name: String)-> HealthItem? {
// assumes unique name
return healthItems.filter { $0.name == name }.first
}
let healthItems: Array<HealthItem> = [
// Nutrition TODO
HealthItem { item in
item.name = "Caffeine"
item.hkIdentifier = HKQuantityTypeIdentifierDietaryCaffeine
},
// Vitals
HealthItem { item in
item.name = "Heart Rate"
item.hkIdentifier = HKQuantityTypeIdentifierHeartRate
},
// Fitness
HealthItem { item in
item.name = "Steps"
item.hkIdentifier = HKQuantityTypeIdentifierStepCount
},
// Body Measurements
HealthItem { item in
item.name = "Weight"
item.hkIdentifier = HKQuantityTypeIdentifierBodyMass
}
]
}
|
unlicense
|
0397c21f4bf6db992bda4b3ea05adf4a
| 26.291667 | 75 | 0.594347 | 4.996183 | false | false | false | false |
ntnmrndn/R.swift
|
Sources/RswiftCore/Util/Glob.swift
|
2
|
6216
|
//
// Created by Eric Firestone on 3/22/16.
// Copyright © 2016 Square, Inc. All rights reserved.
// Released under the Apache v2 License.
//
// Adapted from https://gist.github.com/blakemerryman/76312e1cbf8aec248167
// Adapted from https://gist.github.com/efirestone/ce01ae109e08772647eb061b3bb387c3
import Foundation
public let GlobBehaviorBashV3 = Glob.Behavior(
supportsGlobstar: false,
includesFilesFromRootOfGlobstar: false,
includesDirectoriesInResults: true,
includesFilesInResultsIfTrailingSlash: false
)
public let GlobBehaviorBashV4 = Glob.Behavior(
supportsGlobstar: true, // Matches Bash v4 with "shopt -s globstar" option
includesFilesFromRootOfGlobstar: true,
includesDirectoriesInResults: true,
includesFilesInResultsIfTrailingSlash: false
)
public let GlobBehaviorGradle = Glob.Behavior(
supportsGlobstar: true,
includesFilesFromRootOfGlobstar: true,
includesDirectoriesInResults: false,
includesFilesInResultsIfTrailingSlash: true
)
/**
Finds files on the file system using pattern matching.
*/
public class Glob: Collection {
/**
* Different glob implementations have different behaviors, so the behavior of this
* implementation is customizable.
*/
public struct Behavior {
// If true then a globstar ("**") causes matching to be done recursively in subdirectories.
// If false then "**" is treated the same as "*"
let supportsGlobstar: Bool
// If true the results from the directory where the globstar is declared will be included as well.
// For example, with the pattern "dir/**/*.ext" the fie "dir/file.ext" would be included if this
// property is true, and would be omitted if it's false.
let includesFilesFromRootOfGlobstar: Bool
// If false then the results will not include directory entries. This does not affect recursion depth.
let includesDirectoriesInResults: Bool
// If false and the last characters of the pattern are "**/" then only directories are returned in the results.
let includesFilesInResultsIfTrailingSlash: Bool
}
public static var defaultBehavior = GlobBehaviorBashV4
private var isDirectoryCache = [String: Bool]()
public let behavior: Behavior
var paths = [String]()
public var startIndex: Int { return paths.startIndex }
public var endIndex: Int { return paths.endIndex }
public init(pattern: String, behavior: Behavior = Glob.defaultBehavior) {
self.behavior = behavior
var adjustedPattern = pattern
let hasTrailingGlobstarSlash = pattern.hasSuffix("**/")
var includeFiles = !hasTrailingGlobstarSlash
if behavior.includesFilesInResultsIfTrailingSlash {
includeFiles = true
if hasTrailingGlobstarSlash {
// Grab the files too.
adjustedPattern += "*"
}
}
let patterns = behavior.supportsGlobstar ? expandGlobstar(pattern: adjustedPattern) : [adjustedPattern]
for pattern in patterns {
var gt = glob_t()
if executeGlob(pattern: pattern, gt: >) {
populateFiles(gt: gt, includeFiles: includeFiles)
}
globfree(>)
}
paths = Array(Set(paths)).sorted { lhs, rhs in
lhs.compare(rhs) != ComparisonResult.orderedDescending
}
clearCaches()
}
// MARK: Subscript Support
public subscript(i: Int) -> String {
return paths[i]
}
// MARK: Protocol of IndexableBase
public func index(after i: Glob.Index) -> Glob.Index {
return i + 1
}
// MARK: Private
private var globalFlags = GLOB_TILDE | GLOB_BRACE | GLOB_MARK
private func executeGlob(pattern: UnsafePointer<CChar>, gt: UnsafeMutablePointer<glob_t>) -> Bool {
return 0 == glob(pattern, globalFlags, nil, gt)
}
private func expandGlobstar(pattern: String) -> [String] {
guard pattern.contains("**") else {
return [pattern]
}
var results = [String]()
var parts = pattern.components(separatedBy: "**")
let firstPart = parts.removeFirst()
var lastPart = parts.joined(separator: "**")
let fileManager = FileManager.default
var directories: [String]
do {
directories = try fileManager.subpathsOfDirectory(atPath: firstPart).compactMap { subpath in
let fullPath = NSString(string: firstPart).appendingPathComponent(subpath)
var isDirectory = ObjCBool(false)
if fileManager.fileExists(atPath: fullPath, isDirectory: &isDirectory) && isDirectory.boolValue {
return fullPath
} else {
return nil
}
}
} catch {
directories = []
print("Error parsing file system item: \(error)")
}
if behavior.includesFilesFromRootOfGlobstar {
// Check the base directory for the glob star as well.
directories.insert(firstPart, at: 0)
// Include the globstar root directory ("dir/") in a pattern like "dir/**" or "dir/**/"
if lastPart.isEmpty {
results.append(firstPart)
}
}
if lastPart.isEmpty {
lastPart = "*"
}
for directory in directories {
let partiallyResolvedPattern = NSString(string: directory).appendingPathComponent(lastPart)
results.append(contentsOf: expandGlobstar(pattern: partiallyResolvedPattern))
}
return results
}
private func isDirectory(path: String) -> Bool {
var isDirectory = isDirectoryCache[path]
if let isDirectory = isDirectory {
return isDirectory
}
var isDirectoryBool = ObjCBool(false)
isDirectory = FileManager.default.fileExists(atPath: path, isDirectory: &isDirectoryBool) && isDirectoryBool.boolValue
isDirectoryCache[path] = isDirectory!
return isDirectory!
}
private func clearCaches() {
isDirectoryCache.removeAll()
}
private func populateFiles(gt: glob_t, includeFiles: Bool) {
let includeDirectories = behavior.includesDirectoriesInResults
for i in 0..<Int(gt.gl_matchc) {
if let path = String(validatingUTF8: gt.gl_pathv[i]!) {
if !includeFiles || !includeDirectories {
let isDirectory = self.isDirectory(path: path)
if (!includeFiles && !isDirectory) || (!includeDirectories && isDirectory) {
continue
}
}
paths.append(path)
}
}
}
}
|
mit
|
7ec98929893ed1171aeeca51a8268265
| 29.317073 | 122 | 0.692035 | 4.355291 | false | false | false | false |
khizkhiz/swift
|
test/SILGen/availability_query.swift
|
9
|
3227
|
// RUN: %target-swift-frontend -emit-sil %s -target x86_64-apple-macosx10.50 -verify
// RUN: %target-swift-frontend -emit-silgen %s -target x86_64-apple-macosx10.50 | FileCheck %s
// REQUIRES: OS=macosx
// CHECK-LABEL: sil{{.+}}@main{{.*}} {
// CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
// CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 53
// CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 8
// CHECK: [[FUNC:%.*]] = function_ref @_TFs26_stdlib_isOSVersionAtLeastFTBwBwBw_Bi1_ : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[QUERY_RESULT:%.*]] = apply [[FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
if #available(OSX 10.53.8, iOS 7.1, *) {
}
// CHECK: [[TRUE:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK: cond_br [[TRUE]]
// Since we are compiling for an unmentioned platform (OS X), we check against the minimum
// deployment target, which is 10.50
if #available(iOS 7.1, *) {
}
// CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
// CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 52
// CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0
// CHECK: [[QUERY_FUNC:%.*]] = function_ref @_TFs26_stdlib_isOSVersionAtLeastFTBwBwBw_Bi1_ : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[QUERY_RESULT:%.*]] = apply [[QUERY_FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
if #available(OSX 10.52, *) {
}
// CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
// CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 0
// CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0
// CHECK: [[QUERY_FUNC:%.*]] = function_ref @_TFs26_stdlib_isOSVersionAtLeastFTBwBwBw_Bi1_ : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[QUERY_RESULT:%.*]] = apply [[QUERY_FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
if #available(OSX 10, *) { // expected-warning {{minimum deployment target ensures guard will always be true}}
}
// CHECK: }
func doThing() {}
func testUnreachableVersionAvailable(condition: Bool) {
if #available(OSX 10.0, *) { // expected-warning {{minimum deployment target ensures guard will always be true}}
doThing() // no-warning
return
} else {
doThing() // FIXME-warning {{will never be executed}}
}
if true {
doThing() // no-warning
}
if false { // expected-note {{condition always evaluates to false}}
doThing() // expected-warning {{will never be executed}}
}
}
func testUnreachablePlatformAvailable(condition: Bool) {
if #available(iOS 7.1, *) {
doThing() // no-warning
return
} else {
doThing() // no-warning
}
if true {
doThing() // no-warning
}
if false { // expected-note {{condition always evaluates to false}}
doThing() // expected-warning {{will never be executed}}
}
}
func testUnreachablePlatformAvailableGuard() {
guard #available(iOS 7.1, *) else {
doThing() // no-warning
return
}
doThing() // no-warning
}
|
apache-2.0
|
88533cc80fceec7b8ddca0fcdb323354
| 37.879518 | 170 | 0.6489 | 3.481122 | false | false | false | false |
khizkhiz/swift
|
test/IDE/complete_pound_selector.swift
|
5
|
3151
|
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=AFTER_POUND | FileCheck -check-prefix=CHECK-AFTER_POUND %s
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=SELECTOR_ARG1 | FileCheck -check-prefix=CHECK-SELECTOR_ARG %s
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=SELECTOR_ARG2 | FileCheck -check-prefix=CHECK-SELECTOR_ARG %s
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=IN_SELECTOR1 | FileCheck -check-prefix=CHECK-IN_SELECTOR %s
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=IN_SELECTOR2 | FileCheck -check-prefix=CHECK-IN_SELECTOR %s
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=IN_SELECTOR3 | FileCheck -check-prefix=CHECK-IN_SUPER_SELECTOR %s
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=IN_SELECTOR4 | FileCheck -check-prefix=CHECK-IN_SUPER_SELECTOR %s
// REQUIRES: objc_interop
import Foundation
{
if ##^AFTER_POUND^#
}
func selectorArg1(obj: NSObject) {
obj.doSelector(#^SELECTOR_ARG1^#
}
func selectorArg2(obj: NSObject) {
obj.messageSomeObject(obj, selector:#^SELECTOR_ARG2^#
}
func inSelector1() {
_ = #selector(NSObject.#^IN_SELECTOR1^#)
}
func inSelector2() {
_ = #selector(NSObject#^IN_SELECTOR2^#)
}
class Subclass : NSObject {
func inSelector3() {
_ = #selector(super.#^IN_SELECTOR3^#)
}
func inSelector4() {
_ = #selector(super#^IN_SELECTOR4^#)
}
}
// CHECK-AFTER_POUND: Keyword/ExprSpecific: available({#Platform...#}, *); name=available(Platform..., *)
// CHECK-AFTER_POUND: Keyword/ExprSpecific: selector({#@objc method#}); name=selector(@objc method)
// CHECK-SELECTOR_ARG: Keyword/ExprSpecific: #selector({#@objc method#}); name=#selector(@objc method)
// CHECK-IN_SELECTOR: Decl[Constructor]/CurrNominal: {{.?}}init; name=init
// CHECK-IN_SELECTOR: Decl[StaticMethod]/CurrNominal: {{.?}}perform(_:with:); name=perform(_:with:)
// CHECK-IN_SELECTOR: Decl[InstanceMethod]/CurrNominal: {{.?}}perform(_:with:); name=perform(_:with:)
// CHECK-IN_SELECTOR: Decl[InstanceMethod]/CurrNominal: {{.?}}myClass; name=myClass
// CHECK-IN_SELECTOR: Decl[StaticMethod]/CurrNominal: {{.?}}description; name=description
// CHECK-IN_SELECTOR: Decl[StaticMethod]/CurrNominal: {{.?}}isEqual(_:); name=isEqual(_:)
// CHECK-IN_SELECTOR: Decl[InstanceMethod]/CurrNominal: {{.?}}isEqual(_:); name=isEqual(_:)
// CHECK-IN_SUPER_SELECTOR: Decl[InstanceMethod]/CurrNominal: {{.?}}perform(_:with:); name=perform(_:with:)
// CHECK-IN_SUPER_SELECTOR: Decl[InstanceMethod]/CurrNominal: {{.?}}myClass; name=myClass
// CHECK-IN_SUPER_SELECTOR: Decl[InstanceMethod]/CurrNominal: {{.?}}isEqual(_:); name=isEqual(_:)
|
apache-2.0
|
00c5985973bb9aacaa9de85baf8a0181
| 47.476923 | 187 | 0.701682 | 3.32735 | false | true | false | false |
carabina/GRDB.swift
|
GRDB Tests/Public/Core/SQLiteStatementConvertible/SQLiteStatementConversionTests.swift
|
1
|
48262
|
import XCTest
import GRDB
class SQLiteStatementConversionTests : GRDBTestCase {
// Datatypes In SQLite Version 3: https://www.sqlite.org/datatype3.html
override func setUp() {
super.setUp()
var migrator = DatabaseMigrator()
migrator.registerMigration("createPersons") { db in
try db.execute(
"CREATE TABLE `values` (" +
"integerAffinity INTEGER, " +
"textAffinity TEXT, " +
"noneAffinity BLOB, " +
"realAffinity DOUBLE, " +
"numericAffinity NUMERIC" +
")")
}
assertNoError {
try migrator.migrate(dbQueue)
}
}
func testTextAffinity() {
// https://www.sqlite.org/datatype3.html
//
// > A column with TEXT affinity stores all data using storage classes
// > NULL, TEXT or BLOB. If numerical data is inserted into a column
// > with TEXT affinity it is converted into text form before being
// > stored.
assertNoError {
// Int is turned to Text
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO `values` (textAffinity) VALUES (?)", arguments: [0 as Int])
for row in Row.fetch(db, "SELECT textAffinity FROM `values`") {
// Check SQLite conversions from Text storage:
XCTAssertFalse((row.value(atIndex: 0) as Bool?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int32?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int64?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Double?) == nil) // incompatible with DatabaseValue conversion
XCTAssertEqual((row.value(atIndex: 0) as String?)!, "0")
XCTAssertEqual((row.value(atIndex: 0) as String), "0")
XCTAssertFalse((row.value(atIndex: 0) as Blob?) == nil) // incompatible with DatabaseValue conversion
}
return .Rollback
}
// Int64 is turned to Text
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO `values` (textAffinity) VALUES (?)", arguments: [0 as Int64])
for row in Row.fetch(db, "SELECT textAffinity FROM `values`") {
// Check SQLite conversions from Text storage:
XCTAssertFalse((row.value(atIndex: 0) as Bool?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int32?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int64?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Double?) == nil) // incompatible with DatabaseValue conversion
XCTAssertEqual((row.value(atIndex: 0) as String?)!, "0")
XCTAssertEqual((row.value(atIndex: 0) as String), "0")
XCTAssertFalse((row.value(atIndex: 0) as Blob?) == nil) // incompatible with DatabaseValue conversion
}
return .Rollback
}
// Int32 is turned to Text
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO `values` (textAffinity) VALUES (?)", arguments: [0 as Int32])
for row in Row.fetch(db, "SELECT textAffinity FROM `values`") {
// Check SQLite conversions from Text storage:
XCTAssertFalse((row.value(atIndex: 0) as Bool?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int32?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int64?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Double?) == nil) // incompatible with DatabaseValue conversion
XCTAssertEqual((row.value(atIndex: 0) as String?)!, "0")
XCTAssertEqual((row.value(atIndex: 0) as String), "0")
XCTAssertFalse((row.value(atIndex: 0) as Blob?) == nil) // incompatible with DatabaseValue conversion
}
return .Rollback
}
// Double is turned to Real
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO `values` (textAffinity) VALUES (?)", arguments: [0.0])
for row in Row.fetch(db, "SELECT textAffinity FROM `values`") {
// Check SQLite conversions from Text storage:
XCTAssertFalse((row.value(atIndex: 0) as Bool?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int32?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int64?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Double?) == nil) // incompatible with DatabaseValue conversion
XCTAssertEqual((row.value(atIndex: 0) as String?)!, "0.0")
XCTAssertEqual((row.value(atIndex: 0) as String), "0.0")
XCTAssertFalse((row.value(atIndex: 0) as Blob?) == nil) // incompatible with DatabaseValue conversion
}
return .Rollback
}
// "3.0e+5" is turned to Text
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO `values` (textAffinity) VALUES (?)", arguments: ["3.0e+5"])
for row in Row.fetch(db, "SELECT textAffinity FROM `values`") {
// Check SQLite conversions from Text storage:
XCTAssertFalse((row.value(atIndex: 0) as Bool?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int32?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int64?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Double?) == nil) // incompatible with DatabaseValue conversion
XCTAssertEqual((row.value(atIndex: 0) as String?)!, "3.0e+5")
XCTAssertEqual((row.value(atIndex: 0) as String), "3.0e+5")
XCTAssertFalse((row.value(atIndex: 0) as Blob?) == nil) // incompatible with DatabaseValue conversion
}
return .Rollback
}
// "foo" is turned to Text
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO `values` (textAffinity) VALUES (?)", arguments: ["foo"])
for row in Row.fetch(db, "SELECT textAffinity FROM `values`") {
// Check SQLite conversions from Text storage:
XCTAssertFalse((row.value(atIndex: 0) as Bool?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int32?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int64?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Double?) == nil) // incompatible with DatabaseValue conversion
XCTAssertEqual((row.value(atIndex: 0) as String?)!, "foo")
XCTAssertEqual((row.value(atIndex: 0) as String), "foo")
XCTAssertFalse((row.value(atIndex: 0) as Blob?) == nil) // incompatible with DatabaseValue conversion
}
return .Rollback
}
// Blob is turned to Blob
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO `values` (textAffinity) VALUES (?)", arguments: ["foo".dataUsingEncoding(NSUTF8StringEncoding)])
for row in Row.fetch(db, "SELECT textAffinity FROM `values`") {
// Check SQLite conversions from Blob storage:
XCTAssertFalse((row.value(atIndex: 0) as Bool?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int32?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int64?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Double?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as String?) == nil) // incompatible with DatabaseValue conversion
XCTAssertEqual((row.value(atIndex: 0) as Blob?), Blob(data: "foo".dataUsingEncoding(NSUTF8StringEncoding))!)
}
return .Rollback
}
}
}
func testNumericAffinity() {
// https://www.sqlite.org/datatype3.html
//
// > A column with NUMERIC affinity may contain values using all five
// > storage classes. When text data is inserted into a NUMERIC column,
// > the storage class of the text is converted to INTEGER or REAL (in
// > order of preference) if such conversion is lossless and reversible.
// > For conversions between TEXT and REAL storage classes, SQLite
// > considers the conversion to be lossless and reversible if the first
// > 15 significant decimal digits of the number are preserved. If the
// > lossless conversion of TEXT to INTEGER or REAL is not possible then
// > the value is stored using the TEXT storage class. No attempt is
// > made to convert NULL or BLOB values.
// >
// > A string might look like a floating-point literal with a decimal
// > point and/or exponent notation but as long as the value can be
// > expressed as an integer, the NUMERIC affinity will convert it into
// > an integer. Hence, the string '3.0e+5' is stored in a column with
// > NUMERIC affinity as the integer 300000, not as the floating point
// > value 300000.0.
testNumericAffinity("numericAffinity")
}
func testIntegerAffinity() {
// https://www.sqlite.org/datatype3.html
//
// > A column that uses INTEGER affinity behaves the same as a column
// > with NUMERIC affinity. The difference between INTEGER and NUMERIC
// > affinity is only evident in a CAST expression.
testNumericAffinity("integerAffinity")
}
func testRealAffinity() {
// https://www.sqlite.org/datatype3.html
//
// > A column with REAL affinity behaves like a column with NUMERIC
// > affinity except that it forces integer values into floating point
// > representation. (As an internal optimization, small floating point
// > values with no fractional component and stored in columns with REAL
// > affinity are written to disk as integers in order to take up less
// > space and are automatically converted back into floating point as
// > the value is read out. This optimization is completely invisible at
// > the SQL level and can only be detected by examining the raw bits of
// > the database file.)
assertNoError {
// Int is turned to Real
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO `values` (realAffinity) VALUES (?)", arguments: [0 as Int])
for row in Row.fetch(db, "SELECT realAffinity FROM `values`") {
// Check SQLite conversions from Real storage
XCTAssertEqual((row.value(atIndex: 0) as Bool?)!, false)
XCTAssertEqual((row.value(atIndex: 0) as Bool), false)
XCTAssertEqual((row.value(atIndex: 0) as Int?)!, 0)
XCTAssertEqual((row.value(atIndex: 0) as Int), 0)
XCTAssertEqual((row.value(atIndex: 0) as Int32?)!, Int32(0))
XCTAssertEqual((row.value(atIndex: 0) as Int32), Int32(0))
XCTAssertEqual((row.value(atIndex: 0) as Int64?)!, Int64(0))
XCTAssertEqual((row.value(atIndex: 0) as Int64), Int64(0))
XCTAssertEqual((row.value(atIndex: 0) as Double?)!, 0.0)
XCTAssertEqual((row.value(atIndex: 0) as Double), 0.0)
XCTAssertFalse((row.value(atIndex: 0) as String?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Blob?) == nil) // incompatible with DatabaseValue conversion
}
return .Rollback
}
// Int64 is turned to Real
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO `values` (realAffinity) VALUES (?)", arguments: [0 as Int64])
for row in Row.fetch(db, "SELECT realAffinity FROM `values`") {
// Check SQLite conversions from Real storage
XCTAssertEqual((row.value(atIndex: 0) as Bool?)!, false)
XCTAssertEqual((row.value(atIndex: 0) as Bool), false)
XCTAssertEqual((row.value(atIndex: 0) as Int?)!, 0)
XCTAssertEqual((row.value(atIndex: 0) as Int), 0)
XCTAssertEqual((row.value(atIndex: 0) as Int32?)!, Int32(0))
XCTAssertEqual((row.value(atIndex: 0) as Int32), Int32(0))
XCTAssertEqual((row.value(atIndex: 0) as Int64?)!, Int64(0))
XCTAssertEqual((row.value(atIndex: 0) as Int64), Int64(0))
XCTAssertEqual((row.value(atIndex: 0) as Double?)!, 0.0)
XCTAssertEqual((row.value(atIndex: 0) as Double), 0.0)
XCTAssertFalse((row.value(atIndex: 0) as String?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Blob?) == nil) // incompatible with DatabaseValue conversion
}
return .Rollback
}
// Int32 is turned to Real
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO `values` (realAffinity) VALUES (?)", arguments: [0 as Int32])
for row in Row.fetch(db, "SELECT realAffinity FROM `values`") {
// Check SQLite conversions from Real storage
XCTAssertEqual((row.value(atIndex: 0) as Bool?)!, false)
XCTAssertEqual((row.value(atIndex: 0) as Bool), false)
XCTAssertEqual((row.value(atIndex: 0) as Int?)!, 0)
XCTAssertEqual((row.value(atIndex: 0) as Int), 0)
XCTAssertEqual((row.value(atIndex: 0) as Int32?)!, Int32(0))
XCTAssertEqual((row.value(atIndex: 0) as Int32), Int32(0))
XCTAssertEqual((row.value(atIndex: 0) as Int64?)!, Int64(0))
XCTAssertEqual((row.value(atIndex: 0) as Int64), Int64(0))
XCTAssertEqual((row.value(atIndex: 0) as Double?)!, 0.0)
XCTAssertEqual((row.value(atIndex: 0) as Double), 0.0)
XCTAssertFalse((row.value(atIndex: 0) as String?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Blob?) == nil) // incompatible with DatabaseValue conversion
}
return .Rollback
}
// 3.0e5 Double is turned to Real
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO `values` (realAffinity) VALUES (?)", arguments: [3.0e5])
for row in Row.fetch(db, "SELECT realAffinity FROM `values`") {
// Check SQLite conversions from Real storage
XCTAssertEqual((row.value(atIndex: 0) as Bool?)!, true)
XCTAssertEqual((row.value(atIndex: 0) as Bool), true)
XCTAssertEqual((row.value(atIndex: 0) as Int?)!, 300000)
XCTAssertEqual((row.value(atIndex: 0) as Int), 300000)
XCTAssertEqual((row.value(atIndex: 0) as Int32?)!, Int32(300000))
XCTAssertEqual((row.value(atIndex: 0) as Int32), Int32(300000))
XCTAssertEqual((row.value(atIndex: 0) as Int64?)!, Int64(300000))
XCTAssertEqual((row.value(atIndex: 0) as Int64), Int64(300000))
XCTAssertEqual((row.value(atIndex: 0) as Double?)!, Double(300000))
XCTAssertEqual((row.value(atIndex: 0) as Double), Double(300000))
XCTAssertFalse((row.value(atIndex: 0) as String?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Blob?) == nil) // incompatible with DatabaseValue conversion
}
return .Rollback
}
// 1.0e20 Double is turned to Real
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO `values` (realAffinity) VALUES (?)", arguments: [1.0e20])
for row in Row.fetch(db, "SELECT realAffinity FROM `values`") {
// Check SQLite conversions from Real storage (avoid Int, Int32 and Int64 since 1.0e20 does not fit)
XCTAssertEqual((row.value(atIndex: 0) as Bool?)!, true)
XCTAssertEqual((row.value(atIndex: 0) as Bool), true)
XCTAssertEqual((row.value(atIndex: 0) as Double?)!, 1e20)
XCTAssertEqual((row.value(atIndex: 0) as Double), 1e20)
XCTAssertFalse((row.value(atIndex: 0) as String?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Blob?) == nil) // incompatible with DatabaseValue conversion
}
return .Rollback
}
// "3.0e+5" is turned to Real
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO `values` (realAffinity) VALUES (?)", arguments: ["3.0e+5"])
for row in Row.fetch(db, "SELECT realAffinity FROM `values`") {
// Check SQLite conversions from Real storage
XCTAssertEqual((row.value(atIndex: 0) as Bool?)!, true)
XCTAssertEqual((row.value(atIndex: 0) as Bool), true)
XCTAssertEqual((row.value(atIndex: 0) as Int?)!, 300000)
XCTAssertEqual((row.value(atIndex: 0) as Int), 300000)
XCTAssertEqual((row.value(atIndex: 0) as Int32?)!, Int32(300000))
XCTAssertEqual((row.value(atIndex: 0) as Int32), Int32(300000))
XCTAssertEqual((row.value(atIndex: 0) as Int64?)!, Int64(300000))
XCTAssertEqual((row.value(atIndex: 0) as Int64), Int64(300000))
XCTAssertEqual((row.value(atIndex: 0) as Double?)!, Double(300000))
XCTAssertEqual((row.value(atIndex: 0) as Double), Double(300000))
XCTAssertFalse((row.value(atIndex: 0) as String?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Blob?) == nil) // incompatible with DatabaseValue conversion
}
return .Rollback
}
// "1.0e+20" is turned to Real
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO `values` (realAffinity) VALUES (?)", arguments: ["1.0e+20"])
for row in Row.fetch(db, "SELECT realAffinity FROM `values`") {
// Check SQLite conversions from Real storage: (avoid Int, Int32 and Int64 since 1.0e20 does not fit)
XCTAssertEqual((row.value(atIndex: 0) as Bool?)!, true)
XCTAssertEqual((row.value(atIndex: 0) as Bool), true)
XCTAssertEqual((row.value(atIndex: 0) as Double?)!, 1e20)
XCTAssertEqual((row.value(atIndex: 0) as Double), 1e20)
XCTAssertFalse((row.value(atIndex: 0) as String?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Blob?) == nil) // incompatible with DatabaseValue conversion
}
return .Rollback
}
// "foo" is turned to Text
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO `values` (realAffinity) VALUES (?)", arguments: ["foo"])
for row in Row.fetch(db, "SELECT realAffinity FROM `values`") {
// Check SQLite conversions from Text storage:
XCTAssertFalse((row.value(atIndex: 0) as Bool?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int32?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int64?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Double?) == nil) // incompatible with DatabaseValue conversion
XCTAssertEqual((row.value(atIndex: 0) as String?)!, "foo")
XCTAssertEqual((row.value(atIndex: 0) as String), "foo")
XCTAssertFalse((row.value(atIndex: 0) as Blob?) == nil) // incompatible with DatabaseValue conversion
}
return .Rollback
}
// Blob is turned to Blob
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO `values` (realAffinity) VALUES (?)", arguments: ["foo".dataUsingEncoding(NSUTF8StringEncoding)])
for row in Row.fetch(db, "SELECT realAffinity FROM `values`") {
// Check SQLite conversions from Blob storage:
XCTAssertFalse((row.value(atIndex: 0) as Bool?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int32?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int64?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Double?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as String?) == nil) // incompatible with DatabaseValue conversion
XCTAssertEqual((row.value(atIndex: 0) as Blob?), Blob(data: "foo".dataUsingEncoding(NSUTF8StringEncoding))!)
}
return .Rollback
}
}
}
func testNoneAffinity() {
// https://www.sqlite.org/datatype3.html
//
// > A column with affinity NONE does not prefer one storage class over
// > another and no attempt is made to coerce data from one storage
// > class into another.
assertNoError {
// Int is turned to Integer
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO `values` (noneAffinity) VALUES (?)", arguments: [0 as Int])
for row in Row.fetch(db, "SELECT noneAffinity FROM `values`") {
// Check SQLite conversions from Integer storage
XCTAssertEqual((row.value(atIndex: 0) as Bool?)!, false)
XCTAssertEqual((row.value(atIndex: 0) as Bool), false)
XCTAssertEqual((row.value(atIndex: 0) as Int?)!, 0)
XCTAssertEqual((row.value(atIndex: 0) as Int), 0)
XCTAssertEqual((row.value(atIndex: 0) as Int32?)!, Int32(0))
XCTAssertEqual((row.value(atIndex: 0) as Int32), Int32(0))
XCTAssertEqual((row.value(atIndex: 0) as Int64?)!, Int64(0))
XCTAssertEqual((row.value(atIndex: 0) as Int64), Int64(0))
XCTAssertEqual((row.value(atIndex: 0) as Double?)!, 0.0)
XCTAssertEqual((row.value(atIndex: 0) as Double), 0.0)
XCTAssertFalse((row.value(atIndex: 0) as String?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Blob?) == nil) // incompatible with DatabaseValue conversion
}
return .Rollback
}
// Int64 is turned to Integer
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO `values` (noneAffinity) VALUES (?)", arguments: [0 as Int64])
for row in Row.fetch(db, "SELECT noneAffinity FROM `values`") {
// Check SQLite conversions from Integer storage
XCTAssertEqual((row.value(atIndex: 0) as Bool?)!, false)
XCTAssertEqual((row.value(atIndex: 0) as Bool), false)
XCTAssertEqual((row.value(atIndex: 0) as Int?)!, 0)
XCTAssertEqual((row.value(atIndex: 0) as Int), 0)
XCTAssertEqual((row.value(atIndex: 0) as Int32?)!, Int32(0))
XCTAssertEqual((row.value(atIndex: 0) as Int32), Int32(0))
XCTAssertEqual((row.value(atIndex: 0) as Int64?)!, Int64(0))
XCTAssertEqual((row.value(atIndex: 0) as Int64), Int64(0))
XCTAssertEqual((row.value(atIndex: 0) as Double?)!, 0.0)
XCTAssertEqual((row.value(atIndex: 0) as Double), 0.0)
XCTAssertFalse((row.value(atIndex: 0) as String?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Blob?) == nil) // incompatible with DatabaseValue conversion
}
return .Rollback
}
// Int32 is turned to Integer
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO `values` (noneAffinity) VALUES (?)", arguments: [0 as Int32])
for row in Row.fetch(db, "SELECT noneAffinity FROM `values`") {
// Check SQLite conversions from Integer storage
XCTAssertEqual((row.value(atIndex: 0) as Bool?)!, false)
XCTAssertEqual((row.value(atIndex: 0) as Bool), false)
XCTAssertEqual((row.value(atIndex: 0) as Int?)!, 0)
XCTAssertEqual((row.value(atIndex: 0) as Int), 0)
XCTAssertEqual((row.value(atIndex: 0) as Int32?)!, Int32(0))
XCTAssertEqual((row.value(atIndex: 0) as Int32), Int32(0))
XCTAssertEqual((row.value(atIndex: 0) as Int64?)!, Int64(0))
XCTAssertEqual((row.value(atIndex: 0) as Int64), Int64(0))
XCTAssertEqual((row.value(atIndex: 0) as Double?)!, 0.0)
XCTAssertEqual((row.value(atIndex: 0) as Double), 0.0)
XCTAssertFalse((row.value(atIndex: 0) as String?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Blob?) == nil) // incompatible with DatabaseValue conversion
}
return .Rollback
}
// Double is turned to Real
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO `values` (noneAffinity) VALUES (?)", arguments: [0.0])
for row in Row.fetch(db, "SELECT noneAffinity FROM `values`") {
// Check SQLite conversions from Real storage
XCTAssertEqual((row.value(atIndex: 0) as Bool?)!, false)
XCTAssertEqual((row.value(atIndex: 0) as Bool), false)
XCTAssertEqual((row.value(atIndex: 0) as Int?)!, 0)
XCTAssertEqual((row.value(atIndex: 0) as Int), 0)
XCTAssertEqual((row.value(atIndex: 0) as Int32?)!, Int32(0))
XCTAssertEqual((row.value(atIndex: 0) as Int32), Int32(0))
XCTAssertEqual((row.value(atIndex: 0) as Int64?)!, Int64(0))
XCTAssertEqual((row.value(atIndex: 0) as Int64), Int64(0))
XCTAssertEqual((row.value(atIndex: 0) as Double?)!, 0.0)
XCTAssertEqual((row.value(atIndex: 0) as Double), 0.0)
XCTAssertFalse((row.value(atIndex: 0) as String?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Blob?) == nil) // incompatible with DatabaseValue conversion
}
return .Rollback
}
// "3.0e+5" is turned to Text
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO `values` (noneAffinity) VALUES (?)", arguments: ["3.0e+5"])
for row in Row.fetch(db, "SELECT noneAffinity FROM `values`") {
// Check SQLite conversions from Text storage
XCTAssertFalse((row.value(atIndex: 0) as Bool?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int32?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int64?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Double?) == nil) // incompatible with DatabaseValue conversion
XCTAssertEqual((row.value(atIndex: 0) as String?)!, "3.0e+5")
XCTAssertEqual((row.value(atIndex: 0) as String), "3.0e+5")
XCTAssertFalse((row.value(atIndex: 0) as Blob?) == nil) // incompatible with DatabaseValue conversion
}
return .Rollback
}
// Blob is turned to Blob
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO `values` (noneAffinity) VALUES (?)", arguments: ["foo".dataUsingEncoding(NSUTF8StringEncoding)])
for row in Row.fetch(db, "SELECT noneAffinity FROM `values`") {
// Check SQLite conversions from Blob storage
XCTAssertFalse((row.value(atIndex: 0) as Bool?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int32?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int64?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Double?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as String?) == nil) // incompatible with DatabaseValue conversion
XCTAssertEqual((row.value(atIndex: 0) as Blob?), Blob(data: "foo".dataUsingEncoding(NSUTF8StringEncoding))!)
}
return .Rollback
}
}
}
func testNumericAffinity(columnName: String) {
// https://www.sqlite.org/datatype3.html
//
// > A column with NUMERIC affinity may contain values using all five
// > storage classes. When text data is inserted into a NUMERIC column,
// > the storage class of the text is converted to INTEGER or REAL (in
// > order of preference) if such conversion is lossless and reversible.
// > For conversions between TEXT and REAL storage classes, SQLite
// > considers the conversion to be lossless and reversible if the first
// > 15 significant decimal digits of the number are preserved. If the
// > lossless conversion of TEXT to INTEGER or REAL is not possible then
// > the value is stored using the TEXT storage class. No attempt is
// > made to convert NULL or BLOB values.
// >
// > A string might look like a floating-point literal with a decimal
// > point and/or exponent notation but as long as the value can be
// > expressed as an integer, the NUMERIC affinity will convert it into
// > an integer. Hence, the string '3.0e+5' is stored in a column with
// > NUMERIC affinity as the integer 300000, not as the floating point
// > value 300000.0.
assertNoError {
// Int is turned to Integer
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO `values` (\(columnName)) VALUES (?)", arguments: [0 as Int])
for row in Row.fetch(db, "SELECT \(columnName) FROM `values`") {
// Check SQLite conversions from Integer storage
XCTAssertEqual((row.value(atIndex: 0) as Bool?)!, false)
XCTAssertEqual((row.value(atIndex: 0) as Bool), false)
XCTAssertEqual((row.value(atIndex: 0) as Int?)!, 0)
XCTAssertEqual((row.value(atIndex: 0) as Int), 0)
XCTAssertEqual((row.value(atIndex: 0) as Int32?)!, Int32(0))
XCTAssertEqual((row.value(atIndex: 0) as Int32), Int32(0))
XCTAssertEqual((row.value(atIndex: 0) as Int64?)!, Int64(0))
XCTAssertEqual((row.value(atIndex: 0) as Int64), Int64(0))
XCTAssertEqual((row.value(atIndex: 0) as Double?)!, 0.0)
XCTAssertEqual((row.value(atIndex: 0) as Double), 0.0)
XCTAssertFalse((row.value(atIndex: 0) as String?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Blob?) == nil) // incompatible with DatabaseValue conversion
}
return .Rollback
}
// Int64 is turned to Integer
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO `values` (\(columnName)) VALUES (?)", arguments: [0 as Int64])
for row in Row.fetch(db, "SELECT \(columnName) FROM `values`") {
// Check SQLite conversions from Integer storage
XCTAssertEqual((row.value(atIndex: 0) as Bool?)!, false)
XCTAssertEqual((row.value(atIndex: 0) as Bool), false)
XCTAssertEqual((row.value(atIndex: 0) as Int?)!, 0)
XCTAssertEqual((row.value(atIndex: 0) as Int), 0)
XCTAssertEqual((row.value(atIndex: 0) as Int32?)!, Int32(0))
XCTAssertEqual((row.value(atIndex: 0) as Int32), Int32(0))
XCTAssertEqual((row.value(atIndex: 0) as Int64?)!, Int64(0))
XCTAssertEqual((row.value(atIndex: 0) as Int64), Int64(0))
XCTAssertEqual((row.value(atIndex: 0) as Double?)!, 0.0)
XCTAssertEqual((row.value(atIndex: 0) as Double), 0.0)
XCTAssertFalse((row.value(atIndex: 0) as String?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Blob?) == nil) // incompatible with DatabaseValue conversion
}
return .Rollback
}
// Int32 is turned to Integer
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO `values` (\(columnName)) VALUES (?)", arguments: [0 as Int32])
for row in Row.fetch(db, "SELECT \(columnName) FROM `values`") {
// Check SQLite conversions from Integer storage
XCTAssertEqual((row.value(atIndex: 0) as Bool?)!, false)
XCTAssertEqual((row.value(atIndex: 0) as Bool), false)
XCTAssertEqual((row.value(atIndex: 0) as Int?)!, 0)
XCTAssertEqual((row.value(atIndex: 0) as Int), 0)
XCTAssertEqual((row.value(atIndex: 0) as Int32?)!, Int32(0))
XCTAssertEqual((row.value(atIndex: 0) as Int32), Int32(0))
XCTAssertEqual((row.value(atIndex: 0) as Int64?)!, Int64(0))
XCTAssertEqual((row.value(atIndex: 0) as Int64), Int64(0))
XCTAssertEqual((row.value(atIndex: 0) as Double?)!, 0.0)
XCTAssertEqual((row.value(atIndex: 0) as Double), 0.0)
XCTAssertFalse((row.value(atIndex: 0) as String?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Blob?) == nil) // incompatible with DatabaseValue conversion
}
return .Rollback
}
// 3.0e5 Double is turned to Integer
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO `values` (\(columnName)) VALUES (?)", arguments: [3.0e5])
for row in Row.fetch(db, "SELECT \(columnName) FROM `values`") {
// Check SQLite conversions from Integer storage
XCTAssertEqual((row.value(atIndex: 0) as Bool?)!, true)
XCTAssertEqual((row.value(atIndex: 0) as Bool), true)
XCTAssertEqual((row.value(atIndex: 0) as Int?)!, 300000)
XCTAssertEqual((row.value(atIndex: 0) as Int), 300000)
XCTAssertEqual((row.value(atIndex: 0) as Int32?)!, Int32(300000))
XCTAssertEqual((row.value(atIndex: 0) as Int32), Int32(300000))
XCTAssertEqual((row.value(atIndex: 0) as Int64?)!, Int64(300000))
XCTAssertEqual((row.value(atIndex: 0) as Int64), Int64(300000))
XCTAssertEqual((row.value(atIndex: 0) as Double?)!, Double(300000))
XCTAssertEqual((row.value(atIndex: 0) as Double), Double(300000))
XCTAssertFalse((row.value(atIndex: 0) as String?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Blob?) == nil) // incompatible with DatabaseValue conversion
}
return .Rollback
}
// 1.0e20 Double is turned to Real
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO `values` (\(columnName)) VALUES (?)", arguments: [1.0e20])
for row in Row.fetch(db, "SELECT \(columnName) FROM `values`") {
// Check SQLite conversions from Real storage (avoid Int, Int32 and Int64 since 1.0e20 does not fit)
XCTAssertEqual((row.value(atIndex: 0) as Bool?)!, true)
XCTAssertEqual((row.value(atIndex: 0) as Bool), true)
XCTAssertEqual((row.value(atIndex: 0) as Double?)!, 1e20)
XCTAssertEqual((row.value(atIndex: 0) as Double), 1e20)
XCTAssertFalse((row.value(atIndex: 0) as String?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Blob?) == nil) // incompatible with DatabaseValue conversion
}
return .Rollback
}
// "3.0e+5" is turned to Integer
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO `values` (\(columnName)) VALUES (?)", arguments: ["3.0e+5"])
for row in Row.fetch(db, "SELECT \(columnName) FROM `values`") {
// Check SQLite conversions from Integer storage
XCTAssertEqual((row.value(atIndex: 0) as Bool?)!, true)
XCTAssertEqual((row.value(atIndex: 0) as Bool), true)
XCTAssertEqual((row.value(atIndex: 0) as Int?)!, 300000)
XCTAssertEqual((row.value(atIndex: 0) as Int), 300000)
XCTAssertEqual((row.value(atIndex: 0) as Int32?)!, Int32(300000))
XCTAssertEqual((row.value(atIndex: 0) as Int32), Int32(300000))
XCTAssertEqual((row.value(atIndex: 0) as Int64?)!, Int64(300000))
XCTAssertEqual((row.value(atIndex: 0) as Int64), Int64(300000))
XCTAssertEqual((row.value(atIndex: 0) as Double?)!, Double(300000))
XCTAssertEqual((row.value(atIndex: 0) as Double), Double(300000))
XCTAssertFalse((row.value(atIndex: 0) as String?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Blob?) == nil) // incompatible with DatabaseValue conversion
}
return .Rollback
}
// "1.0e+20" is turned to Real
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO `values` (\(columnName)) VALUES (?)", arguments: ["1.0e+20"])
for row in Row.fetch(db, "SELECT \(columnName) FROM `values`") {
// Check SQLite conversions from Real storage: (avoid Int, Int32 and Int64 since 1.0e20 does not fit)
XCTAssertEqual((row.value(atIndex: 0) as Bool?)!, true)
XCTAssertEqual((row.value(atIndex: 0) as Bool), true)
XCTAssertEqual((row.value(atIndex: 0) as Double?)!, 1e20)
XCTAssertEqual((row.value(atIndex: 0) as Double), 1e20)
XCTAssertFalse((row.value(atIndex: 0) as String?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Blob?) == nil) // incompatible with DatabaseValue conversion
}
return .Rollback
}
// "foo" is turned to Text
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO `values` (\(columnName)) VALUES (?)", arguments: ["foo"])
for row in Row.fetch(db, "SELECT \(columnName) FROM `values`") {
// Check SQLite conversions from Text storage:
XCTAssertFalse((row.value(atIndex: 0) as Bool?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int32?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int64?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Double?) == nil) // incompatible with DatabaseValue conversion
XCTAssertEqual((row.value(atIndex: 0) as String?)!, "foo")
XCTAssertEqual((row.value(atIndex: 0) as String), "foo")
XCTAssertFalse((row.value(atIndex: 0) as Blob?) == nil) // incompatible with DatabaseValue conversion
}
return .Rollback
}
// Blob is turned to Blob
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO `values` (\(columnName)) VALUES (?)", arguments: ["foo".dataUsingEncoding(NSUTF8StringEncoding)])
for row in Row.fetch(db, "SELECT \(columnName) FROM `values`") {
// Check SQLite conversions from Blob storage:
XCTAssertFalse((row.value(atIndex: 0) as Bool?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int32?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Int64?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as Double?) == nil) // incompatible with DatabaseValue conversion
XCTAssertFalse((row.value(atIndex: 0) as String?) == nil) // incompatible with DatabaseValue conversion
XCTAssertEqual((row.value(atIndex: 0) as Blob?), Blob(data: "foo".dataUsingEncoding(NSUTF8StringEncoding))!)
}
return .Rollback
}
}
}
}
|
mit
|
d7ebe8ecc8dcc69a693c1f10e0c4bf7c
| 62.586298 | 141 | 0.548651 | 5.001244 | false | false | false | false |
jindulys/Leetcode_Solutions_Swift
|
Sources/Tree/100_SameTree.swift
|
1
|
1019
|
//
// 100_SameTree.swift
// HRSwift
//
// Created by yansong li on 2016-08-02.
// Copyright © 2016 yansong li. All rights reserved.
//
import Foundation
/**
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
*/
/**
Swift Knowledge:
Enum Comparison
Algorithem Knowledge:
Recursive call.
*/
/**
100. Same Tree
https://leetcode.com/problems/same-tree/
*/
class Solution_SameTree {
func isSameTree(_ p: TreeNode?, _ q: TreeNode?) -> Bool {
switch(p, q){
case (let .some(leftRoot), let .some(rightRoot)):
let valEqual = (leftRoot.val == rightRoot.val)
let leftEqual = isSameTree(leftRoot.left, rightRoot.left)
let rightEqual = isSameTree(leftRoot.right, rightRoot.right)
return valEqual && leftEqual && rightEqual
case (.none, .none):
return true
default:
return false
}
}
}
|
mit
|
5d0a07a1862fc80dd5224ba4717cc3f7
| 21.130435 | 109 | 0.649312 | 3.742647 | false | false | false | false |
xwu/swift
|
test/Distributed/actor_protocols.swift
|
1
|
2316
|
// RUN: %target-typecheck-verify-swift -enable-experimental-distributed -disable-availability-checking
// REQUIRES: concurrency
// REQUIRES: distributed
import _Distributed
// ==== -----------------------------------------------------------------------
actor A: Actor {} // ok
class C: Actor, UnsafeSendable {
// expected-error@-1{{non-actor type 'C' cannot conform to the 'Actor' protocol}} {{1-6=actor}}
// expected-warning@-2{{'UnsafeSendable' is deprecated: Use @unchecked Sendable instead}}
nonisolated var unownedExecutor: UnownedSerialExecutor {
fatalError()
}
}
struct S: Actor {
// expected-error@-1{{non-class type 'S' cannot conform to class protocol 'Actor'}}
nonisolated var unownedExecutor: UnownedSerialExecutor {
fatalError()
}
}
struct E: Actor {
// expected-error@-1{{non-class type 'E' cannot conform to class protocol 'Actor'}}
nonisolated var unownedExecutor: UnownedSerialExecutor {
fatalError()
}
}
// ==== -----------------------------------------------------------------------
distributed actor DA: DistributedActor {} // ok
actor A2: DistributedActor {
// expected-error@-1{{non-distributed actor type 'A2' cannot conform to the 'DistributedActor' protocol}} {{1-1=distributed }}
nonisolated var id: AnyActorIdentity {
fatalError()
}
nonisolated var actorTransport: ActorTransport {
fatalError()
}
init(transport: ActorTransport) {
fatalError()
}
static func resolve(_ identity: AnyActorIdentity, using transport: ActorTransport) throws -> Self {
fatalError()
}
}
final class C2: DistributedActor {
// expected-error@-1{{non-actor type 'C2' cannot conform to the 'Actor' protocol}}
nonisolated var id: AnyActorIdentity {
fatalError()
}
nonisolated var actorTransport: ActorTransport {
fatalError()
}
required init(transport: ActorTransport) {
fatalError()
}
static func resolve(_ identity: AnyActorIdentity, using transport: ActorTransport) throws -> Self {
fatalError()
}
}
struct S2: DistributedActor {
// expected-error@-1{{non-class type 'S2' cannot conform to class protocol 'DistributedActor'}}
// expected-error@-2{{non-class type 'S2' cannot conform to class protocol 'AnyActor'}}
// expected-error@-3{{type 'S2' does not conform to protocol 'Identifiable'}}
}
|
apache-2.0
|
8304d24a96d79c1421991c9945960bc6
| 29.077922 | 128 | 0.66494 | 4.411429 | false | false | false | false |
kalanyuz/SwiftR
|
CommonSource/common/SRMergePlotView.swift
|
1
|
3018
|
//
// SRMergePlotView.swift
// NativeSigP
//
// Created by Kalanyu Zintus-art on 10/20/15.
// Copyright © 2017 KalanyuZ. All rights reserved.
//
open class SRMergePlotView: SRPlotView {
open var numberOfTicks : Int = 0
open var maxDataRange : Int {
get {
return (self.axeLayer?.maxDataRange)!
}
set {
self.axeLayer?.maxDataRange = newValue
#if os(macOS)
let textSize = "\(self.maxDataRange)".size(withAttributes: [NSFontAttributeName: SRFont.boldSystemFont(ofSize: 20)])
#elseif os(iOS)
let textSize = "\(self.maxDataRange)".size(attributes: [NSFontAttributeName: SRFont.boldSystemFont(ofSize: 20)])
#endif
self.axeLayer?.padding.x = newValue < 10 ? textSize.width * 3: textSize.width
self.axeLayer?.layer.setNeedsDisplay()
}
}
open var axeOrigin = CGPoint.zero
//MARK: Initialization
required public init?(coder: NSCoder) {
super.init(coder: coder)
self.axeLayer!.layer.removeFromSuperlayer()
//
self.axeLayer = SRPlotAxe(frame: self.frame, axeOrigin: CGPoint.zero, xPointsToShow: totalSecondsToDisplay, yPointsToShow: totalChannelsToDisplay, numberOfSubticks: 1)
#if os(macOS)
self.layer!.addSublayer(self.axeLayer!.layer)
#elseif os(iOS)
self.layer.addSublayer(self.axeLayer!.layer)
#endif
self.axeLayer?.yPointsToShow = 2
self.axeLayer?.graph.anchorPoint = CGPoint(x: 0, y: 0.5)
self.axeLayer?.hashSystem.anchorPoint = CGPoint(x: 0, y: 0.5)
self.axeLayer?.hashSystem.color = SRColor.darkGray
self.titleField?.textColor = SRColor.darkGray
self.axeLayer?.signalType = .merge
self.maxDataRange = 1
}
required public init(frame frameRect: SRRect) {
super.init(frame: frameRect)
}
convenience init(frame frameRect: SRRect, title: String, seconds: Double, maxRange: (CGPoint, CGPoint), samplingRatae: CGFloat, origin: CGPoint, padding: CGFloat = 0.0) {
self.init(frame: frameRect)
}
// The initial position of a segment that is meant to be displayed on the left side of the graph.
// This positioning is meant so that a few entries must be added to the segment's history before it becomes
// visible to the user. This value could be tweaked a little bit with varying results, but the X coordinate
// should never be larger than 16 (the center of the text view) or the zero values in the segment's history
// will be exposed to the user.
//
override var kSegmentInitialPosition : CGPoint {
get {
//something about anchor point being 0.5
//line width hack
#if os(macOS)
return CGPoint(x: graphAxes.position.x - graphAxes.pointsPerUnit.x - 1, y: graphAxes.position.y + 1)
#elseif os(iOS)
return CGPoint(x: graphAxes.position.x - graphAxes.pointsPerUnit.x , y: graphAxes.position.y - graphAxes.padding.y)
#endif
}
}
}
|
apache-2.0
|
d80938d4db5b099ddf16d1f437d53b32
| 33.678161 | 175 | 0.659927 | 3.887887 | false | false | false | false |
gyro-n/PaymentsIos
|
GyronPayments/Classes/Models/WebhookEvent.swift
|
1
|
1979
|
//
// WebhookEvent.swift
// GyronPayments
//
// Created by David Ye on 2017/09/21.
// Copyright © 2017 gyron. All rights reserved.
//
import Foundation
/**
The WebhookEvent class stores information about webhook events.
*/
open class WebhookEvent: BaseModel {
/**
The unique identifier for the webhook event.
*/
public var id: String
/**
The unique identifier for the webhook.
*/
public var webhookId: String
/**
The unique identifier for the platform.
*/
public var platformId: String
/**
The type of event for the webhook event.
*/
public var event: PaymentSystemEvent
/**
Any metadata to associate with the webhook event.
*/
public var data: Metadata
/**
Whether or not the webhook event was successful.
*/
public var successful: Bool
/**
The date the webhook event was created.
*/
public var createdOn: String
/**
The date the webhook event was fired.
*/
public var firedOn: String
/**
Initializes the WebhookEvent object
*/
override init() {
id = ""
platformId = ""
event = PaymentSystemEvent.chargeFinished
data = Metadata()
createdOn = ""
firedOn = ""
webhookId = ""
successful = false
}
/**
Maps the values from a hash map object into the WebhookEvent.
*/
override open func mapFromObject(map: ResponseData) {
id = map["id"] as? String ?? ""
platformId = map["platform_id"] as? String ?? ""
event = PaymentSystemEvent(rawValue: map["event"] as? String ?? PaymentSystemEvent.chargeFinished.rawValue)!
data = map["data"] as? Metadata ?? Metadata()
createdOn = map["created_on"] as? String ?? ""
firedOn = map["fired_on"] as? String ?? ""
webhookId = map["webhook_id"] as? String ?? ""
successful = map["successful"] as? Bool ?? false
}
}
|
mit
|
4bad7ab1cb7467154476fe4b9b399fc8
| 25.373333 | 116 | 0.594034 | 4.434978 | false | false | false | false |
dcunited001/SpectraNu
|
Spectra/Node/WorldView.swift
|
1
|
808
|
//
// WorldView.swift
// Pods
//
// Created by David Conner on 10/20/15.
//
//
import simd
public protocol WorldView: class {
var uniforms: Uniformable { get set }
// TODO: add activeCamera?
}
public class BaseWorldView: WorldView {
public var uniforms: Uniformable
public init() {
uniforms = BaseUniforms()
}
}
//public class WorldUniforms {
// public var uniformScale = float4()
// public var uniformPosition = float4()
// public var uniformRotation = float4()
//
// public init() {
// setUniformableDefaults()
// }
//
// public func setUniformableDefaults() {
// uniformScale = float4(1.0, 1.0, 1.0, 1.0)
// uniformPosition = float4(0.0, 0.0, 1.0, 1.0)
// uniformRotation = float4(1.0, 1.0, 1.0, 90)
// }
//}
|
mit
|
407de36eae8d701059e0a1a0b623f88c
| 20.289474 | 54 | 0.595297 | 3.181102 | false | false | false | false |
hawkfalcon/SpaceEvaders
|
SpaceEvaders/GameScene.swift
|
1
|
9091
|
import SpriteKit
import AVFoundation
class GameScene: SKScene {
var viewController: GameViewController?
let alienSpawnRate = 5
var isGameOver = false
var gamePaused = false
var removeAliens = false
var scoreboard: Scoreboard!
var rocket: Rocket!
var pause: Pause!
var audioPlayer = AVAudioPlayer()
override func didMove(to view: SKView) {
if Options.option.get(option: "sound") {
run(SKAction.playSoundFileNamed("Start.mp3", waitForCompletion: false))
}
backgroundColor = UIColor.black
Background(size: size).addTo(parent: self)
rocket = Rocket(x: size.width / 2, y: size.height / 2).addToSelf(parent: self) as? Rocket
scoreboard = Scoreboard(x: 50, y: size.height - size.height / 5).addTo(parentNode: self)
scoreboard.viewController = self.viewController
pause = Pause(size: size, x: size.width - 50, y: size.height - size.height / 6).addTo(parent: self)
if Options.option.get(option: "music") {
loopBackground(name: "Chamber-of-Jewels")
audioPlayer.play()
}
}
var currentPosition: CGPoint!
var currentlyTouching = false
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else {return}
currentPosition = touch.location(in: self)
let touched = self.atPoint(currentPosition)
if let name = touched.name {
switch name {
case "gameover":
resetGame()
case "pause":
pauseGame()
case "leaderboard":
viewController?.openGC()
case "option_music":
if Options.option.get(option: "music") {
audioPlayer.stop()
} else {
loopBackground(name: "Chamber-of-Jewels")
//audioPlayer.play()
}
default:
currentlyTouching = true
}
Utility.pressButton(main: self, touched: touched, score: String(scoreboard.getScore()))
} else {
currentlyTouching = true
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else {return}
currentPosition = touch.location(in: self)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if Options.option.get(option: "follow") {
currentlyTouching = false
}
}
var pausemenu: PopupMenu!
func pauseGame() {
if gamePaused {
if Options.option.get(option: "music") {
loopBackground(name: "Chamber-of-Jewels")
audioPlayer.play()
}
gamePaused = false
//speed = 1
isPaused = false
removeDialog()
} else {
if !isGameOver {
if Options.option.get(option: "music") {
audioPlayer.stop()
}
gamePaused = true
//speed = 0
pause.removeThis()
pausemenu = PopupMenu(size: size, title: "Paused", label: "Continue?", id: "pause")
pausemenu.addTo(parent: self)
}
}
}
func removeDialog() {
if pausemenu != nil {
pausemenu.removeThis()
pause = Pause(size: size, x: size.width - 50, y: size.height - size.height / 6).addTo(parent: self)
}
}
override func update(_ currentTime: TimeInterval) {
if !gamePaused {
if !isGameOver {
if currentlyTouching {
rocket.moveTo(x: currentPosition.x, y: currentPosition.y)
}
spawnPowerup()
enumeratePowerups()
}
spawnAliens(startAtTop: true)
spawnAliens(startAtTop: false)
enumerateAliens()
}
}
func spawnAliens(startAtTop: Bool) {
if Int(arc4random()) % 1000 < alienSpawnRate {
let randomX = 10 + Int(arc4random()) % Int(size.width) - 10
let startY = startAtTop ? size.height : 0
let arrowY = startAtTop ? size.height - 200 : 200
let alien = Alien(x: CGFloat(randomX), y: startY, startAtTop: startAtTop).addToSelf(parent: self)
alien.zPosition = 2
if Utility.checkPremium() && Options.option.get(option: "indicators") {
let arrow = Sprite(named: "credits", x: CGFloat(randomX), y: arrowY, scale: 0.05).addToSelf(parent: self)
arrow.zPosition = 1
arrow.run(
SKAction.sequence([
SKAction.fadeAlpha(to: 0.5, duration: 1),
SKAction.removeFromParent(),
])
)
}
}
}
func spawnPowerup() {
if Int(arc4random()) % 1000 < 1 {
let x = CGFloat(Int(arc4random()) % Int(size.width))
let y = CGFloat(Int(arc4random()) % Int(size.height))
let powerup = Powerup(x: x, y: y).addToSelf(parent: self)
powerup.run(
SKAction.sequence([
SKAction.fadeAlpha(to: 1, duration: 0.5),
SKAction.wait(forDuration: 4.5),
SKAction.fadeAlpha(to: 0, duration: 1.0),
SKAction.removeFromParent()
])
)
}
}
func gameOver() {
if Options.option.get(option: "sound") {
run(SKAction.playSoundFileNamed("Death.mp3", waitForCompletion: false))
}
isGameOver = true
let exp = Explosion(x: rocket.position.x, y: rocket.position.y).addToSelf(parent: self) as! Explosion
if Options.option.get(option: "music") {
audioPlayer.stop()
}
exp.boom(main: self)
rocket.removeFromParent()
pause.removeThis()
PopupMenu(size: size, title: "Game Over!", label: "Play Again?", id: "gameover").addTo(parent: self)
if scoreboard.isHighscore() {
addChild(scoreboard.getHighscoreLabel(size: size))
}
}
func resetGame() {
let gameScene = GameScene(size: size)
gameScene.viewController = self.viewController
gameScene.scaleMode = scaleMode
let reveal = SKTransition.doorsOpenVertical(withDuration: 0.5)
view?.presentScene(gameScene, transition: reveal)
}
func enumerateAliens() {
self.enumerateChildNodes(withName: "alien") {
node, stop in
let alien = node as! Alien
self.alienBrains(alien: alien)
}
if (removeAliens) {
removeAliens = false
}
}
func alienBrains(alien: Alien) {
let y = alien.position.y
if !isGameOver {
if alien.frame.insetBy(dx: 25, dy: 25).intersects(rocket.frame.insetBy(dx: 10, dy: 10)) {
gameOver()
}
//disabled by laser
if !alien.isDisabled() {
let middle = size.height / 2
let startAtTop = alien.startAtTop
if (!startAtTop! && y > middle) || (startAtTop! && y < middle) {
alien.setDisabled()
scoreboard.addScore(score: 1)
if Options.option.get(option: "sound") {
run(SKAction.playSoundFileNamed("Alien_Disable.mp3", waitForCompletion: false))
}
}
}
if removeAliens {
if !alien.isDisabled() {
scoreboard.addScore(score: 1)
}
alien.removeFromParent()
}
alien.moveTo(point: CGPoint(x: rocket.position.x, y: rocket.position.y))
} else {
alien.move()
}
if y < 0 || y > size.height {
alien.removeFromParent()
}
}
func enumeratePowerups() {
self.enumerateChildNodes(withName: "powerup") {
node, stop in
if node.frame.insetBy(dx: 5, dy: 5).intersects(self.rocket.frame) {
if Options.option.get(option: "sound") {
self.run(SKAction.playSoundFileNamed("Powerup.mp3", waitForCompletion: false))
}
let explosion = Explosion(x: node.position.x, y: node.position.y)
node.removeFromParent()
explosion.addTo(parent: self)
explosion.boom(main: self)
}
}
}
func loopBackground(name: String) {
let backgroundSound = URL(fileURLWithPath: Bundle.main.path(forResource: name, ofType: "mp3")!)
do {
audioPlayer = try AVAudioPlayer(contentsOf: backgroundSound)
} catch _ as NSError {
print("Failed to set sound")
}
audioPlayer.numberOfLoops = -1
audioPlayer.volume = 0.4
audioPlayer.prepareToPlay()
}
}
|
mit
|
a56ec15aba7c0a402e3e829c308c335e
| 35.075397 | 121 | 0.535585 | 4.543228 | false | false | false | false |
Sharelink/Bahamut
|
Bahamut/BahamutCommon/String+MD5.swift
|
1
|
1349
|
//
// String+MD5.swift
// Vessage
//
// Created by Alex Chow on 2016/11/25.
// Copyright © 2016年 Bahamut. All rights reserved.
//
import Foundation
extension String {
var md5 : String{
let str = self.cString(using: String.Encoding.utf8)
let strLen = CC_LONG(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_MD5_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen);
CC_MD5(str!, strLen, result);
let hash = NSMutableString();
for i in 0 ..< digestLen {
hash.appendFormat("%02x", result[i]);
}
result.deinitialize();
return String(format: hash as String)
}
var sha256 : String{
let str = self.cString(using: String.Encoding.utf8)
let strLen = CC_LONG(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen);
CC_SHA256(str!, strLen, result)
let hash = NSMutableString();
for i in 0 ..< digestLen {
hash.appendFormat("%02x", result[i]);
}
result.deinitialize();
return String(format: hash as String)
}
}
|
mit
|
35d946e049be7cf34566f14bea364590
| 28.911111 | 87 | 0.59584 | 4.20625 | false | false | false | false |
naokits/my-programming-marathon
|
RxSwiftDemo/Carthage/Checkouts/RxSwift/RxExample/RxExample/Examples/GitHubSignup/UsingDriver/GitHubSignupViewController2.swift
|
5
|
3640
|
//
// GitHubSignupViewController2.swift
// RxExample
//
// Created by Krunoslav Zaher on 4/25/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import UIKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
class GitHubSignupViewController2 : ViewController {
@IBOutlet weak var usernameOutlet: UITextField!
@IBOutlet weak var usernameValidationOutlet: UILabel!
@IBOutlet weak var passwordOutlet: UITextField!
@IBOutlet weak var passwordValidationOutlet: UILabel!
@IBOutlet weak var repeatedPasswordOutlet: UITextField!
@IBOutlet weak var repeatedPasswordValidationOutlet: UILabel!
@IBOutlet weak var signupOutlet: UIButton!
@IBOutlet weak var signingUpOulet: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
let viewModel = GithubSignupViewModel2(
input: (
username: usernameOutlet.rx_text.asDriver(),
password: passwordOutlet.rx_text.asDriver(),
repeatedPassword: repeatedPasswordOutlet.rx_text.asDriver(),
loginTaps: signupOutlet.rx_tap.asDriver()
),
dependency: (
API: GitHubDefaultAPI.sharedAPI,
validationService: GitHubDefaultValidationService.sharedValidationService,
wireframe: DefaultWireframe.sharedInstance
)
)
// bind results to {
viewModel.signupEnabled
.driveNext { [weak self] valid in
self?.signupOutlet.enabled = valid
self?.signupOutlet.alpha = valid ? 1.0 : 0.5
}
.addDisposableTo(disposeBag)
viewModel.validatedUsername
.drive(usernameValidationOutlet.ex_validationResult)
.addDisposableTo(disposeBag)
viewModel.validatedPassword
.drive(passwordValidationOutlet.ex_validationResult)
.addDisposableTo(disposeBag)
viewModel.validatedPasswordRepeated
.drive(repeatedPasswordValidationOutlet.ex_validationResult)
.addDisposableTo(disposeBag)
viewModel.signingIn
.drive(signingUpOulet.rx_animating)
.addDisposableTo(disposeBag)
viewModel.signedIn
.driveNext { signedIn in
print("User signed in \(signedIn)")
}
.addDisposableTo(disposeBag)
//}
let tapBackground = UITapGestureRecognizer()
tapBackground.rx_event
.subscribeNext { [weak self] _ in
self?.view.endEditing(true)
}
.addDisposableTo(disposeBag)
view.addGestureRecognizer(tapBackground)
}
// This is one of the reasons why it's a good idea for disposal to be detached from allocations.
// If resources weren't disposed before view controller is being deallocated, signup alert view
// could be presented on top of the wrong screen or could crash your app if it was being presented
// while navigation stack is popping.
// This will work well with UINavigationController, but has an assumption that view controller will
// never be added as a child view controller. If we didn't recreate the dispose bag here,
// then our resources would never be properly released.
override func willMoveToParentViewController(parent: UIViewController?) {
if let parent = parent {
assert(parent.isKindOfClass(UINavigationController), "Please read comments")
}
else {
self.disposeBag = DisposeBag()
}
}
}
|
mit
|
4b749405643d1a7cf87de66d4b894b78
| 34.339806 | 103 | 0.653201 | 5.375185 | false | false | false | false |
Bouke/HAP
|
Sources/HAP/Base/Predefined/Characteristics/Characteristic.OperatingStateResponse.swift
|
1
|
2099
|
import Foundation
public extension AnyCharacteristic {
static func operatingStateResponse(
_ value: Data = Data(),
permissions: [CharacteristicPermission] = [.read, .events],
description: String? = "Operating State Response",
format: CharacteristicFormat? = .tlv8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = nil,
minValue: Double? = nil,
minStep: Double? = nil,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> AnyCharacteristic {
AnyCharacteristic(
PredefinedCharacteristic.operatingStateResponse(
value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange) as Characteristic)
}
}
public extension PredefinedCharacteristic {
static func operatingStateResponse(
_ value: Data = Data(),
permissions: [CharacteristicPermission] = [.read, .events],
description: String? = "Operating State Response",
format: CharacteristicFormat? = .tlv8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = nil,
minValue: Double? = nil,
minStep: Double? = nil,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> GenericCharacteristic<Data> {
GenericCharacteristic<Data>(
type: .operatingStateResponse,
value: value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange)
}
}
|
mit
|
5ef8c81581046bcf7c9cf91178fea255
| 33.409836 | 67 | 0.585993 | 5.437824 | false | false | false | false |
rokuz/omim
|
iphone/Maps/UI/Search/Filters/FilterCollectionHolderCell.swift
|
1
|
1337
|
@objc(MWMFilterCollectionHolderCell)
final class FilterCollectionHolderCell: MWMTableViewCell {
@IBOutlet private(set) weak var collectionView: UICollectionView!
@IBOutlet private weak var collectionViewHeight: NSLayoutConstraint!
private weak var tableView: UITableView?
override var frame: CGRect {
didSet {
if frame.size.height < 1 /* minimal correct height */ {
frame.size.height = max(collectionViewHeight.constant, 1)
tableView?.refresh()
}
}
}
private func layout() {
collectionView.setNeedsLayout()
collectionView.layoutIfNeeded()
if abs(collectionViewHeight.constant - collectionView.contentSize.height) > 2.0 {
let newHeight = collectionView.contentSize.height
collectionViewHeight.constant = newHeight
frame.size.height = newHeight
tableView?.reloadData()
}
}
@objc func config(tableView: UITableView?) {
self.tableView = tableView
layout()
collectionView.allowsMultipleSelection = true
collectionView.contentInset = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
collectionView.reloadData()
}
override func awakeFromNib() {
super.awakeFromNib()
isSeparatorHidden = true
backgroundColor = UIColor.clear
}
override func layoutSubviews() {
super.layoutSubviews()
layout()
}
}
|
apache-2.0
|
0e88b1a7ab5b4d2ac1f8a766f61f1df5
| 29.386364 | 86 | 0.713538 | 5.045283 | false | false | false | false |
Marguerite-iOS/Marguerite
|
Marguerite/ShuttleSystem+Favorites.swift
|
1
|
1758
|
//
// ShuttleSystem+Favorites.swift
// Marguerite
//
// Created by Andrew Finke on 1/26/16.
// Copyright © 2016 Andrew Finke. All rights reserved.
//
extension ShuttleSystem {
// MARK: - Favorite stops
func loadFavorites() {
favoriteStops = []
if let favs = DefaultsHelper.getObjectForKey(DataKey.FavoriteStopIDs.rawValue) as? [Int] {
favoriteStopIDs = favs
favoriteStopIDs.forEach({
if let stop = shuttleStopWithID($0.description) {
favoriteStops.append(stop)
}
})
favoriteStops.sortInPlace({$0.name < $1.name})
} else {
favoriteStopIDs = []
}
}
/**
Adds a shuttle stop to the favorites.
- parameter stop: The shuttle stop.
*/
func addStopToFavorites(stop: ShuttleStop) {
favoriteStops.append(stop)
favoriteStopIDs.append(stop.stopID)
DefaultsHelper.saveDataForKey(favoriteStopIDs, key: DataKey.FavoriteStopIDs.rawValue)
}
/**
Removes a shuttle stop from the favorites.
- parameter stop: The shuttle stop.
*/
func removeStopFromFavorites(stop: ShuttleStop) {
if let index = favoriteStopIDs.indexOf(stop.stopID) {
favoriteStops.removeAtIndex(index)
favoriteStopIDs.removeAtIndex(index)
DefaultsHelper.saveDataForKey(favoriteStopIDs, key: DataKey.FavoriteStopIDs.rawValue)
}
}
/**
Detects if a stop has been favorited
- parameter stop: The shuttle stop.
- returns: The Bool value.
*/
func isStopFavorited(stop: ShuttleStop) -> Bool {
return favoriteStopIDs.contains(stop.stopID)
}
}
|
mit
|
be684abbd4785b17ca7d63c2a3935283
| 27.803279 | 98 | 0.606147 | 4.3925 | false | true | false | false |
mattwelborn/HSTracker
|
HSTracker/Core/CleanroomLogger/HSTrackerLogFormatter.swift
|
1
|
1897
|
//
// HSTrackerLogFormatter.swift
// HSTracker
//
// Created by Benjamin Michotte on 30/03/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
import CleanroomLogger
struct HSTrackerColorTable: CleanroomLogger.ColorTable {
static let VerboseColor = Color(r: 0xA6, g: 0xA6, b: 0xA6)
static let DebugColor = Color(r: 0xA6, g: 0xA6, b: 0xA6)
static let InfoColor = Color(r: 0xDB, g: 0xDF, b: 0xFF)
static let WarningColor = Color(r: 0xF3, g: 0xA2, b: 0x5F)
static let ErrorColor = Color(r: 0xCC, g: 0x31, b: 0x7C)
func foregroundColorForSeverity(severity: LogSeverity) -> Color? {
switch severity {
case .Verbose: return self.dynamicType.VerboseColor
case .Debug: return self.dynamicType.DebugColor
case .Info: return self.dynamicType.InfoColor
case .Warning: return self.dynamicType.WarningColor
case .Error: return self.dynamicType.ErrorColor
}
}
}
class HSTrackerLogFormatter: XcodeLogFormatter {
let dateFormatter: NSDateFormatter = {
let formatter = NSDateFormatter()
//formatter.timeZone = NSTimeZone(name: "UTC")
formatter.dateFormat = "HH:mm:ss.SSS"
return formatter
}()
override func formatLogEntry(entry: LogEntry) -> String? {
let severity: String
switch entry.severity {
case .Verbose: severity = "V"
case .Debug: severity = "D"
case .Info: severity = "I"
case .Warning: severity = "W"
case .Error: severity = "E"
}
let message: String
switch entry.payload {
case .Trace: message = entry.callingStackFrame
case .Message(let msg): message = msg
case .Value(let value): message = "\(value)"
}
return "|\(severity)|\(dateFormatter.stringFromDate(entry.timestamp))| \(message)"
}
}
|
mit
|
213135ceefc74d5bc8000b9d729a1c57
| 31.689655 | 90 | 0.640823 | 3.941788 | false | false | false | false |
gerdmuller/See-A-Note
|
See A Note/Score-Line/ScoreGestures.swift
|
1
|
9951
|
//
// ScoreGestures.swift
// See A Note
//
// Created by Gerd Müller on 15.09.15.
// Copyright © 2015 Gerd Müller. All rights reserved.
//
import Foundation
import UIKit
import AudioToolbox
class PanPressGestureRecognizer: UIPanGestureRecognizer {
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent) {
if #available(iOS 9.0, *) {
if let touch = touches.first {
if touch.force >= touch.maximumPossibleForce / 1.5 {
pressed = true
}
if touch.force <= touch.maximumPossibleForce / 6 {
pressed = false
drewNote = false
}
debugLabel.text = "pressed: \(pressed), f: \(touch.force)"
}
}
else {
// Fallback on earlier versions
}
super.touchesMoved(touches, withEvent: event)
}
var debugLabel: UILabel!
var pressed = false
var drewNote = false
}
class ScoreGestures {
var scoreLineView: ScoreLineView!
var editButton: ScoreEditButton!
init(scoreLineView: ScoreLineView, editButton: ScoreEditButton) {
self.scoreLineView = scoreLineView
self.editButton = editButton
let pan = PanPressGestureRecognizer(target: self, action: #selector(ScoreGestures.panEvent(_:)))
pan.debugLabel = scoreLineView.debugLabel
editButton.addGestureRecognizer(pan)
editButton.addTarget(self, action: #selector(ScoreGestures.touchDownEvent(_:)), forControlEvents: UIControlEvents.TouchDown)
editButton.addTarget(self, action: #selector(ScoreGestures.touchUpEvent(_:)), forControlEvents: UIControlEvents.TouchUpInside)
editButton.addTarget(self, action: #selector(ScoreGestures.touchUpEvent(_:)), forControlEvents: UIControlEvents.TouchUpOutside)
}
var panInitial: CGPoint!
var panPositionMode = true
var panLastChangeX: CGFloat!
var panLastChangeY: CGFloat!
var panAccidental = AccidentalSymbol.NATURAL
var panClef = ClefSymbol.G
var panKeySignature = KeySignature.NATURAL
var panNoteLine = 6
var cancelNote = false
var drewNoteWithPress = false
var deletePosition = false
let lowestPossibleLine = -2
let lineWhichMeansDeletePosition = 14
@objc func touchDownEvent(sender: UIButton) {
scoreLineView.showCursor = true
}
@objc func touchUpEvent(sender: UIButton) {
scoreLineView.showCursor = false
}
@objc func panEvent(sender: PanPressGestureRecognizer) {
let point = sender.translationInView(nil)
switch sender.state {
case .Began:
panInitial = point
panPositionMode = true
panLastChangeX = point.x
panLastChangeY = point.y
cancelNote = false
drewNoteWithPress = false
case .Changed:
if panPositionMode {
if point.y > panInitial.y + 20 || point.y < panInitial.y - 20 {
panPositionMode = false
panInitial = point
panLastChangeX = point.x
panLastChangeY = point.y
panNoteLine = 6
panAccidental = scoreLineView.currentAccidentalAtCurrentEditPositionForLine(panNoteLine)
panClef = scoreLineView.scoreClef
panKeySignature = scoreLineView.keySignature
}
else {
if point.x > panLastChangeX + 15 {
panLastChangeX = point.x
panLastChangeY = point.y
scoreLineView.nextPosition()
}
else if point.x < panLastChangeX - 15 {
panLastChangeX = point.x
panLastChangeY = point.y
scoreLineView.previousPosition()
}
}
}
else {
if scoreLineView.editClef || scoreLineView.editKeySignature {
if point.y > panLastChangeY + 15 {
panLastChangeY = point.y
if scoreLineView.editClef {
panClef = panClef.next
}
else {
panKeySignature = panKeySignature.next
}
}
else if point.y < panLastChangeY - 15 {
panLastChangeY = point.y
if scoreLineView.editClef {
panClef = panClef.previous
}
else {
panKeySignature = panKeySignature.previous
}
}
if scoreLineView.editClef {
scoreLineView.cursorView.cursorEditColor()
scoreLineView.showHoverClefOnCursor(panClef)
}
else {
scoreLineView.cursorView.cursorEditColor()
scoreLineView.showHoverKeySignatureOnCursor(panKeySignature)
}
}
else {
if point.x > panLastChangeX + 15 {
panLastChangeY = point.y
panLastChangeX = point.x
if cancelNote == false && panAccidental == .DOUBLE_SHARP {
cancelNote = true
}
else {
panAccidental = panAccidental.next
cancelNote = false
}
}
else if point.x < panLastChangeX - 15 {
panLastChangeY = point.y
panLastChangeX = point.x
if !cancelNote {
panAccidental = panAccidental.previous
}
cancelNote = false
}
if point.y > panLastChangeY + 15 {
panLastChangeY = point.y
panLastChangeX = point.x
if panNoteLine > lowestPossibleLine {
panNoteLine -= 1
deletePosition = false
}
cancelNote = false
panAccidental = scoreLineView.currentAccidentalAtCurrentEditPositionForLine(panNoteLine)
}
else if point.y < panLastChangeY - 15 {
panLastChangeY = point.y
panLastChangeX = point.x
if panNoteLine < lineWhichMeansDeletePosition {
panNoteLine += 1
if panNoteLine == lineWhichMeansDeletePosition {
deletePosition = true
}
else {
deletePosition = false
}
}
cancelNote = false
panAccidental = scoreLineView.currentAccidentalAtCurrentEditPositionForLine(panNoteLine)
}
if sender.pressed && !sender.drewNote && !cancelNote {
scoreLineView.addNoteToPosition(panNoteLine, accidental: panAccidental)
AudioServicesPlaySystemSound(SystemSoundID(1306))
sender.drewNote = true
drewNoteWithPress = true
}
if !deletePosition && !cancelNote {
scoreLineView.cursorView.cursorEditColor()
scoreLineView.showHoverHeadOnCursorOnLine(panNoteLine, drewNoteByPress: sender.drewNote, accidental: panAccidental)
}
else if deletePosition{
scoreLineView.cursorView.cursorDeleteColor()
scoreLineView.hideHoverOnCursor()
}
else if cancelNote {
scoreLineView.cursorView.cursorEditCancelColor()
scoreLineView.hideHoverOnCursor()
}
}
}
case .Ended:
sender.setTranslation(CGPointMake(0.0, 0.0), inView: nil)
scoreLineView.cursorView.cursorEditColor()
scoreLineView.hideHoverOnCursor()
scoreLineView.showCursor = false
if !panPositionMode {
if scoreLineView.editClef {
scoreLineView.scoreClef = panClef
}
else if scoreLineView.editKeySignature {
scoreLineView.keySignature = panKeySignature
}
else {
if panNoteLine == lineWhichMeansDeletePosition {
scoreLineView.removePosition()
}
else if !cancelNote {
if !drewNoteWithPress {
scoreLineView.addNoteToPosition(panNoteLine, accidental: panAccidental)
}
}
}
}
scoreLineView.editKeySignature = false
scoreLineView.editClef = false
deletePosition = false
default:
sender.setTranslation(CGPointMake(0.0, 0.0), inView: nil)
scoreLineView.cursorView.cursorEditColor()
scoreLineView.hideHoverOnCursor()
scoreLineView.showCursor = false
scoreLineView.editKeySignature = false
scoreLineView.editClef = false
}
}
}
|
mit
|
7fb0c4603bb3b9c7c1cd4942b544e7be
| 38.47619 | 139 | 0.501608 | 5.817544 | false | false | false | false |
NextFaze/FazeKit
|
FazeKit/Classes/UIColorAdditions.swift
|
1
|
4439
|
//
// Copyright 2016 NextFaze
//
// 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.
//
// UIColorAdditions.swift
// Pods
//
// Created by Ricardo Santos on 30/11/2016.
//
//
import UIKit
public extension UIColor {
var redInt: Int {
var red: CGFloat = 0
self.getRed(&red, green: nil, blue: nil, alpha: nil)
return Int(red * 255)
}
var greenInt: Int {
var green: CGFloat = 0
self.getRed(nil, green: &green, blue: nil, alpha: nil)
return Int(green * 255)
}
var blueInt: Int {
var blue: CGFloat = 0
self.getRed(nil, green: nil, blue: &blue, alpha: nil)
return Int(blue * 255)
}
var alphaInt: Int {
var alpha: CGFloat = 0
self.getRed(nil, green: nil, blue: nil, alpha: &alpha)
return Int(alpha * 255)
}
var rgba: (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) {
var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
guard self.getRed(&red, green: &green, blue: &blue, alpha: &alpha) else { return (0, 0, 0, 0) }
return (red, green, blue, alpha)
}
var rgbaInt: (r: Int, g: Int, b: Int, a: Int) {
var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
guard self.getRed(&red, green: &green, blue: &blue, alpha: &alpha) else { return (0, 0, 0, 0) }
return (Int(red * 255), Int(green * 255), Int(blue * 255), Int(alpha * 255))
}
convenience init(redInt: Int, greenInt: Int, blueInt: Int, alpha: CGFloat) {
self.init(red: CGFloat(redInt)/255.0, green: CGFloat(greenInt)/255.0, blue: CGFloat(blueInt)/255.0, alpha: alpha)
}
// adapted from: https://gist.github.com/arshad/de147c42d7b3063ef7bc
convenience init(hexString: String, alpha: Double = 1.0) {
let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
var int = UInt32()
Scanner(string: hex).scanHexInt32(&int)
let r, g, b: UInt32
switch hex.count {
case 3: // RGB (12-bit)
(r, g, b) = ((int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6: // RGB (24-bit)
(r, g, b) = (int >> 16, int >> 8 & 0xFF, int & 0xFF)
default:
(r, g, b) = (1, 1, 0)
}
self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(255 * alpha) / 255)
}
var hexStringRGB: String {
let rgbaInt = self.rgbaInt
return String(format: "%02x%02x%02x", rgbaInt.r, rgbaInt.g, rgbaInt.b)
}
var hexStringARGB: String {
let rgbaInt = self.rgbaInt
return String(format: "%02x%02x%02x%02x", rgbaInt.a, rgbaInt.r, rgbaInt.g, rgbaInt.b)
}
var htmlStringRGB: String {
return "#" + self.hexStringRGB
}
var htmlStringARGB: String {
return "#" + self.hexStringARGB
}
convenience init(source: String, minBrightness: CGFloat = 0.66, maxBrightness: CGFloat = 1.0) {
guard !source.isEmpty, let md5 = source.md5() else {
self.init(red: 0, green: 0, blue: 0, alpha: 1)
return
}
self.init(md5: md5, minBrightness: minBrightness, maxBrightness: maxBrightness)
}
convenience init(md5: String, minBrightness: CGFloat = 0.66, maxBrightness: CGFloat = 1.0) {
let mid = md5.index(md5.startIndex, offsetBy: md5.count / 2)
let firstHalf = md5[md5.startIndex..<mid]
let secondHalf = md5[mid..<md5.endIndex]
let firstHash = abs(firstHalf.hashValue % 100)
let secondHash = abs(secondHalf.hashValue % 100)
let hue = CGFloat(firstHash) / 100.0
let brightness: CGFloat = minBrightness + (maxBrightness - minBrightness) * CGFloat(secondHash) / 100.0
self.init(hue: hue, saturation: 0.8, brightness: brightness, alpha: 1.0)
}
}
|
apache-2.0
|
c6fa88b7b3089c429599926d130ba3e1
| 36.302521 | 124 | 0.599009 | 3.462559 | false | false | false | false |
kickstarter/ios-oss
|
Library/ViewModels/PledgeViewModel.swift
|
1
|
50086
|
import Foundation
import KsApi
import PassKit
import Prelude
import ReactiveSwift
public struct PaymentSourceSelected: Equatable {
let paymentSourceId: String
let isSetupIntentClientSecret: Bool
}
public typealias StripeConfigurationData = (merchantIdentifier: String, publishableKey: String)
public typealias CreateBackingData = (
project: Project,
rewards: [Reward],
pledgeTotal: Double,
selectedQuantities: SelectedRewardQuantities,
shippingRule: ShippingRule?,
paymentSourceId: String?,
setupIntentClientSecret: String?,
applePayParams: ApplePayParams?,
refTag: RefTag?
)
public typealias UpdateBackingData = (
backing: Backing,
rewards: [Reward],
pledgeTotal: Double,
selectedQuantities: SelectedRewardQuantities,
shippingRule: ShippingRule?,
paymentSourceId: String?,
setupIntentClientSecret: String?,
applePayParams: ApplePayParams?
)
public typealias PaymentAuthorizationData = (
project: Project,
reward: Reward,
allRewardsTotal: Double,
additionalPledgeAmount: Double,
allRewardsShippingTotal: Double,
merchantIdentifier: String
)
public typealias PKPaymentData = (displayName: String, network: String, transactionIdentifier: String)
public struct PledgeViewData: Equatable {
public let project: Project
public let rewards: [Reward]
public let selectedQuantities: SelectedRewardQuantities
public let selectedLocationId: Int?
public let refTag: RefTag?
public let context: PledgeViewContext
}
public protocol PledgeViewModelInputs {
func applePayButtonTapped()
func configure(with data: PledgeViewData)
func creditCardSelected(with paymentSourceData: PaymentSourceSelected)
func goToLoginSignupTapped()
func paymentAuthorizationDidAuthorizePayment(
paymentData: (displayName: String?, network: String?, transactionIdentifier: String)
)
func paymentAuthorizationViewControllerDidFinish()
func pledgeAmountViewControllerDidUpdate(with data: PledgeAmountData)
func pledgeDisclaimerViewDidTapLearnMore()
func riskMessagingViewControllerDismissed(isApplePay: Bool)
func scaFlowCompleted(with result: StripePaymentHandlerActionStatusType, error: Error?)
func shippingRuleSelected(_ shippingRule: ShippingRule)
func stripeTokenCreated(token: String?, error: Error?) -> PKPaymentAuthorizationStatus
func submitButtonTapped()
func termsOfUseTapped(with: HelpType)
func userSessionStarted()
func viewDidLoad()
}
public protocol PledgeViewModelOutputs {
var beginSCAFlowWithClientSecret: Signal<String, Never> { get }
var configureExpandableRewardsHeaderWithData: Signal<PledgeExpandableRewardsHeaderViewData, Never> { get }
var configureLocalPickupViewWithData: Signal<PledgeLocalPickupViewData, Never> { get }
var configurePaymentMethodsViewControllerWithValue: Signal<PledgePaymentMethodsValue, Never> { get }
var configurePledgeAmountViewWithData: Signal<PledgeAmountViewConfigData, Never> { get }
var configurePledgeAmountSummaryViewControllerWithData: Signal<PledgeAmountSummaryViewData, Never> { get }
var configurePledgeViewCTAContainerView: Signal<PledgeViewCTAContainerViewData, Never> { get }
var configureShippingLocationViewWithData: Signal<PledgeShippingLocationViewData, Never> { get }
var configureShippingSummaryViewWithData: Signal<PledgeShippingSummaryViewData, Never> { get }
var configureStripeIntegration: Signal<StripeConfigurationData, Never> { get }
var configureSummaryViewControllerWithData: Signal<PledgeSummaryViewData, Never> { get }
var descriptionSectionSeparatorHidden: Signal<Bool, Never> { get }
var expandableRewardsHeaderViewHidden: Signal<Bool, Never> { get }
var goToApplePayPaymentAuthorization: Signal<PaymentAuthorizationData, Never> { get }
var goToRiskMessagingModal: Signal<Bool, Never> { get }
var goToThanks: Signal<ThanksPageData, Never> { get }
var goToLoginSignup: Signal<(LoginIntent, Project, Reward), Never> { get }
var localPickupViewHidden: Signal<Bool, Never> { get }
var notifyDelegateUpdatePledgeDidSucceedWithMessage: Signal<String, Never> { get }
var notifyPledgeAmountViewControllerUnavailableAmountChanged: Signal<Double, Never> { get }
var paymentMethodsViewHidden: Signal<Bool, Never> { get }
var pledgeAmountViewHidden: Signal<Bool, Never> { get }
var pledgeAmountSummaryViewHidden: Signal<Bool, Never> { get }
var popToRootViewController: Signal<(), Never> { get }
var processingViewIsHidden: Signal<Bool, Never> { get }
var projectTitle: Signal<String, Never> { get }
var projectTitleLabelHidden: Signal<Bool, Never> { get }
var shippingLocationViewHidden: Signal<Bool, Never> { get }
var shippingSummaryViewHidden: Signal<Bool, Never> { get }
var showApplePayAlert: Signal<(String, String), Never> { get }
var showErrorBannerWithMessage: Signal<String, Never> { get }
var showWebHelp: Signal<HelpType, Never> { get }
var summarySectionSeparatorHidden: Signal<Bool, Never> { get }
var rootStackViewLayoutMargins: Signal<UIEdgeInsets, Never> { get }
var title: Signal<String, Never> { get }
}
public protocol PledgeViewModelType {
var inputs: PledgeViewModelInputs { get }
var outputs: PledgeViewModelOutputs { get }
}
public class PledgeViewModel: PledgeViewModelType, PledgeViewModelInputs, PledgeViewModelOutputs {
public init() {
let initialData = Signal.combineLatest(
self.configureWithDataProperty.signal,
self.viewDidLoadProperty.signal
)
.map(first)
.skipNil()
let project = initialData.map(\.project)
let baseReward = initialData.map(\.rewards).map(\.first).skipNil()
let rewards = initialData.map(\.rewards)
let selectedQuantities = initialData.map(\.selectedQuantities)
let selectedLocationId = initialData.map(\.selectedLocationId)
let refTag = initialData.map(\.refTag)
let context = initialData.map(\.context)
let initialDataUnpacked = Signal.zip(project, baseReward, refTag, context)
let backing = project.map { $0.personalization.backing }.skipNil()
self.projectTitleLabelHidden = context
.zip(with: baseReward)
.map { context, reward in context.descriptionViewHidden || reward.isNoReward == false }
self.pledgeAmountViewHidden = context.map { $0.pledgeAmountViewHidden }
self.summarySectionSeparatorHidden = self.pledgeAmountViewHidden
self.pledgeAmountSummaryViewHidden = Signal.zip(baseReward, context).map { baseReward, context in
(baseReward.isNoReward && context == .update) || context.pledgeAmountSummaryViewHidden
}
self.descriptionSectionSeparatorHidden = Signal.combineLatest(context, baseReward)
.map { context, reward in
if context.isAny(of: .pledge, .updateReward) {
return reward.isNoReward == false
}
return context.sectionSeparatorsHidden
}
let isLoggedIn = Signal.merge(initialData.ignoreValues(), self.userSessionStartedSignal)
.map { _ in AppEnvironment.current.currentUser }
.map(isNotNil)
let selectedShippingRule = Signal.merge(
project.mapConst(nil),
self.shippingRuleSelectedSignal.wrapInOptional()
)
let allRewardsTotal = Signal.combineLatest(
rewards,
selectedQuantities
)
.map(calculateAllRewardsTotal)
let calculatedShippingTotal = Signal.combineLatest(
selectedShippingRule.skipNil(),
rewards,
selectedQuantities
)
.map(calculateShippingTotal)
let baseRewardShippingTotal = Signal.zip(project, baseReward, selectedShippingRule)
.map(getBaseRewardShippingTotal)
let allRewardsShippingTotal = Signal.merge(
baseRewardShippingTotal,
calculatedShippingTotal
)
// Initial pledge amount is zero if not backed.
let initialAdditionalPledgeAmount = Signal.merge(
initialData.filter { $0.project.personalization.backing == nil }.mapConst(0.0),
backing.map(\.bonusAmount)
)
.take(first: 1)
let additionalPledgeAmount = Signal.merge(
self.pledgeAmountDataSignal.map { $0.amount },
initialAdditionalPledgeAmount
)
self.notifyPledgeAmountViewControllerUnavailableAmountChanged = Signal.combineLatest(
allRewardsTotal,
allRewardsShippingTotal
)
.map { $0.addingCurrency($1) }
let projectAndReward = Signal.zip(project, baseReward)
/**
Shipping location selector is hidden if the context hides it,
if the base reward has no shipping, when add-ons were selected or when base reward has local pickup option.
*/
let nonLocalPickupShippingLocationViewHidden = Signal.combineLatest(baseReward, rewards, context)
.map { baseReward, rewards, context in
[
context.shippingLocationViewHidden,
!baseReward.shipping.enabled,
rewards.count > 1
].contains(true)
}
self.shippingLocationViewHidden = Signal
.combineLatest(nonLocalPickupShippingLocationViewHidden, baseReward)
.map { flag, baseReward in
isRewardLocalPickup(baseReward) ? true : flag
}
/**
Shipping summary view is hidden when updating,
if the base reward has no shipping, when NO add-ons were selected or when base reward has local pickup option.
*/
let nonLocalPickupShippingSummaryViewHidden = Signal.combineLatest(baseReward, rewards, context)
.map { baseReward, rewards, context in
[
context.isAny(of: .update, .changePaymentMethod, .fixPaymentMethod),
!baseReward.shipping.enabled,
rewards.count == 1
].contains(true)
}
self.shippingSummaryViewHidden = Signal.combineLatest(nonLocalPickupShippingSummaryViewHidden, baseReward)
.map { flag, baseReward in
isRewardLocalPickup(baseReward) ? true : flag
}
let shippingViewsHidden = Signal.combineLatest(
self.shippingSummaryViewHidden,
self.shippingLocationViewHidden
)
.map { a, b -> Bool in
let r = a && b
return r
}
let shippingViewsHiddenConditionsForPledgeAmountSummary = Signal
.combineLatest(
nonLocalPickupShippingLocationViewHidden,
nonLocalPickupShippingSummaryViewHidden
)
.map { a, b -> Bool in
let r = a && b
return r
}
self.localPickupViewHidden = baseReward.map(isRewardLocalPickup).negate()
// Only shown for regular non-add-ons based rewards
self.configureShippingLocationViewWithData = Signal.combineLatest(
projectAndReward,
shippingViewsHidden.filter(isFalse),
selectedLocationId
)
.map { projectAndReward, _, selectedLocationId in
(projectAndReward.0, projectAndReward.1, selectedLocationId)
}
.map { project, reward, locationId in
(project, reward, true, locationId)
}
// Only shown for add-ons based rewards
self.configureShippingSummaryViewWithData = Signal.combineLatest(
selectedShippingRule.skipNil().map(\.location.localizedName),
project.map(\.stats.omitUSCurrencyCode),
project.map { project in
projectCountry(forCurrency: project.stats.currency) ?? project.country
},
allRewardsShippingTotal
)
.map(PledgeShippingSummaryViewData.init)
self.configurePledgeAmountViewWithData = Signal.combineLatest(
projectAndReward,
initialAdditionalPledgeAmount
)
.map(unpack)
.map { project, reward, additionalPledgeAmount in
(
project,
reward,
additionalPledgeAmount
)
}
// Only shown for if the shipping summary view and shipping location view are hidden
self.configureLocalPickupViewWithData = Signal.combineLatest(
projectAndReward,
shippingViewsHidden.filter(isTrue)
)
.switchMap { projectAndReward, _ -> SignalProducer<PledgeLocalPickupViewData?, Never> in
guard let locationName = projectAndReward.1.localPickup?.displayableName else {
return SignalProducer(value: nil)
}
let localPickupLocationData = PledgeLocalPickupViewData(locationName: locationName)
return SignalProducer(value: localPickupLocationData)
}
.skipNil()
/**
* The total pledge amount that will be used to create the backing.
* For a regular reward this includes the bonus support amount,
* the total of all rewards and their respective shipping costs.
* For No Reward this is only the pledge amount.
*/
let calculatedPledgeTotal = Signal.combineLatest(
additionalPledgeAmount,
allRewardsShippingTotal,
allRewardsTotal
)
.map(calculatePledgeTotal)
let pledgeTotal = Signal.merge(
backing.map(\.amount),
calculatedPledgeTotal
)
let projectAndConfirmationLabelHidden = Signal.combineLatest(
project,
context.map { $0.confirmationLabelHidden }
)
self.configureSummaryViewControllerWithData = Signal.combineLatest(
projectAndConfirmationLabelHidden,
pledgeTotal
)
.map(unpack)
.map { project, confirmationLabelHidden, total in (project, total, confirmationLabelHidden) }
.map(pledgeSummaryViewData)
self.configurePledgeAmountSummaryViewControllerWithData = Signal.combineLatest(
projectAndReward,
allRewardsTotal,
additionalPledgeAmount,
shippingViewsHiddenConditionsForPledgeAmountSummary,
context
)
.map { projectAndReward, allRewardsTotal, amount, shippingViewsHidden, context in
(projectAndReward.0, projectAndReward.1, allRewardsTotal, amount, shippingViewsHidden, context)
}
.map(pledgeAmountSummaryViewData)
.skipNil()
let configurePaymentMethodsViewController = Signal.merge(
initialDataUnpacked,
initialDataUnpacked.takeWhen(self.userSessionStartedSignal)
)
self.configurePaymentMethodsViewControllerWithValue = configurePaymentMethodsViewController
.filter { !$3.paymentMethodsViewHidden }
.compactMap { project, reward, refTag, context -> PledgePaymentMethodsValue? in
guard let user = AppEnvironment.current.currentUser else { return nil }
return (user, project, reward, context, refTag)
}
self.goToLoginSignup = Signal.combineLatest(project, baseReward, self.goToLoginSignupSignal)
.map { (LoginIntent.backProject, $0.0, $0.1) }
self.paymentMethodsViewHidden = Signal.combineLatest(isLoggedIn, context)
.map { !$0 || $1.paymentMethodsViewHidden }
let pledgeAmountIsValid = self.pledgeAmountDataSignal
.map { $0.isValid }
self.configureStripeIntegration = Signal.combineLatest(
initialData,
context
)
.filter { !$1.paymentMethodsViewHidden }
.ignoreValues()
.map { _ in
(
Secrets.ApplePay.merchantIdentifier,
AppEnvironment.current.environmentType.stripePublishableKey
)
}
/// The `selectedPaymentSourceId` will do as it did before taking the payment source id (A) or the setup intent client secret (B), one or the other for comparison against the existing backing payment source id. It does not care which of two payment sources the id refers to.
let selectedPaymentSourceId = Signal.merge(
initialData.mapConst(nil),
self.creditCardSelectedSignal.map { $0.paymentSourceId }.wrapInOptional()
)
/// The `selectedPaymentSourceIdOrSetupIntentClientSecret` will take the payment source id (A) or the setup intent client secret (B) and map only to `createBackingData` or `updateBackingData`
let selectedPaymentSourceIdOrSetupIntentClientSecret = Signal.merge(
initialData.mapConst(nil),
self.creditCardSelectedSignal.wrapInOptional()
)
self.showWebHelp = Signal.merge(
self.termsOfUseTappedSignal,
self.pledgeDisclaimerViewDidTapLearnMoreSignal.mapConst(.trust)
)
// MARK: - Apple Pay
let applePayButtonTappedAndIsChangingPaymentMethod = self.applePayButtonTappedSignal
.filter { _ in !isNativeRiskMessagingControlEnabled() }
.combineLatest(with: context)
.map(second)
.filter { $0 == .changePaymentMethod }
.ignoreValues()
// If the Optimizely risk messaging experiment is set to the control AND the Pay With Apple button is tapped
// Or if the Optimizely risk messaging experiment is set to the variant, and we are changing the payment method to Pay With Apple
// Or if the Optimizely risk messaging experiment is set to the variant and it is dismissed, this emits
let applePayButtonTappedOrRiskMessagingModalDismissed = Signal.merge(
self.applePayButtonTappedSignal.filter(isNativeRiskMessagingControlEnabled),
applePayButtonTappedAndIsChangingPaymentMethod,
self.riskMessagingViewControllerDismissedProperty.signal.skipNil().filter(isTrue).ignoreValues()
)
let paymentAuthorizationData = Signal.combineLatest(
project,
baseReward,
allRewardsTotal,
additionalPledgeAmount,
allRewardsShippingTotal
)
.map { project, reward, allRewardsTotal, additionalPledgeAmount, allRewardsShippingTotal -> PaymentAuthorizationData in
let r = (
project,
reward,
allRewardsTotal,
additionalPledgeAmount,
allRewardsShippingTotal,
Secrets.ApplePay.merchantIdentifier
) as PaymentAuthorizationData
return r
}
let goToApplePayPaymentAuthorization = pledgeAmountIsValid
.takeWhen(applePayButtonTappedOrRiskMessagingModalDismissed)
.filter(isTrue)
let showApplePayAlert = pledgeAmountIsValid
.takeWhen(applePayButtonTappedOrRiskMessagingModalDismissed)
.filter(isFalse)
self.goToApplePayPaymentAuthorization = paymentAuthorizationData
.takeWhen(goToApplePayPaymentAuthorization)
let pkPaymentData = self.pkPaymentSignal
.map { pkPayment -> PKPaymentData? in
guard let displayName = pkPayment.displayName, let network = pkPayment.network else {
return nil
}
return (displayName, network, pkPayment.transactionIdentifier)
}
// MARK: - Create Apple Pay Backing
let applePayStatusSuccess = Signal.combineLatest(
self.stripeTokenSignal.skipNil(),
self.stripeErrorSignal.filter(isNil),
pkPaymentData.skipNil()
)
.mapConst(PKPaymentAuthorizationStatus.success)
let applePayStatusFailure = Signal.merge(
self.stripeErrorSignal.skipNil().ignoreValues(),
self.stripeTokenSignal.filter(isNil).ignoreValues(),
pkPaymentData.filter(isNil).ignoreValues()
)
.mapConst(PKPaymentAuthorizationStatus.failure)
self.createApplePayBackingStatusProperty <~ Signal.merge(
applePayStatusSuccess,
applePayStatusFailure
)
let willCreateApplePayBacking = Signal.combineLatest(
applePayStatusSuccess,
context
)
.map { $1.isCreating }
.filter(isTrue)
// MARK: - Update Apple Pay Backing
let applePayParams = Signal.combineLatest(
pkPaymentData.skipNil(),
self.stripeTokenSignal.skipNil()
)
.map { paymentData, token in
(
paymentData.displayName,
paymentData.network,
paymentData.transactionIdentifier,
token
)
}
.map(ApplePayParams.init)
let applePayParamsData = Signal.merge(
initialData.mapConst(nil),
applePayParams.wrapInOptional()
)
// MARK: - Risk Messaging Modal
// If a pledge is being updated and the variant is returning from the experiment, this emits (self.riskMessagingViewControllerDismissedProperty never does)
let submitButtonTappedAndIsUpdating = self.submitButtonTappedSignal
.combineLatest(with: context)
.filter { _, context in
context.isUpdating && !isNativeRiskMessagingControlEnabled()
}
.ignoreValues()
// If the Optimizely risk messaging experiment is set to the control AND the Pledge button is tapped
// Or if the Optimizely risk messaging experiment is set to the variant and it is dismissed, this emits
let submitButtonTappedOrRiskMessagingModalDismissed = Signal.merge(
self.submitButtonTappedSignal.filter(isNativeRiskMessagingControlEnabled),
self.riskMessagingViewControllerDismissedProperty.signal.skipNil().filter(isFalse).ignoreValues(),
submitButtonTappedAndIsUpdating
)
// The mapConst Bool value here represents whether this is Pay With Apple (true) or Pledge (false)
// We only want to present risk messaging when a backing is created, NOT updated
self.goToRiskMessagingModal = Signal.merge(
self.submitButtonTappedSignal.mapConst(false),
self.applePayButtonTappedSignal.mapConst(true)
)
.combineLatest(with: context)
.filter { _, context in
context.isCreating && !isNativeRiskMessagingControlEnabled()
}
.map(first)
// MARK: - Create Backing
let createBackingData = Signal.combineLatest(
project,
rewards,
pledgeTotal,
selectedQuantities,
selectedShippingRule,
selectedPaymentSourceIdOrSetupIntentClientSecret,
applePayParamsData,
refTag
)
.map { (
project,
rewards,
pledgeTotal,
selectedQuantities,
selectedShippingRule,
selectedPaymentSourceIdOrSetupIntentClientSecret,
applePayParams,
refTag
) -> CreateBackingData in
var paymentSourceId: String?
var setupIntentClientSecret: String?
if let isSetupIntentClientSecretAvailable = selectedPaymentSourceIdOrSetupIntentClientSecret {
paymentSourceId = isSetupIntentClientSecretAvailable
.isSetupIntentClientSecret ? nil : isSetupIntentClientSecretAvailable.paymentSourceId
setupIntentClientSecret = isSetupIntentClientSecretAvailable
.isSetupIntentClientSecret ? isSetupIntentClientSecretAvailable.paymentSourceId : nil
}
return (
project: project,
rewards: rewards,
pledgeTotal: pledgeTotal,
selectedQuantities: selectedQuantities,
shippingRule: selectedShippingRule,
paymentSourceId: paymentSourceId,
setupIntentClientSecret: setupIntentClientSecret,
applePayParams: applePayParams,
refTag: refTag
)
}
let createButtonTapped = Signal.combineLatest(
submitButtonTappedOrRiskMessagingModalDismissed,
context
)
.filter { _, context in context.isCreating }
.ignoreValues()
let createBackingDataAndIsApplePay = createBackingData.takePairWhen(
Signal.merge(
createButtonTapped.mapConst(false),
willCreateApplePayBacking
)
)
// Captures the checkoutId immediately and avoids a race condition further down the chain.
let checkoutIdProperty = MutableProperty<Int?>(nil)
let processingViewIsHidden = MutableProperty<Bool>(true)
let createBackingEvents = createBackingDataAndIsApplePay
.map(CreateBackingInput.input(from:isApplePay:))
.switchMap { [checkoutIdProperty] input in
AppEnvironment.current.apiService.createBacking(input: input)
.ksr_delay(AppEnvironment.current.apiDelayInterval, on: AppEnvironment.current.scheduler)
.on(
starting: {
processingViewIsHidden.value = false
},
terminated: {
processingViewIsHidden.value = true
}
)
.map { envelope -> StripeSCARequiring in
checkoutIdProperty.value = decompose(id: envelope.createBacking.checkout.id)
return envelope as StripeSCARequiring
}
.materialize()
}
// MARK: - Update Backing
let updateBackingData = Signal.combineLatest(
backing,
rewards,
pledgeTotal,
selectedQuantities,
selectedShippingRule,
selectedPaymentSourceIdOrSetupIntentClientSecret,
applePayParamsData
)
.map { (
backing,
rewards,
pledgeTotal,
selectedQuantities,
selectedShippingRule,
selectedPaymentSourceIdOrSetupIntentClientSecret,
applePayParams
) -> UpdateBackingData in
var paymentSourceId: String?
var setupIntentClientSecret: String?
if let isSetupIntentClientSecretAvailable = selectedPaymentSourceIdOrSetupIntentClientSecret {
paymentSourceId = isSetupIntentClientSecretAvailable
.isSetupIntentClientSecret ? nil : isSetupIntentClientSecretAvailable.paymentSourceId
setupIntentClientSecret = isSetupIntentClientSecretAvailable
.isSetupIntentClientSecret ? isSetupIntentClientSecretAvailable.paymentSourceId : nil
}
return (
backing: backing,
rewards: rewards,
pledgeTotal: pledgeTotal,
selectedQuantities: selectedQuantities,
shippingRule: selectedShippingRule,
paymentSourceId: paymentSourceId,
setupIntentClientSecret: setupIntentClientSecret,
applePayParams: applePayParams
)
}
let willUpdateApplePayBacking = Signal.combineLatest(
applePayStatusSuccess,
context
)
.map { $1.isUpdating }
.filter(isTrue)
let updateButtonTapped = Signal.combineLatest(
submitButtonTappedOrRiskMessagingModalDismissed,
context
)
.filter { _, context in context.isUpdating }
.ignoreValues()
let updateBackingDataAndIsApplePay = updateBackingData.takePairWhen(
Signal.merge(
updateButtonTapped.mapConst(false),
willUpdateApplePayBacking
)
)
let updateBackingEvents = updateBackingDataAndIsApplePay
.map(UpdateBackingInput.input(from:isApplePay:))
.switchMap { input in
AppEnvironment.current.apiService.updateBacking(input: input)
.ksr_delay(AppEnvironment.current.apiDelayInterval, on: AppEnvironment.current.scheduler)
.on(
starting: {
processingViewIsHidden.value = false
},
terminated: {
processingViewIsHidden.value = true
}
)
.map { $0 as StripeSCARequiring }
.materialize()
}
let createOrUpdateEvent = Signal.merge(
createBackingEvents,
updateBackingEvents
)
self.processingViewIsHidden = processingViewIsHidden.signal
// MARK: - Form Validation
let amountChangedAndValid = Signal.combineLatest(
project,
baseReward,
self.pledgeAmountDataSignal,
initialAdditionalPledgeAmount,
context
)
.map(amountValid)
let shippingRuleChangedAndValid = Signal.combineLatest(
project,
baseReward,
selectedShippingRule,
context
)
.map(shippingRuleValid)
self.showApplePayAlert = Signal.combineLatest(
project,
self.pledgeAmountDataSignal
)
.takeWhen(showApplePayAlert)
.map { project, pledgeAmountData in (project, pledgeAmountData.min, pledgeAmountData.max) }
.map { project, min, max in
(
Strings.Almost_there(),
Strings.Please_enter_a_pledge_amount_between_min_and_max(
min: Format
.currency(
min,
country: projectCountry(forCurrency: project.stats.currency) ?? project.country,
omitCurrencyCode: false
),
max: Format
.currency(
max,
country: projectCountry(forCurrency: project.stats.currency) ?? project.country,
omitCurrencyCode: false
)
)
)
}
let notChangingPaymentMethod = context.map { context in
context.isUpdating && context != .changePaymentMethod
}
.filter(isTrue)
/// The `paymentMethodChangedAndValid` will do as it before taking the payment source id (A) or the setup intent client secret (B), one or the other for comparison against the existing backing payment source id. It does not care which of two payment sources the id refers to.
let paymentMethodChangedAndValid = Signal.merge(
notChangingPaymentMethod.mapConst(false),
Signal.combineLatest(
project,
baseReward,
self.creditCardSelectedSignal.map { $0.paymentSourceId },
context
)
.map(paymentMethodValid)
)
let valuesChangedAndValid = Signal.combineLatest(
amountChangedAndValid,
shippingRuleChangedAndValid,
paymentMethodChangedAndValid,
context
)
.map(allValuesChangedAndValid)
let isEnabled = Signal.merge(
self.viewDidLoadProperty.signal.mapConst(false)
.take(until: valuesChangedAndValid.ignoreValues()),
valuesChangedAndValid,
submitButtonTappedOrRiskMessagingModalDismissed.mapConst(false),
createOrUpdateEvent.filter { $0.isTerminating }.mapConst(true)
)
.skipRepeats()
let isCreateOrUpdateBacking = Signal.merge(
submitButtonTappedOrRiskMessagingModalDismissed.mapConst(true),
Signal.merge(willUpdateApplePayBacking, willCreateApplePayBacking).mapConst(false)
)
// MARK: - Success/Failure
let scaFlowCompletedWithError = self.scaFlowCompletedWithResultSignal
.filter { $0.0.status == .failed }
.map(second)
.skipNil()
let scaFlowCompletedWithSuccess = self.scaFlowCompletedWithResultSignal
.filter { $0.0.status == .succeeded }
.map(first)
.ignoreValues()
let didInitiateApplePayBacking = Signal.merge(
willCreateApplePayBacking,
willUpdateApplePayBacking
)
let paymentAuthorizationDidFinish = didInitiateApplePayBacking
.takeWhen(self.paymentAuthorizationDidFinishSignal)
let createOrUpdateApplePayBackingCompleted = Signal.zip(
didInitiateApplePayBacking,
createOrUpdateEvent.filter { $0.isTerminating }.ignoreValues(),
paymentAuthorizationDidFinish
)
let valuesOrNil = Signal.merge(
createOrUpdateEvent.values().wrapInOptional(),
isCreateOrUpdateBacking.mapConst(nil)
)
let createOrUpdateBackingEventValuesNoSCA = valuesOrNil
.skipNil()
.filter(requiresSCA >>> isFalse)
let createOrUpdateBackingDidCompleteNoSCA = isCreateOrUpdateBacking
.takeWhen(createOrUpdateBackingEventValuesNoSCA)
.filter(isTrue)
.ignoreValues()
let createOrUpdateBackingEventValuesRequiresSCA = valuesOrNil
.skipNil()
.filter(requiresSCA)
self.beginSCAFlowWithClientSecret = createOrUpdateBackingEventValuesRequiresSCA
.map { $0.clientSecret }
.skipNil()
let didCompleteApplePayBacking = valuesOrNil
.takeWhen(createOrUpdateApplePayBackingCompleted)
.skipNil()
let creatingContext = context.filter { $0.isCreating }
let createBackingCompletionEvents = Signal.merge(
didCompleteApplePayBacking.combineLatest(with: willCreateApplePayBacking).ignoreValues(),
createOrUpdateBackingDidCompleteNoSCA.combineLatest(with: creatingContext).ignoreValues(),
scaFlowCompletedWithSuccess.combineLatest(with: creatingContext).ignoreValues()
)
let thanksPageData = Signal.combineLatest(
createBackingDataAndIsApplePay,
checkoutIdProperty.signal,
baseReward,
additionalPledgeAmount,
allRewardsShippingTotal
)
.map { dataAndIsApplePay, checkoutId, baseReward, additionalPledgeAmount, allRewardsShippingTotal
-> (CreateBackingData, Bool, String?, Reward, Double, Double) in
let (data, isApplePay) = dataAndIsApplePay
guard let checkoutId = checkoutId else {
return (data, isApplePay, nil, baseReward, additionalPledgeAmount, allRewardsShippingTotal)
}
return (
data,
isApplePay,
String(checkoutId),
baseReward,
additionalPledgeAmount,
allRewardsShippingTotal
)
}
.map { data, isApplePay, checkoutId, baseReward, additionalPledgeAmount, allRewardsShippingTotal
-> ThanksPageData? in
let checkoutPropsData = checkoutProperties(
from: data.project,
baseReward: baseReward,
addOnRewards: data.rewards,
selectedQuantities: data.selectedQuantities,
additionalPledgeAmount: additionalPledgeAmount,
pledgeTotal: data.pledgeTotal,
shippingTotal: allRewardsShippingTotal,
checkoutId: checkoutId,
isApplePay: isApplePay
)
return (data.project, baseReward, checkoutPropsData)
}
.skipNil()
self.goToThanks = thanksPageData
.takeWhen(createBackingCompletionEvents)
let errorsOrNil = Signal.merge(
createOrUpdateEvent.errors().wrapInOptional(),
isCreateOrUpdateBacking.mapConst(nil)
)
let createOrUpdateApplePayBackingError = createOrUpdateApplePayBackingCompleted
.withLatest(from: errorsOrNil)
.map(second)
.skipNil()
let createOrUpdateBackingError = isCreateOrUpdateBacking
.takePairWhen(errorsOrNil.skipNil())
.filter(first >>> isTrue)
.map(second)
let updatingContext = context.filter { $0.isUpdating }
let updateBackingCompletionEvents = Signal.merge(
didCompleteApplePayBacking.combineLatest(with: willUpdateApplePayBacking).ignoreValues(),
createOrUpdateBackingDidCompleteNoSCA.combineLatest(with: updatingContext).ignoreValues(),
scaFlowCompletedWithSuccess.combineLatest(with: updatingContext).ignoreValues()
)
self.notifyDelegateUpdatePledgeDidSucceedWithMessage = updateBackingCompletionEvents
.mapConst(Strings.Got_it_your_changes_have_been_saved())
let graphErrors = Signal.merge(
createOrUpdateApplePayBackingError,
createOrUpdateBackingError
)
.map { $0.localizedDescription }
let scaErrors = scaFlowCompletedWithError.map { $0.localizedDescription }
self.showErrorBannerWithMessage = Signal.merge(
graphErrors,
scaErrors
)
self.popToRootViewController = self.notifyDelegateUpdatePledgeDidSucceedWithMessage.ignoreValues()
let willRetryPaymentMethod = Signal.combineLatest(
context,
project,
selectedPaymentSourceId
)
.map { context, project, selectedPaymentSourceId -> Bool in
context == .fixPaymentMethod
&& project.personalization.backing?.paymentSource?.id == selectedPaymentSourceId
}
.skipRepeats()
self.configurePledgeViewCTAContainerView = Signal.combineLatest(
isLoggedIn,
isEnabled,
context,
willRetryPaymentMethod
)
.map { $0 as PledgeViewCTAContainerViewData }
self.configureExpandableRewardsHeaderWithData = Signal.zip(
baseReward.map(\.isNoReward).filter(isFalse),
project,
rewards,
selectedQuantities
)
.map { _, project, rewards, selectedQuantities in
guard let projectCurrencyCountry = projectCountry(forCurrency: project.stats.currency) else {
return (rewards, selectedQuantities, project.country, project.stats.omitUSCurrencyCode)
}
return (rewards, selectedQuantities, projectCurrencyCountry, project.stats.omitUSCurrencyCode)
}
.map(PledgeExpandableRewardsHeaderViewData.init)
self.expandableRewardsHeaderViewHidden = Signal.zip(context, baseReward)
.map { context, reward in
if context.isAny(of: .pledge, .updateReward) {
return reward.isNoReward
}
return context.expandableRewardViewHidden
}
self.rootStackViewLayoutMargins = self.expandableRewardsHeaderViewHidden.map { hidden in
hidden ? UIEdgeInsets(topBottom: Styles.grid(3)) : UIEdgeInsets(bottom: Styles.grid(3))
}
self.projectTitle = project.map(\.name)
self.title = context.map { $0.title }
let trackCheckoutPageViewData = Signal.zip(
project,
baseReward,
rewards,
selectedQuantities,
refTag,
initialAdditionalPledgeAmount,
pledgeTotal,
baseRewardShippingTotal,
context
)
// MARK: - Tracking
trackCheckoutPageViewData
.observeValues { project, baseReward, rewards, selectedQuantities, refTag, additionalPledgeAmount, pledgeTotal, shippingTotal, pledgeViewContext in
let checkoutData = checkoutProperties(
from: project,
baseReward: baseReward,
addOnRewards: rewards,
selectedQuantities: selectedQuantities,
additionalPledgeAmount: additionalPledgeAmount,
pledgeTotal: pledgeTotal,
shippingTotal: shippingTotal,
checkoutId: nil,
isApplePay: false
)
AppEnvironment.current.ksrAnalytics.trackCheckoutPaymentPageViewed(
project: project,
reward: baseReward,
pledgeViewContext: pledgeViewContext,
checkoutData: checkoutData,
refTag: refTag
)
}
let pledgeSubmitEventsSignal = Signal.combineLatest(
createBackingData,
baseReward,
additionalPledgeAmount,
allRewardsShippingTotal
)
// Pledge pledge_submit event
pledgeSubmitEventsSignal
.takeWhen(self.submitButtonTappedSignal)
.map { data, baseReward, additionalPledgeAmount, allRewardsShippingTotal in
let checkoutData = checkoutProperties(
from: data.project,
baseReward: baseReward,
addOnRewards: data.rewards,
selectedQuantities: data.selectedQuantities,
additionalPledgeAmount: additionalPledgeAmount,
pledgeTotal: data.pledgeTotal,
shippingTotal: allRewardsShippingTotal,
checkoutId: nil,
isApplePay: false
)
return (data.project, baseReward, data.refTag, checkoutData)
}
.observeValues { project, reward, refTag, checkoutData in
AppEnvironment.current.ksrAnalytics.trackPledgeSubmitButtonClicked(
project: project,
reward: reward,
typeContext: .creditCard,
checkoutData: checkoutData,
refTag: refTag
)
}
// Pay With Apple pledge_submit event
pledgeSubmitEventsSignal
.takeWhen(self.applePayButtonTappedSignal)
.map { data, baseReward, additionalPledgeAmount, allRewardsShippingTotal in
let checkoutData = checkoutProperties(
from: data.project,
baseReward: baseReward,
addOnRewards: data.rewards,
selectedQuantities: data.selectedQuantities,
additionalPledgeAmount: additionalPledgeAmount,
pledgeTotal: data.pledgeTotal,
shippingTotal: allRewardsShippingTotal,
checkoutId: nil,
isApplePay: true
)
return (data.project, baseReward, data.refTag, checkoutData)
}
.observeValues { project, reward, refTag, checkoutData in
AppEnvironment.current.ksrAnalytics.trackPledgeSubmitButtonClicked(
project: project,
reward: reward,
typeContext: .applePay,
checkoutData: checkoutData,
refTag: refTag
)
}
// Risk Messaging Modal pledge_confirm event
pledgeSubmitEventsSignal
.takePairWhen(self.riskMessagingViewControllerDismissedProperty.signal.skipNil())
.map { pledgeSubmitEvent, isApplePay in
let (data, baseReward, additionalPledgeAmount, allRewardsShippingTotal) = pledgeSubmitEvent
let checkoutData = checkoutProperties(
from: data.project,
baseReward: baseReward,
addOnRewards: data.rewards,
selectedQuantities: data.selectedQuantities,
additionalPledgeAmount: additionalPledgeAmount,
pledgeTotal: data.pledgeTotal,
shippingTotal: allRewardsShippingTotal,
checkoutId: nil,
isApplePay: isApplePay
)
return (data.project, baseReward, data.refTag, checkoutData, isApplePay)
}
.observeValues { project, reward, refTag, checkoutData, isApplePay in
AppEnvironment.current.ksrAnalytics.trackPledgeConfirmButtonClicked(
project: project,
reward: reward,
typeContext: isApplePay ? .applePay : .creditCard,
checkoutData: checkoutData,
refTag: refTag
)
}
}
// MARK: - Inputs
private let (applePayButtonTappedSignal, applePayButtonTappedObserver) = Signal<Void, Never>.pipe()
public func applePayButtonTapped() {
self.applePayButtonTappedObserver.send(value: ())
}
private let configureWithDataProperty = MutableProperty<PledgeViewData?>(nil)
public func configure(with data: PledgeViewData) {
self.configureWithDataProperty.value = data
}
private let (creditCardSelectedSignal, creditCardSelectedObserver) = Signal<PaymentSourceSelected, Never>
.pipe()
public func creditCardSelected(with paymentSourceData: PaymentSourceSelected) {
self.creditCardSelectedObserver.send(value: paymentSourceData)
}
private let (pkPaymentSignal, pkPaymentObserver) = Signal<(
displayName: String?,
network: String?,
transactionIdentifier: String
), Never>.pipe()
public func paymentAuthorizationDidAuthorizePayment(paymentData: (
displayName: String?,
network: String?,
transactionIdentifier: String
)) {
self.pkPaymentObserver.send(value: paymentData)
}
private let (paymentAuthorizationDidFinishSignal, paymentAuthorizationDidFinishObserver)
= Signal<Void, Never>.pipe()
public func paymentAuthorizationViewControllerDidFinish() {
self.paymentAuthorizationDidFinishObserver.send(value: ())
}
private let (goToLoginSignupSignal, goToLoginSignupObserver) = Signal<Void, Never>.pipe()
public func goToLoginSignupTapped() {
self.goToLoginSignupObserver.send(value: ())
}
private let (pledgeAmountDataSignal, pledgeAmountObserver) = Signal<PledgeAmountData, Never>.pipe()
public func pledgeAmountViewControllerDidUpdate(with data: PledgeAmountData) {
self.pledgeAmountObserver.send(value: data)
}
private let (pledgeDisclaimerViewDidTapLearnMoreSignal, pledgeDisclaimerViewDidTapLearnMoreObserver)
= Signal<Void, Never>.pipe()
public func pledgeDisclaimerViewDidTapLearnMore() {
self.pledgeDisclaimerViewDidTapLearnMoreObserver.send(value: ())
}
private let riskMessagingViewControllerDismissedProperty = MutableProperty<Bool?>(nil)
public func riskMessagingViewControllerDismissed(isApplePay: Bool) {
self.riskMessagingViewControllerDismissedProperty.value = isApplePay
}
private let (scaFlowCompletedWithResultSignal, scaFlowCompletedWithResultObserver)
= Signal<(StripePaymentHandlerActionStatusType, Error?), Never>.pipe()
public func scaFlowCompleted(with result: StripePaymentHandlerActionStatusType, error: Error?) {
self.scaFlowCompletedWithResultObserver.send(value: (result, error))
}
private let (shippingRuleSelectedSignal, shippingRuleSelectedObserver) = Signal<ShippingRule, Never>.pipe()
public func shippingRuleSelected(_ shippingRule: ShippingRule) {
self.shippingRuleSelectedObserver.send(value: shippingRule)
}
private let (stripeTokenSignal, stripeTokenObserver) = Signal<String?, Never>.pipe()
private let (stripeErrorSignal, stripeErrorObserver) = Signal<Error?, Never>.pipe()
private let (submitButtonTappedSignal, submitButtonTappedObserver) = Signal<Void, Never>.pipe()
public func submitButtonTapped() {
self.submitButtonTappedObserver.send(value: ())
}
private let createApplePayBackingStatusProperty = MutableProperty<PKPaymentAuthorizationStatus>(.failure)
public func stripeTokenCreated(token: String?, error: Error?) -> PKPaymentAuthorizationStatus {
self.stripeTokenObserver.send(value: token)
self.stripeErrorObserver.send(value: error)
return self.createApplePayBackingStatusProperty.value
}
private let (termsOfUseTappedSignal, termsOfUseTappedObserver) = Signal<HelpType, Never>.pipe()
public func termsOfUseTapped(with helpType: HelpType) {
self.termsOfUseTappedObserver.send(value: helpType)
}
private let (userSessionStartedSignal, userSessionStartedObserver) = Signal<Void, Never>.pipe()
public func userSessionStarted() {
self.userSessionStartedObserver.send(value: ())
}
private let viewDidLoadProperty = MutableProperty(())
public func viewDidLoad() {
self.viewDidLoadProperty.value = ()
}
// MARK: - Outputs
public let beginSCAFlowWithClientSecret: Signal<String, Never>
public let configureExpandableRewardsHeaderWithData: Signal<PledgeExpandableRewardsHeaderViewData, Never>
public let configureLocalPickupViewWithData: Signal<PledgeLocalPickupViewData, Never>
public let configurePaymentMethodsViewControllerWithValue: Signal<PledgePaymentMethodsValue, Never>
public let configurePledgeAmountViewWithData: Signal<PledgeAmountViewConfigData, Never>
public let configurePledgeAmountSummaryViewControllerWithData: Signal<PledgeAmountSummaryViewData, Never>
public let configurePledgeViewCTAContainerView: Signal<PledgeViewCTAContainerViewData, Never>
public let configureShippingLocationViewWithData: Signal<PledgeShippingLocationViewData, Never>
public let configureShippingSummaryViewWithData: Signal<PledgeShippingSummaryViewData, Never>
public let configureStripeIntegration: Signal<StripeConfigurationData, Never>
public let configureSummaryViewControllerWithData: Signal<PledgeSummaryViewData, Never>
public let descriptionSectionSeparatorHidden: Signal<Bool, Never>
public let expandableRewardsHeaderViewHidden: Signal<Bool, Never>
public let goToApplePayPaymentAuthorization: Signal<PaymentAuthorizationData, Never>
public let goToRiskMessagingModal: Signal<Bool, Never>
public let goToThanks: Signal<ThanksPageData, Never>
public let goToLoginSignup: Signal<(LoginIntent, Project, Reward), Never>
public let localPickupViewHidden: Signal<Bool, Never>
public let notifyDelegateUpdatePledgeDidSucceedWithMessage: Signal<String, Never>
public let notifyPledgeAmountViewControllerUnavailableAmountChanged: Signal<Double, Never>
public let paymentMethodsViewHidden: Signal<Bool, Never>
public let pledgeAmountViewHidden: Signal<Bool, Never>
public let pledgeAmountSummaryViewHidden: Signal<Bool, Never>
public let popToRootViewController: Signal<(), Never>
public let processingViewIsHidden: Signal<Bool, Never>
public let projectTitle: Signal<String, Never>
public let projectTitleLabelHidden: Signal<Bool, Never>
public let shippingLocationViewHidden: Signal<Bool, Never>
public let shippingSummaryViewHidden: Signal<Bool, Never>
public let showErrorBannerWithMessage: Signal<String, Never>
public let showApplePayAlert: Signal<(String, String), Never>
public let showWebHelp: Signal<HelpType, Never>
public let summarySectionSeparatorHidden: Signal<Bool, Never>
public let rootStackViewLayoutMargins: Signal<UIEdgeInsets, Never>
public let title: Signal<String, Never>
public var inputs: PledgeViewModelInputs { return self }
public var outputs: PledgeViewModelOutputs { return self }
}
// MARK: - Functions
private func requiresSCA(_ envelope: StripeSCARequiring) -> Bool {
return envelope.requiresSCAFlow
}
// MARK: - Validation Functions
private func amountValid(
project: Project,
reward: Reward,
pledgeAmountData: PledgeAmountData,
initialAdditionalPledgeAmount: Double,
context: PledgeViewContext
) -> Bool {
guard
project.personalization.backing != nil,
context.isUpdating,
userIsBacking(reward: reward, inProject: project)
else {
return pledgeAmountData.isValid
}
/**
The amount is valid if it's changed or if the reward has add-ons.
This works because of the validation that would have occurred during add-ons selection,
that is, in `RewardAddOnSelectionViewController` we don't navigate further unless the selection changes.
*/
return [
pledgeAmountData.amount != initialAdditionalPledgeAmount || reward.hasAddOns,
pledgeAmountData.isValid
]
.allSatisfy(isTrue)
}
private func shippingRuleValid(
project: Project,
reward: Reward,
shippingRule: ShippingRule?,
context: PledgeViewContext
) -> Bool {
if context.isCreating || context == .updateReward {
return !reward.shipping.enabled || shippingRule != nil
}
guard
let backing = project.personalization.backing,
let shippingRule = shippingRule,
context.isUpdating
else {
return false
}
return backing.locationId != shippingRule.location.id
}
private func paymentMethodValid(
project: Project,
reward: Reward,
paymentSourceId: String,
context: PledgeViewContext
) -> Bool {
guard
let backedPaymentSourceId = project.personalization.backing?.paymentSource?.id,
context.isUpdating,
userIsBacking(reward: reward, inProject: project)
else {
return true
}
if project.personalization.backing?.status == .errored {
return true
} else if backedPaymentSourceId != paymentSourceId {
return true
}
return false
}
private func allValuesChangedAndValid(
amountValid: Bool,
shippingRuleValid: Bool,
paymentSourceValid: Bool,
context: PledgeViewContext
) -> Bool {
if context.isUpdating, context != .updateReward {
return amountValid || shippingRuleValid || paymentSourceValid
}
return amountValid && shippingRuleValid
}
// MARK: - Helper Functions
private func pledgeSummaryViewData(
project: Project,
total: Double,
confirmationLabelHidden: Bool
) -> PledgeSummaryViewData {
return (project, total, confirmationLabelHidden)
}
private func pledgeAmountSummaryViewData(
with project: Project,
reward _: Reward,
allRewardsTotal: Double,
additionalPledgeAmount: Double,
shippingViewsHidden: Bool,
context: PledgeViewContext
) -> PledgeAmountSummaryViewData? {
guard let backing = project.personalization.backing else { return nil }
let rewardIsLocalPickup = isRewardLocalPickup(backing.reward)
let projectCurrencyCountry = projectCountry(forCurrency: project.stats.currency) ?? project.country
return .init(
bonusAmount: additionalPledgeAmount,
bonusAmountHidden: context == .update,
isNoReward: backing.reward?.isNoReward ?? false,
locationName: backing.locationName,
omitUSCurrencyCode: project.stats.omitUSCurrencyCode,
projectCurrencyCountry: projectCurrencyCountry,
pledgedOn: backing.pledgedAt,
rewardMinimum: allRewardsTotal,
shippingAmount: backing.shippingAmount.flatMap(Double.init),
shippingAmountHidden: !shippingViewsHidden,
rewardIsLocalPickup: rewardIsLocalPickup
)
}
|
apache-2.0
|
b12655381f203184d660480f3698c8c7
| 34.775714 | 279 | 0.729705 | 4.826636 | false | false | false | false |
mentalfaculty/impeller
|
Examples/Listless/Listless/TasksViewController.swift
|
1
|
3608
|
//
// TasksViewController.swift
// Listless
//
// Created by Drew McCormack on 07/01/2017.
// Copyright © 2017 The Mental Faculty B.V. All rights reserved.
//
import UIKit
class TasksViewController: UITableViewController {
var taskList: TaskList? {
didSet {
self.tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 75
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let navController = self.presentedViewController as? UINavigationController,
let taskController = navController.topViewController as? TaskViewController,
var task = taskController.task {
// Save and sync
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.localRepository.commit(&task)
appDelegate.sync()
// In case the edited task hss moved due to a sync, use the identifier to find the right index
let identifiers = taskList!.tasks.map({ $0.metadata.uniqueIdentifier })
if let editedRow = identifiers.index(of: task.metadata.uniqueIdentifier) {
taskList!.tasks[editedRow] = task
}
}
}
@IBAction func add(_ sender: Any?) {
guard taskList != nil else { return }
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let newTask = Task()
taskList!.tasks.insert(newTask, at: 0)
appDelegate.localRepository.commit(&taskList!)
let path = IndexPath(row: 0, section: 0)
tableView.selectRow(at: path, animated: true, scrollPosition: .none)
performSegue(withIdentifier: "toTask", sender: self)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return taskList?.tasks.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let task = taskList!.tasks[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "taskCell", for: indexPath) as! TaskCell
cell.contentLabel.text = task.text
cell.tagsLabel.text = task.tagList.asString
cell.accessoryType = task.isComplete ? .checkmark : .none
return cell
}
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let task = taskList!.tasks[indexPath.row]
let title = task.isComplete ? "Mark Incomplete" : "Mark Complete"
let action = UITableViewRowAction(style: .normal, title: title) { action, indexPath in
var newTask = task
newTask.isComplete = !task.isComplete
self.taskList!.tasks[indexPath.row] = newTask
// Save and sync
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.localRepository.commit(&newTask)
appDelegate.sync()
}
return [action]
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toTask" {
let navController = segue.destination as! UINavigationController
let c = navController.topViewController as! TaskViewController
c.task = taskList!.tasks[tableView.indexPathForSelectedRow!.row]
}
}
}
|
mit
|
187e1cb4044a117c2ad588d92b9b9d87
| 37.37234 | 124 | 0.639867 | 5.130868 | false | false | false | false |
younata/RSSClient
|
TethysKitSpecs/Use Cases/ImportUseCaseSpec.swift
|
1
|
13506
|
import Quick
import Nimble
import Result
import CBGPromise
import FutureHTTP
@testable import TethysKit
class ImportUseCaseSpec: QuickSpec {
override func spec() {
var subject: DefaultImportUseCase!
var httpClient: FakeHTTPClient!
var feedCoordinator: FakeFeedCoordinator!
var opmlService: FakeOPMLService!
var fileManager: FakeFileManager!
var mainQueue: FakeOperationQueue!
beforeEach {
opmlService = FakeOPMLService()
fileManager = FakeFileManager()
mainQueue = FakeOperationQueue()
mainQueue.runSynchronously = true
httpClient = FakeHTTPClient()
feedCoordinator = FakeFeedCoordinator()
subject = DefaultImportUseCase(
httpClient: httpClient,
feedCoordinator: feedCoordinator,
opmlService: opmlService,
fileManager: fileManager,
mainQueue: mainQueue
)
}
func itBehavesLikeSubscribingToAFeed(url: URL, future: @escaping () -> Future<Result<Void, TethysError>>) {
describe("subscribing to a feed") {
it("asks the feed coordinator to subscribe to the feed at that url") {
expect(feedCoordinator.subscribeCalls).to(haveCount(1))
expect(feedCoordinator.subscribeCalls.last).to(equal(url))
}
describe("when the subscribe request succeeds") {
beforeEach {
feedCoordinator.subscribePromises.last?.resolve(.success(
Feed(title: "", url: url, summary: "", tags: [])
))
}
it("resolves the promise with .success") {
expect(future().value?.value).to(beVoid())
}
}
describe("when the subscribe request fails") {
beforeEach {
feedCoordinator.subscribePromises.last?.resolve(.failure(.database(.unknown)))
}
it("forwards the error") {
expect(future().value?.error).to(equal(.database(.unknown)))
}
}
}
}
describe("-scanForImportable:progress:callback:") {
var receivedItem: ImportUseCaseItem?
beforeEach {
receivedItem = nil
}
context("when asked to scan a network URL") {
let url = URL(string: "https://example.com/item")!
beforeEach {
_ = subject.scanForImportable(url).then {
receivedItem = $0
}
}
it("makes a call to the network for the item") {
expect(httpClient.requests).to(haveCount(1))
expect(httpClient.requests.last?.url).to(equal(url))
}
context("when the network returns a feed file") {
let feedURL = Bundle(for: self.classForCoder).url(forResource: "feed", withExtension: "rss")!
let feedData = try! Data(contentsOf: feedURL)
beforeEach {
httpClient.requestPromises.last?.resolve(.success(HTTPResponse(
body: feedData,
status: .ok,
mimeType: "",
headers: [:]
)))
}
it("calls the callback with .Feed, the URL and the number of articles found") {
expect(receivedItem) == ImportUseCaseItem.feed(url, 10)
}
context("later calling -importItem:callback: with that url") {
var future: Future<Result<Void, TethysError>>!
beforeEach {
future = subject.importItem(url)
}
it("does not make another network call") {
expect(httpClient.requests).to(haveCount(1))
}
itBehavesLikeSubscribingToAFeed(url: url) { return future }
}
}
context("when the network returns an OPML file") {
let opmlURL = Bundle(for: self.classForCoder).url(forResource: "test", withExtension: "opml")!
let opmlData = try! Data(contentsOf: opmlURL)
beforeEach {
httpClient.requestPromises.last?.resolve(.success(HTTPResponse(
body: opmlData,
status: .ok,
mimeType: "",
headers: [:]
)))
}
it("calls the callback with .OPML and the URL") {
expect(receivedItem) == ImportUseCaseItem.opml(url, 3)
}
context("later calling -importItem:callback: with that url") {
var future: Future<Result<Void, TethysError>>!
beforeEach {
future = subject.importItem(url)
}
it("does not make another network call") {
expect(httpClient.requests).to(haveCount(1))
}
it("asks the opml service to import the feed list") {
expect(opmlService.importOPMLCalls).to(equal([url]))
}
describe("when the opml service succeeds") {
beforeEach {
opmlService.importOPMLPromises.last?.resolve(.success(AnyCollection([])))
}
it("resolves the promise successfully") {
expect(future.value?.value).to(beVoid())
}
}
describe("when the opml service fails") {
beforeEach {
opmlService.importOPMLPromises.last?.resolve(.failure(.database(.unknown)))
}
it("forwards the error") {
expect(future.value?.error).to(equal(.database(.unknown)))
}
}
}
}
context("when the network returns a standard web page") {
let feed1html = "<link rel=\"alternate\" type=\"application/rss+xml\" title=\"RSS\" href=\"/feed.xml\">"
let feed1Url = URL(string: "/feed.xml", relativeTo: url)!.absoluteURL
let feed2html = "<link rel=\"alternate\" type=\"application/rss+xml\" title=\"RSS\" href=\"/feed2.xml\">"
let feed2Url = URL(string: "/feed2.xml", relativeTo: url)!.absoluteURL
let webPageString = "<html><head>\(feed1html)\(feed2html)</head><body></body></html>"
let webPageData = webPageString.data(using: String.Encoding.utf8)!
beforeEach {
httpClient.requestPromises.last?.resolve(.success(HTTPResponse(
body: webPageData,
status: .ok,
mimeType: "",
headers: [:]
)))
}
it("calls the callback with the url and the list of found feed urls") {
expect(receivedItem) == ImportUseCaseItem.webPage(url, [feed1Url, feed2Url])
}
context("later calling -importItem:callback: with one of the found feed urls") {
var future: Future<Result<Void, TethysError>>!
beforeEach {
future = subject.importItem(feed1Url)
}
it("does not make another network call") {
expect(httpClient.requests).to(haveCount(1))
}
itBehavesLikeSubscribingToAFeed(url: feed1Url) { return future }
}
}
context("when the network returns an error") {
beforeEach {
httpClient.requestPromises.last?.resolve(.failure(.unknown("error")))
}
it("calls the callback with .None and the URL") {
expect(receivedItem) == ImportUseCaseItem.none(url)
}
}
}
context("when asked to scan a file system URL") {
context("and that file is a feed file") {
let feedURL = Bundle(for: self.classForCoder).url(forResource: "feed", withExtension: "rss")!
beforeEach {
_ = subject.scanForImportable(feedURL).then {
receivedItem = $0
}
}
it("does not make a network call") {
expect(httpClient.requests).to(haveCount(0))
}
it("calls the callback with .Feed and the URL") {
expect(receivedItem) == ImportUseCaseItem.feed(feedURL, 10)
}
context("later calling -importItem:callback: with that url") {
var future: Future<Result<Void, TethysError>>!
beforeEach {
future = subject.importItem(feedURL)
}
itBehavesLikeSubscribingToAFeed(url: URL(string: "https://younata.github.io/")!) { return future }
}
}
context("and that file is an opml file") {
let opmlURL = Bundle(for: self.classForCoder).url(forResource: "test", withExtension: "opml")!
beforeEach {
_ = subject.scanForImportable(opmlURL).then {
receivedItem = $0
}
}
it("does not call the network service") {
expect(httpClient.requests).to(haveCount(0))
}
it("calls the callback with .OPML and the URL") {
expect(receivedItem) == ImportUseCaseItem.opml(opmlURL, 3)
}
context("later calling -importItem:callback: with that url") {
var future: Future<Result<Void, TethysError>>!
beforeEach {
future = subject.importItem(opmlURL)
}
it("asks the opml service to import the feed list") {
expect(opmlService.importOPMLCalls).to(equal([opmlURL]))
}
describe("when the opml service succeeds") {
beforeEach {
opmlService.importOPMLPromises.last?.resolve(.success(AnyCollection([])))
}
it("resolves the promise successfully") {
expect(future.value?.value).to(beVoid())
}
}
describe("when the opml service fails") {
beforeEach {
opmlService.importOPMLPromises.last?.resolve(.failure(.database(.unknown)))
}
it("forwards the error") {
expect(future.value?.error).to(equal(.database(.unknown)))
}
}
}
}
context("and that file is neither") {
let url = Bundle(for: self.classForCoder).url(forResource: "test", withExtension: "jpg")!
beforeEach {
_ = subject.scanForImportable(url).then {
receivedItem = $0
}
}
it("does not call the network service") {
expect(httpClient.requests).to(haveCount(0))
}
it("calls the callback with .None and the URL") {
expect(receivedItem) == ImportUseCaseItem.none(url)
}
}
}
}
describe("-importItem:callback:") {
let url = URL(string: "https://example.com/item")!
it("informs the user that we don't have data for this url") {
var didImport = false
_ = subject.importItem(url).then { _ in
didImport = true
}
expect(didImport) == true
}
// other cases are covered up above
}
}
}
|
mit
|
9c11864bc92dfde6b455f3bdd9efaaba
| 39.196429 | 125 | 0.445061 | 5.944542 | false | false | false | false |
codeOfRobin/Components-Personal
|
Sources/FuzzyMatching.swift
|
1
|
10996
|
/*
Copyright 2016 Sean O'Shea
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
/**
Allows client code to pass parameters to the `fuzzyMatchPattern` calls.
*/
public struct FuzzyMatchOptions {
// defines how strict you want to be when fuzzy matching. A value of 0.0 is equivalent to an exact match. A value of 1.0 indicates a very loose understanding of whether a match has been found.
var threshold:Double = FuzzyMatchingOptionsDefaultValues.threshold.rawValue
// defines where in the host String to look for the pattern
var distance:Double = FuzzyMatchingOptionsDefaultValues.distance.rawValue
/**
Standard initializer.
*/
public init() {
}
/**
Initializer which defines `threshold` and `distance` parameters.
- parameter threshold: The threshold value to set
- parameter distance: The distance value to set
- returns: An instance of `FuzzyMatchOptions`
*/
public init(threshold: Double, distance: Double) {
self.threshold = threshold
self.distance = distance
}
}
/**
Defines constants which are used if no `options` parameters are passed to `fuzzyMatchPattern` calls.
*/
public enum FuzzyMatchingOptionsDefaultValues : Double {
// Default threshold value. Defines how strict you want to be when fuzzy matching. A value of 0.0 is equivalent to an exact match. A value of 1.0 indicates a very loose understanding of whether a match has been found.
case threshold = 0.5
// Default distance value. Defines where in the host String to look for the pattern.
case distance = 1000.0
}
/**
Allows for fuzzy matching to happen on all String elements in an Array.
*/
extension Sequence where Iterator.Element == String {
/**
Iterates over all elements in the array and executes a fuzzy match using the `pattern` parameter.
- parameter pattern: The pattern to search for.
- parameter loc: defines the approximate position in the text where the pattern is expected to be found.
- parameter distance: Determines how close the match must be to the fuzzy location. See `loc` parameter.
- returns: An ordered set of Strings based on whichever element matches closest to the `pattern` parameter.
*/
public func sortedByFuzzyMatchPattern(_ pattern:String, loc:Int? = 0, distance:Double? = FuzzyMatchingOptionsDefaultValues.distance.rawValue) -> [String] {
var indexesAdded = [Int]()
var sortedArray = [String]()
for element in stride(from: 1, to: 10, by: 1) {
// stop if we've already found all there is to find
if sortedArray.count == underestimatedCount { break }
// otherwise, proceed to the rest of the values
var options = FuzzyMatchOptions.init(threshold:Double(Double(element) / Double(10)), distance:FuzzyMatchingOptionsDefaultValues.distance.rawValue)
if let unwrappedDistance = distance {
options.distance = unwrappedDistance
}
for (index, value) in self.enumerated() {
if !indexesAdded.contains(index) {
if let _ = value.fuzzyMatchPattern(pattern, loc: loc, options: options) {
sortedArray.append(value)
indexesAdded.append(index)
}
}
}
}
// make sure that the array we return to the user has ALL elements which is in the initial array
for (index, value) in self.enumerated() {
if !indexesAdded.contains(index) {
sortedArray.append(value)
}
}
return sortedArray
}
}
/**
Allows for fuzzy matching to happen on Strings
*/
extension String {
/**
Provides a confidence score relating to how likely the pattern is to be found in the host string.
- parameter pattern: The pattern to search for.
- parameter loc: The index in the element from which to search.
- parameter distance: Determines how close the match must be to the fuzzy location. See `loc` parameter.
- returns: A Double which indicates how confident we are that the pattern can be found in the host string. A low value (0.001) indicates that the pattern is likely to be found. A high value (0.999) indicates that the pattern is not likely to be found
*/
public func confidenceScore(_ pattern:String, loc:Int? = 0, distance:Double? = FuzzyMatchingOptionsDefaultValues.distance.rawValue) -> Double? {
// start at a low threshold and work our way up
for index in stride(from: 1, to: 1000, by: 1) {
let threshold:Double = Double(Double(index) / Double(1000))
var d = FuzzyMatchingOptionsDefaultValues.distance.rawValue
if let unwrappedDistance = distance {
d = unwrappedDistance
}
let options = FuzzyMatchOptions.init(threshold: threshold, distance: d)
if self.fuzzyMatchPattern(pattern, loc: loc, options: options) != nil {
return threshold
}
}
return nil
}
/**
Executes a fuzzy match on the String using the `pattern` parameter.
- parameter pattern: The pattern to search for.
- parameter loc: The index in the element from which to search.
- parameter options: Dictates how the search is executed. See `FuzzyMatchingOptionsParams` and `FuzzyMatchingOptionsDefaultValues` for details.
- returns: An Int indicating where the fuzzy matched pattern can be found in the String.
*/
public func fuzzyMatchPattern(_ pattern:String, loc:Int? = 0, options:FuzzyMatchOptions? = nil) -> Int? {
guard count > 0 else { return nil }
let generatedOptions = generateOptions(options)
let location = max(0, min(loc ?? 0, count))
let threshold = generatedOptions.threshold
let distance = generatedOptions.distance
if caseInsensitiveCompare(pattern) == ComparisonResult.orderedSame {
return 0
} else if pattern.isEmpty {
return nil
} else {
if (location + pattern.count) < count {
let substring = self[self.index(self.startIndex, offsetBy: 0)...self.index(self.startIndex, offsetBy: pattern.count)]
if pattern.caseInsensitiveCompare(substring) == ComparisonResult.orderedSame {
return location
} else {
return matchBitapOfText(pattern, loc:location, threshold:threshold, distance:distance)
}
} else {
return matchBitapOfText(pattern, loc:location, threshold:threshold, distance:distance)
}
}
}
func matchBitapOfText(_ pattern:String, loc:Int, threshold:Double, distance:Double) -> Int? {
let alphabet = matchAlphabet(pattern)
let bestGuessAtThresholdAndLocation = speedUpBySearchingForSubstring(pattern, loc:loc, threshold:threshold, distance:distance)
var scoreThreshold = bestGuessAtThresholdAndLocation.threshold
var bestLoc = bestGuessAtThresholdAndLocation.bestLoc
let matchMask = 1 << (pattern.count - 1)
var binMin:Int
var binMid:Int
var binMax = pattern.count + count
var rd:[Int?] = [Int?]()
var lastRd:[Int?] = [Int?]()
bestLoc = NSNotFound
for (index, _) in pattern.enumerated() {
binMin = 0
binMid = binMax
while binMin < binMid {
let score = bitapScoreForErrorCount(index, x:(loc + binMid), loc:loc, pattern:pattern, distance:distance)
if score <= scoreThreshold {
binMin = binMid
} else {
binMax = binMid
}
binMid = (binMax - binMin) / 2 + binMin
}
binMax = binMid
var start = maxOfConstAndDiff(1, b:loc, c:binMid)
let finish = min(loc + binMid, count) + pattern.count
rd = [Int?](repeating: 0, count: finish + 2)
rd[finish + 1] = (1 << index) - 1
var j = finish
for _ in stride(from: j, to: start - 1, by: -1) {
var charMatch:Int
if count <= j - 1 {
charMatch = 0
} else {
let character = String(self[self.index(startIndex, offsetBy: j - 1)])
if count <= j - 1 || alphabet[character] == nil {
charMatch = 0
} else {
charMatch = alphabet[character]!
}
}
if index == 0 {
rd[j] = ((rd[j + 1]! << 1) | 1) & charMatch
} else {
rd[j] = (((rd[j + 1]! << 1) | 1) & charMatch) | (((lastRd[j + 1]! | lastRd[j]!) << 1) | 1) | lastRd[j + 1]!
}
if (rd[j]! & matchMask) != 0 {
let score = bitapScoreForErrorCount(index, x:(j - 1), loc:loc, pattern:pattern, distance:distance)
if score <= scoreThreshold {
scoreThreshold = score
bestLoc = j - 1
if bestLoc > loc {
start = maxOfConstAndDiff(1, b:2 * loc, c:bestLoc)
} else {
break
}
}
}
j = j - 1
}
if bitapScoreForErrorCount(index + 1, x:loc, loc:loc, pattern:pattern, distance:distance) > scoreThreshold {
break
}
lastRd = rd
}
return bestLoc != NSNotFound ? bestLoc : nil
}
func matchAlphabet(_ pattern:String) -> [String: Int] {
var alphabet = [String: Int]()
for char in pattern {
alphabet[String(char)] = 0
}
for (i, char) in pattern.enumerated() {
let stringRepresentationOfCharacter = String(char)
let possibleEntry = alphabet[stringRepresentationOfCharacter]!
let value = possibleEntry | (1 << (pattern.count - i - 1))
alphabet[stringRepresentationOfCharacter] = value
}
return alphabet
}
func bitapScoreForErrorCount(_ e:Int, x:Int, loc:Int, pattern:String, distance:Double) -> Double {
let accuracy:Double = Double(e) / Double(pattern.count)
let proximity = abs(loc - x)
if distance == 0 {
return Double(proximity == 0 ? accuracy : 1)
} else {
return Double(Double(accuracy) + (Double(proximity) / distance))
}
}
func speedUpBySearchingForSubstring(_ pattern:String, loc:Int, threshold:Double, distance:Double) -> (bestLoc: Int, threshold: Double) {
var scoreThreshold = threshold
var bestLoc = NSNotFound
var range: Range<String.Index> = startIndex..<self.index(startIndex, offsetBy: count)
if let possibleLiteralSearchRange = self.range(of: pattern, options:NSString.CompareOptions.literal, range:range, locale: Locale.current) {
bestLoc = self.distance(from: startIndex, to: possibleLiteralSearchRange.lowerBound)
scoreThreshold = min(bitapScoreForErrorCount(0, x:bestLoc, loc:loc, pattern:pattern, distance:distance), threshold)
range = startIndex..<self.index(startIndex, offsetBy: min(loc + pattern.count, count))
if let possibleBackwardsSearchRange = self.range(of: pattern, options:NSString.CompareOptions.backwards, range:range, locale: Locale.current) {
bestLoc = self.distance(from: startIndex, to: possibleBackwardsSearchRange.lowerBound)
scoreThreshold = min(bitapScoreForErrorCount(0, x:bestLoc, loc:loc, pattern:pattern, distance:distance), scoreThreshold)
}
}
return (bestLoc, threshold)
}
func generateOptions(_ options:FuzzyMatchOptions?) -> FuzzyMatchOptions {
if let unwrappedOptions = options {
return unwrappedOptions
} else {
return FuzzyMatchOptions.init()
}
}
func maxOfConstAndDiff(_ a:Int, b:Int, c:Int) -> Int {
return b <= c ? a : b - c + a
}
}
|
mit
|
d751a32d7675a265f88ee5e61bd78276
| 37.582456 | 251 | 0.709985 | 3.636243 | false | false | false | false |
larryhou/swift
|
QRCode/QRCode/PDF417ImageViewController.swift
|
1
|
2856
|
//
// PDF417ImageViewController.swift
// QRCode
//
// Created by larryhou on 24/12/2015.
// Copyright © 2015 larryhou. All rights reserved.
//
import Foundation
import UIKit
class PDF417ImageViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextViewDelegate {
struct CompactStyleInfo {
let mode: Float, name: String
}
@IBOutlet weak var imageView: PDF417ImageView!
@IBOutlet weak var aspectRatioSlider: UISlider!
@IBOutlet weak var aspactRatioIndicator: UILabel!
@IBOutlet weak var compactionModePicker: UIPickerView!
@IBOutlet weak var compactStyleSwitch: UISwitch!
@IBOutlet weak var alwaysSpecifyCompactionSwitch: UISwitch!
private var styles: [CompactStyleInfo]!
override func viewDidLoad() {
super.viewDidLoad()
styles = []
styles.append(CompactStyleInfo(mode: 0, name: "Automatic"))
styles.append(CompactStyleInfo(mode: 1, name: "Numeric"))
styles.append(CompactStyleInfo(mode: 2, name: "Text"))
styles.append(CompactStyleInfo(mode: 3, name: "Byte"))
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
aspactRatioDidChange(aspectRatioSlider)
alwaysSpecifyCompactionDidChange(alwaysSpecifyCompactionSwitch)
compactStyleDidChange(compactStyleSwitch)
compactionModePicker.selectRow(2, inComponent: 0, animated: false)
}
@IBAction func aspactRatioDidChange(_ sender: UISlider) {
aspactRatioIndicator.text = String(format: "%2.0f", sender.value)
imageView.inputPreferredAspectRatio = Float(sender.value)
}
@IBAction func compactStyleDidChange(_ sender: UISwitch) {
imageView.inputCompactStyle = sender.isOn
}
@IBAction func alwaysSpecifyCompactionDidChange(_ sender: UISwitch) {
imageView.inputAlwaysSpecifyCompaction = sender.isOn
}
// MARK: text
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text == "\n" {
textView.resignFirstResponder()
return false
}
return true
}
func textViewDidChange(_ textView: UITextView) {
imageView.inputMessage = textView.text
}
// MARK: picker
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return styles.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return styles[row].name
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
imageView.inputCompactionMode = styles[row].mode
}
}
|
mit
|
7bec8fcc185a3561f2770941ed1282fa
| 30.373626 | 117 | 0.69387 | 4.814503 | false | false | false | false |
mindbody/Conduit
|
Tests/ConduitTests/Auth/OAuth2TokenGrantManagerTests.swift
|
1
|
3048
|
//
// OAuth2TokenGrantManagerTests.swift
// Conduit
//
// Created by John Hammerlund on 7/7/17.
// Copyright © 2017 MINDBODY. All rights reserved.
//
import XCTest
@testable import Conduit
class OAuth2TokenGrantManagerTests: XCTestCase {
typealias BadResponse = (response: HTTPURLResponse?, expectedError: OAuth2Error)
let dummyURL = URL(string: "https://httpbin.org/get")
func testErrorsGeneratedAsExpected() {
guard let url = dummyURL else {
XCTFail("Inavlid url")
return
}
let response401 = HTTPURLResponse(url: url, statusCode: 401, httpVersion: "1.1", headerFields: nil)
let response400 = HTTPURLResponse(url: url, statusCode: 400, httpVersion: "1.1", headerFields: nil)
let response500 = HTTPURLResponse(url: url, statusCode: 500, httpVersion: "1.1", headerFields: nil)
guard let errorNoResponse = OAuth2TokenGrantManager.errorFrom(data: nil, response: nil) as? OAuth2Error,
let error401 = OAuth2TokenGrantManager.errorFrom(data: nil, response: response401) as? OAuth2Error,
let error400 = OAuth2TokenGrantManager.errorFrom(data: nil, response: response400) as? OAuth2Error,
let error500 = OAuth2TokenGrantManager.errorFrom(data: nil, response: response500) as? OAuth2Error else {
XCTFail("Unexpected error type")
return
}
guard case .noResponse = errorNoResponse,
case .clientFailure = error401,
case .clientFailure = error400,
case .serverFailure = error500 else {
XCTFail("Unexpected error type")
return
}
}
func testValidResponseGeneratesNoErrors() {
guard let url = dummyURL else {
XCTFail("Inavlid url")
return
}
let validResponse = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "1.1", headerFields: nil)
let generatedError = OAuth2TokenGrantManager.errorFrom(data: nil, response: validResponse)
XCTAssertNil(generatedError)
}
func testBadResponses() {
guard let url = dummyURL, let mockResponse = HTTPURLResponse(url: url, statusCode: 401, httpVersion: "1.1", headerFields: nil) else {
XCTFail("Invalid response")
return
}
let badResponses = [
(nil, OAuth2Error.noResponse),
(HTTPURLResponse(url: url, statusCode: 401, httpVersion: "1.1", headerFields: nil), OAuth2Error.clientFailure(nil, mockResponse)),
(HTTPURLResponse(url: url, statusCode: 400, httpVersion: "1.1", headerFields: nil), OAuth2Error.clientFailure(nil, mockResponse)),
(HTTPURLResponse(url: url, statusCode: 500, httpVersion: "1.1", headerFields: nil), OAuth2Error.serverFailure(nil, mockResponse))
]
badResponses.forEach { badResponse in
let generatedError = OAuth2TokenGrantManager.errorFrom(data: nil, response: badResponse.0)
XCTAssertNotNil(generatedError)
}
}
}
|
apache-2.0
|
85c2c9e2b2f0ba586f4be81e15c60564
| 40.739726 | 142 | 0.656383 | 4.428779 | false | true | false | false |
marty-suzuki/QiitaApiClient
|
QiitaApiClient/Model/QiitaAccessToken.swift
|
1
|
1009
|
//
// QiitaAccessToken.swift
// QiitaApiClient
//
// Created by Taiki Suzuki on 2016/08/20.
//
//
import Foundation
public enum QiitaAuthorizeScope: String {
case ReadQiita = "read_qiita"
case ReadQiitaTeam = "read_qiita_team"
case WriteQiita = "write_qiita"
case WriteQiitaTeam = "write_qiita_team"
}
public class QiitaAccessToken: QiitaModel {
public let clientId: String
public let scopes: [QiitaAuthorizeScope]
public let token: String
public required init?(dictionary: [String : NSObject]) {
guard
let clientId = dictionary["client_id"] as? String,
let rawScopes = dictionary["scopes"] as? [String],
let token = dictionary["token"] as? String
else {
return nil
}
let scopes = rawScopes.flatMap { QiitaAuthorizeScope(rawValue: $0) }
if scopes.count < 1 { return nil }
self.clientId = clientId
self.scopes = scopes
self.token = token
}
}
|
mit
|
4ce11fc571f5448d4caeee8378bab005
| 26.297297 | 76 | 0.622398 | 4.135246 | false | false | false | false |
superman-coder/pakr
|
pakr/pakr/UserInterface/PostParking/InfoScreen/PostInfoController.swift
|
1
|
17571
|
//
// PostInfoController.swift
// pakr
//
// Created by Huynh Quang Thao on 4/11/16.
// Copyright © 2016 Pakr. All rights reserved.
//
import Foundation
import UIKit
import Material
import BEMCheckBox
protocol PostInfoControllerDelegate {
func nextStep(parking :Parking)
}
class PostInfoController: BaseViewController {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var businessNameTextField: TextField!
@IBOutlet weak var businessDescriptionTextField: TextField!
@IBOutlet weak var businessTelephoneTextField: TextField!
@IBOutlet weak var parkingNameTextField: TextField!
@IBOutlet weak var parkingAddressTextField: TextField!
@IBOutlet weak var parkingDescriptionTextField: TextField!
@IBOutlet weak var workTimeTableView: UITableView!
@IBOutlet weak var noteWorkTime: TextField!
@IBOutlet weak var capacityTextField: TextField!
@IBOutlet weak var contentMarginBottom: NSLayoutConstraint!
@IBOutlet weak var parkingInfoContainer: UIView!
@IBOutlet weak var contentView: UIView!
@IBOutlet weak var businessInfoContainer: UIView!
@IBOutlet weak var bikeDetailContainer: UIView!
@IBOutlet weak var motorbikeDetailContainer: UIView!
@IBOutlet weak var carDetailContainer: UIView!
@IBOutlet weak var parkingDetailContainer: UIView!
@IBOutlet weak var bikeMinPriceTextField: TextField!
@IBOutlet weak var bikeMaxPriceTextField: TextField!
@IBOutlet weak var bikeCheckBox: BEMCheckBox!
@IBOutlet weak var motorMinPriceTextField: TextField!
@IBOutlet weak var motorMaxPriceTextField: TextField!
@IBOutlet weak var motorCheckBox: BEMCheckBox!
@IBOutlet weak var carMinPriceTextField: TextField!
@IBOutlet weak var carMaxPriceTextField: TextField!
@IBOutlet weak var carCheckBox: BEMCheckBox!
func initDemoData() {
businessNameTextField.text = "Pakr Company"
businessDescriptionTextField.text = "We are superman. We can keep safe your vehicle. Anytime, anywhere"
businessTelephoneTextField.text = "08-03-01676029814"
parkingNameTextField.text = "Bãi giữ xe Hồ Con Rùa"
parkingAddressTextField.text = "138 Hai Bà Trưng"
parkingDescriptionTextField.text = "Đội ngũ giữ xe chuyên nghiệp thành phố"
capacityTextField.text = "200"
noteWorkTime.text = "Chúng tôi làm việc cả ngày nghỉ cuối tuần"
bikeMinPriceTextField.text = "2000"
bikeMaxPriceTextField.text = "4000"
motorMinPriceTextField.text = "3000"
motorMaxPriceTextField.text = "10000"
carMinPriceTextField.text = "30000"
carMaxPriceTextField.text = "80000"
carCheckBox.on = true
motorCheckBox.on = true
bikeCheckBox.on = true
}
let value: Int = 1
var isShowKeyBoard = false
var keyBoardHeight : CGFloat = 0
var currentTextField: UITextField?
var message: String!
var arrDayOfWeek: NSArray!
var arrTimeRange: NSMutableArray!
var currentCellSelect : WorkTimeTableViewCell!
var isCloseTimeAction : Bool!
var delegate: PostInfoControllerDelegate?
var isSelfShow: Bool = true
var parking: Parking?
override func viewDidLoad() {
super.viewDidLoad()
carCheckBox.tintColor = UIColor.redColor()
carCheckBox.onCheckColor = UIColor.redColor()
// carCheckBox.onFillColor = UIColor.redColor()
configTextFields()
setShowdow()
registryNotifyKeyBoard()
workTimeTableView.scrollEnabled = false
workTimeTableView.rowHeight = 45
self.contentView.backgroundColor = UIColor.UIColorFromRGB(0xE0E0E0)
let nib = UINib(nibName: "WorkTimeTableViewCell", bundle: nil)
workTimeTableView.registerNib(nib , forCellReuseIdentifier: "WorkTimeTableViewCell")
initWorkTime()
// init data for demo.
initDemoData()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
isSelfShow = true
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
setDataForParking()
isSelfShow = true
}
override func viewDidDisappear(animated: Bool) {
isSelfShow = false
}
//MARK - Private method
func isNextStep() -> Bool {
let mutableArray = NSMutableArray()
mutableArray.addObject(businessNameTextField)
mutableArray.addObject(businessDescriptionTextField)
mutableArray.addObject(businessTelephoneTextField)
mutableArray.addObject(parkingNameTextField)
mutableArray.addObject(parkingAddressTextField)
mutableArray.addObject(parkingDescriptionTextField)
mutableArray.addObject(capacityTextField)
if bikeCheckBox.on {
mutableArray.addObject(bikeMinPriceTextField)
mutableArray.addObject(bikeMaxPriceTextField)
}
if motorCheckBox.on {
mutableArray.addObject(motorMinPriceTextField)
mutableArray.addObject(motorMaxPriceTextField)
}
if carCheckBox.on {
mutableArray.addObject(carMinPriceTextField)
mutableArray.addObject(carMaxPriceTextField)
}
for textField in mutableArray {
let string = (textField as! TextField).text?.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
if (string == "") {
showMessage(textField as! TextField)
return false
}
}
return true
}
func showMessage(textField: TextField){
switch textField {
case businessNameTextField:
message = "Please Insert Company Name"
case businessDescriptionTextField:
message = "Please Insert Company Decription"
case businessTelephoneTextField:
message = "Please Insert Company TelePhone"
case parkingNameTextField:
message = "Please Insert Parking Name"
case parkingAddressTextField:
message = "Please Insert Parking Address"
case parkingDescriptionTextField:
message = "Please Insert Parking Decription"
case capacityTextField:
message = "Please Insert Parking Capacity"
case bikeMinPriceTextField:
message = "Please Insert Bike Min Price"
case bikeMaxPriceTextField:
message = "Please Insert Bike Max Price"
case motorMinPriceTextField:
message = "Please Insert Motor Min Price"
case motorMaxPriceTextField:
message = "Please Insert Motor Max Price"
case carMinPriceTextField:
message = "Please Insert Car Min Price"
case carMaxPriceTextField:
message = "Please Insert Car Max Price"
break
default:
break
}
let alert = UIAlertController(title: "Lack of information", message: message, preferredStyle: .Alert)
let okAction = UIAlertAction(title:"OK", style: .Default) { (action: UIAlertAction) in
self.dismissViewControllerAnimated(true, completion: {
})
}
alert.addAction(okAction)
presentViewController(alert, animated: true, completion: nil)
}
func setDataForParking(){
let business = Business(businessName: businessNameTextField.text, businessDescription: businessDescriptionTextField.text, telephone: businessTelephoneTextField.text)
// let coordinate = Coordinate(latitude: <#T##Double!#>, longitude: <#T##Double!#>)
let vehicleList = NSMutableArray()
if carCheckBox.on {
let vehic = VehicleDetail(vehicleType: VehicleType.Car, minPrice: carMinPriceTextField.text, maxPrice: carMaxPriceTextField.text, note: noteWorkTime.text)
vehicleList.addObject(vehic)
}
if bikeCheckBox.on {
let vehic = VehicleDetail(vehicleType: VehicleType.Bike, minPrice: bikeMinPriceTextField.text, maxPrice: bikeMaxPriceTextField.text, note: noteWorkTime.text)
vehicleList.addObject(vehic)
}
if motorCheckBox.on {
let vehic = VehicleDetail(vehicleType: VehicleType.Motor, minPrice: motorMinPriceTextField.text, maxPrice: motorMaxPriceTextField.text, note: noteWorkTime.text)
vehicleList.addObject(vehic)
}
parking = Parking(business: business, parkingName: parkingNameTextField.text, capacity: Int(capacityTextField.text!), addressName: parkingAddressTextField.text!, coordinate: nil, vehicleDetailList: vehicleList.copy() as! [VehicleDetail], schedule: arrTimeRange.copy() as! [TimeRange], region: [])
dispatch_async(dispatch_get_main_queue()) {
self.delegate?.nextStep(self.parking!)
}
}
func initWorkTime() {
arrDayOfWeek = ["Monday","Tues","Wed","Thur","Fri","Sat","Sun"]
arrTimeRange = NSMutableArray()
for var i = 0; i<=6 ; i += 1 {
let time = TimeRange(openTime: "6:00", closeTime: "24:00")
arrTimeRange.addObject(time)
}
workTimeTableView.reloadData()
}
func configTextFields(){
LayoutUtils.setUpTextField(businessNameTextField, title: "Company Name", suggestionText: "Please tell us your company name")
LayoutUtils.setUpTextField(businessDescriptionTextField, title: "Description", suggestionText: "Let us know more about you")
LayoutUtils.setUpTextField(businessTelephoneTextField, title: "Telephone number", suggestionText: "How can we contact you")
LayoutUtils.setUpTextField(parkingNameTextField, title: "Parking Name", suggestionText: "make customer easily know parking lot")
LayoutUtils.setUpTextField(parkingAddressTextField, title: "Parking Address", suggestionText: "How can we find your parking lot")
LayoutUtils.setUpTextField(parkingDescriptionTextField, title: "Parking Description", suggestionText: "Let us know more")
LayoutUtils.setUpTextField(bikeMinPriceTextField, title: "Min Price", suggestionText: "Let us know more")
LayoutUtils.setUpTextField(bikeMaxPriceTextField, title: "Max Price", suggestionText: "Let us know more")
LayoutUtils.setUpTextField(motorMinPriceTextField, title: "Min Price", suggestionText: "Let us know more")
LayoutUtils.setUpTextField(motorMaxPriceTextField, title: "Max Price", suggestionText: "Let us know more")
LayoutUtils.setUpTextField(carMinPriceTextField, title: "Min Price", suggestionText: "Let us know more")
LayoutUtils.setUpTextField(carMaxPriceTextField, title: "Max Price", suggestionText: "Let us know more")
LayoutUtils.setUpTextField(noteWorkTime, title: "This is notes for workTime", suggestionText: "Let us know more")
LayoutUtils.setUpTextField(capacityTextField, title: "This is capacity", suggestionText: "Let us know more")
businessNameTextField.delegate = self
businessDescriptionTextField.delegate = self
businessTelephoneTextField.delegate = self
parkingNameTextField.delegate = self
parkingAddressTextField.delegate = self
parkingDescriptionTextField.delegate = self
bikeMinPriceTextField.delegate = self
bikeMaxPriceTextField.delegate = self
motorMinPriceTextField.delegate = self
motorMaxPriceTextField.delegate = self
carMinPriceTextField.delegate = self
carMaxPriceTextField.delegate = self
noteWorkTime.delegate = self
capacityTextField.delegate = self
}
func registryNotifyKeyBoard(){
NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(PostInfoController.keyBoardShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(PostInfoController.keyBoardHide(_:)), name: UIKeyboardWillHideNotification, object: nil)
}
func keyBoardShow(notifycation: NSNotification){
if isSelfShow == false {
return
}
if !isShowKeyBoard{
isShowKeyBoard = true
let dic = notifycation.userInfo
let keyboardFrame = dic![UIKeyboardFrameBeginUserInfoKey]?.CGRectValue()
if keyBoardHeight == 0.0 {
keyBoardHeight = (keyboardFrame?.size.height)!
}
UIView .animateWithDuration(0.3) {
self.contentMarginBottom.constant = (keyboardFrame?.size.height)! - 50
self.contentView .layoutIfNeeded()
}
if currentTextField != nil {
focusScrollViewWhenShowKeyBoard(currentTextField!)
}
}
}
func keyBoardHide(notifycation: NSNotification){
if isSelfShow == false {
return
}
if isShowKeyBoard{
isShowKeyBoard = false
UIView .animateWithDuration(0.3) {
self.contentMarginBottom.constant = 5
self.contentView .layoutIfNeeded()
}
}
}
func setShowdow() {
LayoutUtils.dropShadowView(businessInfoContainer)
LayoutUtils.dropShadowView(parkingInfoContainer)
LayoutUtils.dropShadowView(bikeDetailContainer)
LayoutUtils.dropShadowView(motorbikeDetailContainer)
LayoutUtils.dropShadowView(carDetailContainer)
LayoutUtils.dropShadowView(parkingDetailContainer)
}
func focusScrollViewWhenShowKeyBoard(textField: UITextField){
focusCoordinates(textField)
}
func focusCoordinates(textField: UITextField){
let contentViewVisuableHeight = UIScreen.mainScreen().bounds.size.height - (self.navigationController?.navigationBar.bounds.size.height)! - 20 - keyBoardHeight
// 100 is height of stepView config in PostParkingViewController
var pointY = textField.bounds.size.height + textField.frame.origin.y + 100
var viewSuper = textField.superview
while (!viewSuper!.isKindOfClass(UIScrollView)){
pointY = pointY + (viewSuper?.frame.origin.y)!
viewSuper = viewSuper!.superview
}
print(pointY)
print(contentViewVisuableHeight)
print(pointY - scrollView.contentOffset.y)
if contentViewVisuableHeight - (pointY - scrollView.contentOffset.y) <= 0 {
isShowKeyBoard = false
scrollView.contentOffset = CGPointMake(0, pointY - contentViewVisuableHeight + 15)
isShowKeyBoard = true
}
}
func showClockView(cell: WorkTimeTableViewCell, isCloseTime: Bool){
currentCellSelect = cell
isCloseTimeAction = isCloseTime
let view = UIView(frame: CGRectMake(0, 0, 320, 500))
let rootView = UIApplication.sharedApplication().keyWindow?.rootViewController
view.center = rootView!.view.center
let clockView = CustomTimePicker(view: view, withDarkTheme: false)
clockView.backgroundColor = UIColor.blackColor()
clockView.alpha = 0.8
clockView.delegate = self
rootView!.view .addSubview(clockView)
}
}
extension PostInfoController: UITextFieldDelegate{
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
currentTextField = textField
return true
}
}
extension PostInfoController: UIScrollViewDelegate{
func scrollViewDidScroll(scrollView: UIScrollView) {
if isShowKeyBoard{
isShowKeyBoard = false
UIView .animateWithDuration(0.3) {
self.contentMarginBottom.constant = 5
self.contentView.layoutIfNeeded()
}
self.view.endEditing(true)
}
}
}
extension PostInfoController: UITableViewDelegate, UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 7
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("WorkTimeTableViewCell", forIndexPath: indexPath) as! WorkTimeTableViewCell
cell.delegate = self
let timeRange = arrTimeRange[indexPath.row] as! TimeRange
cell.disPlay(arrDayOfWeek[indexPath.row] as! String, closeTime:timeRange.closeTime , openTime: timeRange.openTime )
return cell
}
}
extension PostInfoController: CustomTimePickerDelegate{
func dismissClockViewWithHours(hours: String!, andMinutes minutes: String!, andTimeMode timeMode: String!) {
let text = "\(hours):\(minutes) \(timeMode)"
let indexPath = workTimeTableView.indexPathForCell(currentCellSelect)
let timeRange = arrTimeRange[indexPath!.row] as! TimeRange
if isCloseTimeAction == true {
currentCellSelect.lblCloseTime.text = text
timeRange.closeTime = text
}else{
currentCellSelect.lblOpenTime.text = text
timeRange.openTime = text
}
}
}
extension PostInfoController: WorkTimeTableViewCellDelegate{
func didSelectOpenTimeAction(cell: WorkTimeTableViewCell) {
showClockView(cell,isCloseTime: false)
}
func didSelectCloseTimeAction(cell: WorkTimeTableViewCell) {
showClockView(cell,isCloseTime: true)
}
}
|
apache-2.0
|
a0077988eda2e5ddb47457640ad303a9
| 42.516129 | 304 | 0.680486 | 4.990324 | false | false | false | false |
haijianhuo/TopStore
|
Pods/PopupDialog/PopupDialog/Classes/PopupDialogButton.swift
|
1
|
6003
|
//
// PopupDialogButton.swift
//
// Copyright (c) 2016 Orderella Ltd. (http://orderella.co.uk)
// Author - Martin Wildfeuer (http://www.mwfire.de)
//
// 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 UIKit
/// Represents the default button for the popup dialog
open class PopupDialogButton: UIButton {
public typealias PopupDialogButtonAction = () -> Void
// MARK: Public
/// The font and size of the button title
@objc open dynamic var titleFont: UIFont? {
get { return titleLabel?.font }
set { titleLabel?.font = newValue }
}
/// The height of the button
@objc open dynamic var buttonHeight: Int
/// The title color of the button
@objc open dynamic var titleColor: UIColor? {
get { return self.titleColor(for: UIControlState()) }
set { setTitleColor(newValue, for: UIControlState()) }
}
/// The background color of the button
@objc open dynamic var buttonColor: UIColor? {
get { return backgroundColor }
set { backgroundColor = newValue }
}
/// The separator color of this button
@objc open dynamic var separatorColor: UIColor? {
get { return separator.backgroundColor }
set {
separator.backgroundColor = newValue
leftSeparator.backgroundColor = newValue
}
}
/// Default appearance of the button
open var defaultTitleFont = UIFont.systemFont(ofSize: 14)
open var defaultTitleColor = UIColor(red: 0.25, green: 0.53, blue: 0.91, alpha: 1)
open var defaultButtonColor = UIColor.clear
open var defaultSeparatorColor = UIColor(white: 0.9, alpha: 1)
/// Whether button should dismiss popup when tapped
@objc open var dismissOnTap = true
/// The action called when the button is tapped
open fileprivate(set) var buttonAction: PopupDialogButtonAction?
// MARK: Private
fileprivate lazy var separator: UIView = {
let line = UIView(frame: .zero)
line.translatesAutoresizingMaskIntoConstraints = false
return line
}()
fileprivate lazy var leftSeparator: UIView = {
let line = UIView(frame: .zero)
line.translatesAutoresizingMaskIntoConstraints = false
line.alpha = 0
return line
}()
// MARK: Internal
internal var needsLeftSeparator: Bool = false {
didSet {
leftSeparator.alpha = needsLeftSeparator ? 1.0 : 0.0
}
}
// MARK: Initializers
/*!
Creates a button that can be added to the popup dialog
- parameter title: The button title
- parameter dismisssOnTap: Whether a tap automatically dismisses the dialog
- parameter action: The action closure
- returns: PopupDialogButton
*/
@objc public init(title: String, height: Int = 45, dismissOnTap: Bool = true, action: PopupDialogButtonAction?) {
// Assign the button height
buttonHeight = height
// Assign the button action
buttonAction = action
super.init(frame: .zero)
// Set the button title
setTitle(title, for: UIControlState())
self.dismissOnTap = dismissOnTap
// Setup the views
setupView()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: View setup
open func setupView() {
// Default appearance
setTitleColor(defaultTitleColor, for: UIControlState())
titleLabel?.font = defaultTitleFont
backgroundColor = defaultButtonColor
separator.backgroundColor = defaultSeparatorColor
leftSeparator.backgroundColor = defaultSeparatorColor
// Add and layout views
addSubview(separator)
addSubview(leftSeparator)
let views = ["separator": separator, "leftSeparator": leftSeparator, "button": self]
let metrics = ["buttonHeight": buttonHeight]
var constraints = [NSLayoutConstraint]()
constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:[button(buttonHeight)]", options: [], metrics: metrics, views: views)
constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|[separator]|", options: [], metrics: nil, views: views)
constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[separator(1)]", options: [], metrics: nil, views: views)
constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|[leftSeparator(1)]", options: [], metrics: nil, views: views)
constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[leftSeparator]|", options: [], metrics: nil, views: views)
NSLayoutConstraint.activate(constraints)
}
open override var isHighlighted: Bool {
didSet {
isHighlighted ? pv_fade(.out, 0.5) : pv_fade(.in, 1.0)
}
}
}
|
mit
|
7681b881d391dbbf33c7b1cae4e181bd
| 35.162651 | 144 | 0.6665 | 4.876523 | false | false | false | false |
steve-holmes/music-app-2
|
MusicApp/Modules/Online/OnlineModule.swift
|
1
|
4901
|
//
// OnlineModule.swift
// MusicApp
//
// Created by Hưng Đỗ on 6/9/17.
// Copyright © 2017 HungDo. All rights reserved.
//
import UIKit
import Swinject
class OnlineModule: Module {
override func register() {
// MARK: Controller
container.register(UINavigationController.self) { [weak self] resolver in
let navigationController = UIStoryboard.online.instantiateViewController(withIdentifier: String(describing: OnlineViewController.self)) as! UINavigationController
if let onlineController = navigationController.viewControllers.first as? OnlineViewController {
onlineController.store = resolver.resolve(OnlineStore.self)!
onlineController.action = resolver.resolve(OnlineAction.self)!
if let searchModule = self?.parent?.searchModule {
onlineController.searchController = searchModule.container.resolve(UISearchController.self)!
}
self?.setupMenu(onlineController)
onlineController.controllers = [
self!.getController(of: HomeViewController.self, in: self!.parent!.homeModule),
self!.getController(of: PlaylistViewController.self, in: self!.parent!.playlistModule),
self!.getController(of: SongViewController.self, in: self!.parent!.songModule),
self!.getController(of: VideoViewController.self, in: self!.parent!.videoModule),
self!.getController(of: RankViewController.self, in: self!.parent!.rankModule),
self!.getController(of: SingerViewController.self, in: self!.parent!.singerModule),
self!.getController(of: TopicViewController.self, in: self!.parent!.topicModule)
]
}
return navigationController
}
container.register(OnlineStore.self) { resolver in
return MAOnlineStore()
}
container.register(OnlineAction.self) { resolver in
return MAOnlineAction(
store: resolver.resolve(OnlineStore.self)!,
service: resolver.resolve(OnlineService.self)!
)
}
// MARK: Domain Model
container.register(OnlineService.self) { resolver in
return MAOnlineService(
coordinator: resolver.resolve(OnlineCoordinator.self)!
)
}
container.register(OnlineCoordinator.self) { resolver in
return MAOnlineCoordinator()
}.initCompleted { [weak self] resolver, coordinator in
let coordinator = coordinator as! MAOnlineCoordinator
coordinator.sourceController = resolver.resolve(UINavigationController.self)?.viewControllers.first as? OnlineViewController
let searchModule = self?.parent?.searchModule
coordinator.getSearchController = { searchModule?.container.resolve(SearchViewController.self) }
}
}
private func setupMenu(_ controller: OnlineViewController) {
let menuColor = UIColor(withIntWhite: 250)
controller.settings.style.buttonBarBackgroundColor = menuColor
controller.settings.style.selectedBarBackgroundColor = .main
controller.settings.style.selectedBarHeight = 3
controller.settings.style.buttonBarBackgroundColor = menuColor
controller.settings.style.buttonBarItemFont = UIFont(name: "AvenirNext-Medium", size: 15)!
controller.settings.style.buttonBarItemTitleColor = .text
controller.buttonBarItemSpec = .cellClass { _ in 80 }
controller.changeCurrentIndexProgressive = { oldCell, newCell, progressPercentage, changeCurrentIndex, animated in
guard changeCurrentIndex == true else { return }
newCell?.label.textColor = .main
oldCell?.label.textColor = .text
newCell?.imageView?.tintColor = .main
oldCell?.imageView?.tintColor = .text
let startScale: CGFloat = 0.9
let endScale: CGFloat = 1.1
if animated {
UIView.animate(withDuration: 0.1) {
newCell?.layer.transform = CATransform3DMakeScale(endScale, endScale, 1)
oldCell?.layer.transform = CATransform3DMakeScale(startScale, startScale, 1)
}
} else {
newCell?.layer.transform = CATransform3DMakeScale(endScale, endScale, 1)
oldCell?.layer.transform = CATransform3DMakeScale(startScale, startScale, 1)
}
}
controller.edgesForExtendedLayout = []
}
}
|
mit
|
2253ffab7ae14d36fc3ec47e3a539d5d
| 42.327434 | 174 | 0.610703 | 5.557321 | false | false | false | false |
ArthurKK/ZLSwipeableViewSwift
|
ZLSwipeableViewSwiftDemo/Pods/Cartography/Cartography/LayoutProxy.swift
|
15
|
4545
|
//
// LayoutProxy.swift
// Cartography
//
// Created by Robert Böhnke on 17/06/14.
// Copyright (c) 2014 Robert Böhnke. All rights reserved.
//
import Foundation
public class LayoutProxy {
/// The width of the view.
public let width: Dimension
/// The height of the view.
public let height: Dimension
/// The size of the view. This property affects both `width` and `height`.
public let size: Size
/// The top edge of the view.
public let top: Edge
/// The right edge of the view.
public let right: Edge
/// The bottom edge of the view.
public let bottom: Edge
/// The left edge of the view.
public let left: Edge
/// All edges of the view. This property affects `top`, `bottom`, `leading`
/// and `trailing`.
public let edges: Edges
/// The leading edge of the view.
public let leading: Edge
/// The trailing edge of the view.
public let trailing: Edge
/// The horizontal center of the view.
public let centerX: Edge
/// The vertical center of the view.
public let centerY: Edge
/// The center point of the view. This property affects `centerX` and
/// `centerY`.
public let center: Point
/// The baseline of the view.
public let baseline: Edge
#if os(iOS)
/// The first baseline of the view. iOS exclusive.
public let firstBaseline: Edge
/// The left margin of the view. iOS exclusive.
public let leftMargin: Edge
/// The right margin of the view. iOS exclusive.
public let rightMargin: Edge
/// The top margin of the view. iOS exclusive.
public let topMargin: Edge
/// The bottom margin of the view. iOS exclusive.
public let bottomMargin: Edge
/// The leading margin of the view. iOS exclusive.
public let leadingMargin: Edge
/// The trailing margin of the view. iOS exclusive.
public let trailingMargin: Edge
/// The horizontal center within the margins of the view. iOS exclusive.
public let centerXWithinMargins: Edge
/// The vertical center within the margins of the view. iOS exclusive.
public let centerYWithinMargins: Edge
/// The center point within the margins of the view. This property affects
/// `centerXWithinMargins` and `centerYWithinMargins`. iOS exclusive.
public let centerWithinMargins: Point
#endif
internal let context: Context
internal let view: View
/// The superview of the view, if it exists.
public var superview: LayoutProxy? {
if let superview = view.superview {
return LayoutProxy(context, superview)
} else {
return nil
}
}
init(_ context: Context, _ view: View) {
self.context = context
self.view = view
width = Dimension(context, view, .Width)
height = Dimension(context, view, .Height)
size = Size(context, [
Dimension(context, view, .Width),
Dimension(context, view, .Height)
])
top = Edge(context, view, .Top)
right = Edge(context, view, .Right)
bottom = Edge(context, view, .Bottom)
left = Edge(context, view, .Left)
edges = Edges(context, [
Edge(context, view, .Top),
Edge(context, view, .Leading),
Edge(context, view, .Bottom),
Edge(context, view, .Trailing)
])
leading = Edge(context, view, .Leading)
trailing = Edge(context, view, .Trailing)
centerX = Edge(context, view, .CenterX)
centerY = Edge(context, view, .CenterY)
center = Point(context, [
Edge(context, view, .CenterX),
Edge(context, view, .CenterY)
])
baseline = Edge(context, view, .Baseline)
#if os(iOS)
firstBaseline = Edge(context, view, .FirstBaseline)
leftMargin = Edge(context, view, .LeftMargin)
rightMargin = Edge(context, view, .RightMargin)
topMargin = Edge(context, view, .TopMargin)
bottomMargin = Edge(context, view, .BottomMargin)
leadingMargin = Edge(context, view, .LeadingMargin)
trailingMargin = Edge(context, view, .TrailingMargin)
centerXWithinMargins = Edge(context, view, .CenterXWithinMargins)
centerYWithinMargins = Edge(context, view, .CenterYWithinMargins)
centerWithinMargins = Point(context, [
Edge(context, view, .CenterXWithinMargins),
Edge(context, view, .CenterYWithinMargins)
])
#endif
}
}
|
mit
|
ead6c867ce8f8f71f024ea55d6b0a0fc
| 28.121795 | 79 | 0.625798 | 4.565829 | false | false | false | false |
silt-lang/silt
|
Sources/InnerCore/ValueBehaviors.swift
|
1
|
12615
|
/// IRValueBehaviors.swift
///
/// Copyright 2019, The Silt Language Project.
///
/// This project is released under the MIT license, a copy of which is
/// available in the repository.
import LLVM
import Seismography
/// A type that provides information to extend an aggregate lowering schema for
/// a value.
///
/// Aggregate lowering is the first step in the physical lowering of an abstract
/// value to an ABI-relevant runtime value. The aggregate lowering algorithm
/// is a facility to automatically lay out a naive description of a sequence of
/// byte ranges provided to a builder object. This description is then
/// transformed and legalized into a valid layout for the given type, and used
/// to guide the ABI conventions for the value.
///
/// A size range may either be associated with a concrete `IRType`, in which
/// case the size of the range must match the size of the type, or an
/// opaque size range.
protocol Aggregable {
/// Append a proposed storage range describing a possible runtime layout
/// for this value.
///
/// - Parameters:
/// - IGM: The IR Builder for the current module.
/// - builder: The aggregate lowering builder.
/// - offset: The next available offset. For aggregate structures, this
/// value should be adjusted forward for each member.
func buildAggregateLowering(_ IGM: IRGenModule,
_ builder: AggregateLowering.Builder,
_ offset: Size)
}
/// A type that provides a custom assign-with-copy operation.
protocol Assignable {
/// Copy a value out of an object and into another, destroying the old value
/// in the destination.
///
/// - Parameters:
/// - IGF: The IR Builder for the current function.
/// - destination: The address of the destination value.
/// - source: The addreses of the source value.
/// - type: The type of the value at the source.
func assignWithCopy(_ IGF: IRGenFunction,
_ destination: Address, _ source: Address,
_ type: GIRType)
}
/// A type that provides a custom destruction mechanism for a value.
protocol Destroyable {
/// A custom destruction function for a value at the given address. The type
/// of the value is provided to aid dynamic deallocation routines.
///
/// Trivial values and POD values of trivial values should override this
/// function and provide a no-op implementation.
///
/// - Parameters:
/// - IGF: The IR Builder for the current function.
/// - address: The address of a value to destroy.
/// - type: The type of the value to destroy.
func destroy(_ IGF: IRGenFunction, _ address: Address, _ type: GIRType)
}
/// A type that provides information to extend an explosion schema for a value.
///
/// An `Explodable` type must be able to append a profile of its structure to
/// the given builder, or delegate the responsibility to its fields.
protocol Explodable {
/// Append an explosion schema describing the structure of this value to the
/// given builder.
///
/// - Parameter builder: The explosion schema builder.
func buildExplosionSchema(_ builder: Explosion.Schema.Builder)
}
/// A type that has a fully-exposed concrete representation. Because its
/// representation is explicitly known, directly loading and storing this value
/// into member is always a legal operation.
protocol Loadable {
/// Computes and returns the size of an explosion for this value.
///
/// - NOTE: This operation should avoid recomputing the explosion schema.
func explosionSize() -> Int
/// Initialize a given address with the values from an explosion.
///
/// - Parameters:
/// - IGF: The IR Builder for the current function.
/// - source: The explosion containing the source values.
/// - address: The address of the value to initialize.
func initialize(_ IGF: IRGenFunction, _ source: Explosion, _ address: Address)
/// Assign a set of exploded values into an address. The values are
/// consumed out of the explosion.
///
/// - Parameters:
/// - IGF: The IR Builder for the current function.
/// - source: The explosion containing the source values.
/// - destination: The address of the value to initialize.
func assign(_ IGF: IRGenFunction, _ source: Explosion, _ destination: Address)
/// Shift values from the source explosion to the destination explosion as
/// if by copy-initialization.
///
/// - Parameters:
/// - IGF: The IR Builder for the current function.
/// - source: The explosion containing the source values.
/// - destination: The destination explosion.
func copy(_ IGF: IRGenFunction, _ source: Explosion, _ destination: Explosion)
/// Release the values contained in an explosion.
///
/// - Parameters:
/// - IGF: The IR Builder for the current function.
/// - explosion: The explosion containing the values to consume.
func consume(_ IGF: IRGenFunction, _ explosion: Explosion)
/// Load an values from an address into an explosion value as if by
/// copy-initialization.
///
/// - Parameters:
/// - IGF: The IR Builder for the current function.
/// - source: The address containing the value(s) to load.
/// - destination: The destination explosion.
func loadAsCopy(_ IGF: IRGenFunction,
_ source: Address, _ destination: Explosion)
/// Load an values from an address into an explosion value as if by
/// take-initialization.
///
/// - Parameters:
/// - IGF: The IR Builder for the current function.
/// - source: The address containing the value(s) to load.
/// - destination: The destination explosion.
func loadAsTake(_ IGF: IRGenFunction,
_ source: Address, _ destination: Explosion)
/// Pack the source explosion into a data type payload destination.
///
/// - Parameters:
/// - IGF: The IR Builder for the current function.
/// - payload: The payload into which the value will be packed.
/// - source: The explosion containing the set of values to store.
/// - offset: The offset at which to pack the value.
func packIntoPayload(_ IGF: IRGenFunction,
_ payload: Payload, _ source: Explosion, _ offset: Size)
/// Unpack values from a data type payload into a destination explosion.
///
/// - Parameters:
/// - IGF: The IR Builder for the current function.
/// - payload: The payload from which the value will be unpacked.
/// - destination: The destination explosion.
/// - offset: The offset at which to unpack the value.
func unpackFromPayload(_ IGF: IRGenFunction,
_ payload: Payload, _ destination: Explosion,
_ offset: Size)
/// Consume a bunch of values which have exploded at one explosion
/// level and produce them at another.
///
/// Essentially, this is like take-initializing the new explosion.
///
/// - Parameters:
/// - IGF: The IR Builder for the current function.
/// - source: The source explosion.
/// - destination: The destination explosion.
func reexplode(_ IGF: IRGenFunction,
_ source: Explosion, _ destination: Explosion)
}
/// A type that provides custom stack allocation and deallocation routines.
protocol StackAllocatable {
/// Allocate a value of this type on the stack.
///
/// - Parameters:
/// - IGF: The IR Builder for the current function.
/// - type: The type of the value to allocate.
/// - Returns: The stack address of the allocation.
func allocateStack(_ IGF: IRGenFunction, _ type: GIRType) -> StackAddress
/// Deallocate a value of this type that is resident on the stack.
///
/// - Parameters:
/// - IGF: The IR Builder for the current function.
/// - address: The stack address of the value to deallocate.
/// - type: The type of the value to deallocate.
func deallocateStack(_ IGF: IRGenFunction,
_ address: StackAddress, _ type: GIRType)
}
/// A type that provides a way to query whether it is a "plain old data" value.
///
/// A POD type does not require further action to copy, move, or destroy it or
/// its fields.
protocol PODable {
/// Returns `true` if the described type is a "plain old data" type, `false`
/// otherwise.
var isPOD: Bool { get }
}
extension PODable {
var isPOD: Bool {
return false
}
}
/// A type that provides access to an underlying data type strategy describing
/// its concrete implementation.
///
/// `Strategizable` types generally defer the implementation of their protocol
/// requirements to their underlying strategy.
protocol Strategizable {
var strategy: DataTypeStrategy { get }
}
extension Strategizable {
func buildExplosionSchema(_ schema: Explosion.Schema.Builder) {
self.strategy.buildExplosionSchema(schema)
}
}
/// A type that provides custom retain and release functions for one or more
/// scalar values. The type should essentially be thought of as a single
/// scalar value.
protocol Scalarizable {
/// Compute whether the underlying type is a "Plain Old Data" type.
///
/// POD types have trivial representations and require no effort to copy,
/// move, retain, release, or destroy. Returning `true` from the accessor
/// opts-in to those optimizations in the default implementations of many
/// scalar `TypeInfo` requirements.
static var isPOD: Bool { get }
/// Emit an operation to "retain" a given value.
///
/// For non-reference-typed scalar values, this operation is a no-op. For
/// scalar values that are references, this may cause a reference count
/// increase.
///
/// - Parameters:
/// - IGF: The IR Builder for the current function.
/// - value: The value to retain.
func emitScalarRetain(_ IGF: IRGenFunction, _ value: IRValue)
/// Emit an operation to "release" a given value.
///
/// For non-reference-typed scalar values, this operation is a no-op. For
/// scalar values that are references, this may cause a reference count
/// decrease.
///
/// - Parameters:
/// - IGF: The IR Builder for the current function.
/// - value: The value to release.
func emitScalarRelease(_ IGF: IRGenFunction, _ value: IRValue)
}
extension Scalarizable {
var isPOD: Bool {
return type(of: self).isPOD
}
}
/// A refinement of the `Scalarizable` for values with
/// a single scalar as their underlying representation.
protocol SingleScalarizable: Scalarizable { }
extension SingleScalarizable {
func assign(_ IGF: IRGenFunction, _ src: Explosion, _ dest: Address) {
// Grab the old value if we need to.
var oldValue: IRValue?
if !type(of: self).isPOD {
oldValue = IGF.B.createLoad(dest, name: "oldValue")
}
// Store.
let newValue = src.claimSingle()
IGF.B.buildStore(newValue, to: dest.address)
// Release the old value if we need to.
if let valToRelease = oldValue {
self.emitScalarRelease(IGF, valToRelease)
}
}
func emitScalarRetain(_ IGF: IRGenFunction, _ value: IRValue) {
guard !type(of: self).isPOD else {
return
}
IGF.GR.emitRetain(value)
}
func emitScalarRelease(_ IGF: IRGenFunction, _ value: IRValue) {
guard !type(of: self).isPOD else {
return
}
IGF.GR.emitRelease(value)
}
}
protocol FixedHeapLayout {
var layout: RecordLayout { get }
}
extension FixedHeapLayout {
func allocate(_ IGF: IRGenFunction, _ boxedType: GIRType) -> OwnedAddress {
// Allocate a new object using the layout.
let boxDescriptor = IGF.IGM.addressOfBoxDescriptor(for: boxedType)
let allocation = IGF.GR.emitUnmanagedAlloc(self.layout, boxDescriptor)
let rawAddr = project(IGF, allocation, boxedType)
return OwnedAddress(rawAddr, allocation)
}
func deallocate(_ IGF: IRGenFunction, _ box: IRValue, _ boxedType: GIRType) {
let size = layout.emitSize(IGF.IGM)
let alignMask = layout.emitAlignMask(IGF.IGM)
IGF.GR.emitDeallocUninitializedObject(box, size, alignMask)
}
func project(_ IGF: IRGenFunction,
_ box: IRValue, _ boxedType: GIRType) -> Address {
let asBox = layout.emitCastTo(IGF, box, "")
let rawAddr = layout.fieldLayouts[0].project(IGF, asBox, "", nil)
let ti = IGF.getTypeInfo(boxedType)
let ptrTy = PointerType(pointee: ti.llvmType)
return IGF.B.createPointerBitCast(of: rawAddr, to: ptrTy)
}
}
protocol DynamicOffsets {
func offsetForIndex(_ IGF: IRGenFunction, _ index: Int) -> IRValue
}
protocol DynamicOffsetable {
func dynamicOffsets(_ IGF: IRGenFunction, _ T: GIRType) -> DynamicOffsets?
}
|
mit
|
8db5087c6772f99f37f3a3c6a12a19fa
| 36.433234 | 80 | 0.679191 | 4.258947 | false | false | false | false |
fuku2014/spritekit-original-game
|
src/scenes/rooms/RoomsScene.swift
|
1
|
8691
|
//
// RoomsScene.swift
// あるきスマホ
//
// Created by admin on 2016/03/13.
// Copyright © 2016年 m.fukuzawa. All rights reserved.
//
import UIKit
import SpriteKit
import NCMB
import Moscapsule
class RoomsScene: SKScene, TopBtnDelegate, RefreshBtnDelegate, CreateRoomBtnDelegate, RoomEnterDelegate {
var rooms : [Room] = []
var mqttConfig : MQTTConfig!
var mqttClient : MQTTClient!
override func didMoveToView(view: SKView) {
// 背景のセット
let back = SKSpriteNode(imageNamed:"rooms_back")
back.xScale = self.size.width/back.size.width
back.yScale = self.size.height/back.size.height
back.position = CGPointMake(CGRectGetMidX(self.frame),CGRectGetMidY(self.frame));
back.zPosition = 0
self.addChild(back)
// ラベル
let strLabel : SKLabelNode = SKLabelNode(fontNamed: "serif")
strLabel.text = "他の人とリアルタイムで遊べるモードです。"
strLabel.fontColor = UIColor.blueColor()
strLabel.fontSize = 15
strLabel.position = CGPointMake(CGRectGetMidX(self.frame),self.size.height * 0.9)
strLabel.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Center
strLabel.zPosition = 1
self.addChild(strLabel)
// トップ
let top : TopBtn = TopBtn(imageNamed: "Top")
top.userInteractionEnabled = true
top.position = CGPointMake(self.size.width * 0.2, self.size.height * 0.1)
top.delegate = self
top.xScale = 1 / 2
top.yScale = 1 / 2
top.zPosition = 1
self.addChild(top)
// 更新
let refreshBtn : RefreshBtn = RefreshBtn(imageNamed: "Refresh")
refreshBtn.userInteractionEnabled = true
refreshBtn.position = CGPointMake(self.size.width * 0.8, self.size.height * 0.1)
refreshBtn.delegate = self
refreshBtn.xScale = 1 / 2
refreshBtn.yScale = 1 / 2
refreshBtn.zPosition = 1
self.addChild(refreshBtn)
// 作成
let createRoom : CreateRoomBtn = CreateRoomBtn()
createRoom.userInteractionEnabled = true
createRoom.position = CGPointMake(CGRectGetMidX(self.frame), self.size.height * 0.8)
createRoom.delegate = self
createRoom.zPosition = 1
self.addChild(createRoom)
self.mqttInit()
}
func mqttInit() {
let username = NCMBUser.currentUser().userName + "room"
let host = MqttServerInfo.shared.domain
let port = MqttServerInfo.shared.port
let mqttUser = MqttServerInfo.shared.user
let mqttPw = MqttServerInfo.shared.password
mqttConfig = MQTTConfig(clientId: username, host: host, port: Int32(port), keepAlive: 60)
mqttConfig.mqttAuthOpts = MQTTAuthOpts(username: mqttUser, password: mqttPw)
mqttConfig.cleanSession = true
// メッセージ受信
mqttConfig.onMessageCallback = { mqttMessage in
let userName : String = mqttMessage.payloadString!
let topic : String = mqttMessage.topic
if topic == "left" {
dispatch_async(dispatch_get_main_queue(), {
self.removeRoom(userName)
})
} else if topic == "waiting/" + NCMBUser.currentUser().userName {
dispatch_async(dispatch_get_main_queue(), {
self.addRoom(userName)
})
} else if topic == "ready/" + NCMBUser.currentUser().userName {
dispatch_async(dispatch_get_main_queue(), {
self.readyForBattle(userName)
})
}
}
mqttClient = MQTT.newConnection(mqttConfig)
let topic = "waiting/" + NCMBUser.currentUser().userName
mqttClient.subscribe(topic , qos: 2)
let topicWill = "left"
mqttClient.subscribe(topicWill , qos: 2)
let topicReady = "ready/" + NCMBUser.currentUser().userName
mqttClient.subscribe(topicReady , qos: 2)
}
func addRoom(userName : String) {
if self.rooms.count >= 3 {
return
}
let query : NCMBQuery = NCMBUser.query()
query.whereKey("userName", equalTo: userName)
let user : NCMBUser = try! query.getFirstObject() as! NCMBUser
// user name
let labelUserName = SKLabelNode(fontNamed: "Chalkduster")
labelUserName.text = " VS " + (user.objectForKey("myName") as? String)!
labelUserName.fontColor = UIColor.blackColor()
labelUserName.fontSize = 25
labelUserName.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Left
labelUserName.verticalAlignmentMode = SKLabelVerticalAlignmentMode.Center
// user image
let data = NSData(contentsOfURL: NSURL (string: NCMBConfig.FILE_URL + user.userName)!)
let userAvater = data == nil ? UIImage(named: "manAvatar.png") : UIImage(data: data!)
let imgUserAvater = SKSpriteNode(texture: SKTexture(image: userAvater!))
// room
let roomNode = Room()
roomNode.name = user.userName
roomNode.userInteractionEnabled = true
roomNode.delegate = self
roomNode.zPosition = 1
labelUserName.position = CGPointMake(-roomNode.frame.size.width / 2 + 5 , CGRectGetMidY(roomNode.frame))
imgUserAvater.position = CGPointMake(roomNode.frame.size.width / 2 - imgUserAvater.frame.size.width / 2 - 5, CGRectGetMidY(roomNode.frame))
roomNode.addChild(labelUserName)
roomNode.addChild(imgUserAvater)
self.rooms.append(roomNode)
renderRooms()
}
func removeRoom(userName : String) {
let targetRoom = rooms.filter({(room : Room) -> Bool in
return room.name == userName
}).first
if (targetRoom != nil) {
targetRoom!.removeFromParent()
let foundIndex = rooms.indexOf(targetRoom!)
rooms.removeAtIndex(foundIndex!)
}
}
func fetchRooms() {
let topic = "rooms"
let msg = NCMBUser.currentUser().userName
mqttClient.publishString(msg, topic: topic , qos: 2, retain: false)
}
func renderRooms() {
var myHeight = self.size.height * 0.65
for room in self.rooms {
room.position = CGPointMake(CGRectGetMidX(self.frame), myHeight)
self.addChild(room)
myHeight = myHeight - self.size.height * 0.15
}
}
func goTop(){
let homeScene = HomeScene(size: self.view!.bounds.size)
self.view!.presentScene(homeScene)
let sound = SKAction.playSoundFileNamed("button.mp3", waitForCompletion: false)
homeScene.runAction(sound)
}
func refresh() {
for room in self.rooms {
room.removeFromParent()
}
self.rooms.removeAll()
self.fetchRooms()
}
func createRoom() {
let waitingScene = WaitingScene(size: self.view!.bounds.size)
waitingScene.scaleMode = SKSceneScaleMode.AspectFill;
self.view!.presentScene(waitingScene)
let sound = SKAction.playSoundFileNamed("button.mp3", waitForCompletion: false)
waitingScene.runAction(sound)
}
func enterRoom(userName: String) {
let topic = "enter/" + userName
let msg = NCMBUser.currentUser().userName
mqttClient.publishString(msg, topic: topic , qos: 2, retain: false)
}
func readyForBattle(userName: String) {
// ユーザー取得
let query : NCMBQuery = NCMBUser.query()
query.whereKey("userName", equalTo: userName)
let user : NCMBUser = try! query.getFirstObject() as! NCMBUser
// バトル画面へ移動
let battleScene = BattleScene(friend: user, size: self.view!.bounds.size)
battleScene.scaleMode = SKSceneScaleMode.AspectFill;
self.view!.presentScene(battleScene)
// BGMの再生
let vc = UIApplication.sharedApplication().keyWindow?.rootViewController! as! ViewController
vc.changeBGM(battleScene)
}
override func willMoveFromView(view: SKView) {
mqttClient.disconnect()
}
}
|
apache-2.0
|
855335e935bf7691e682b3b15a0b0fc8
| 39.169014 | 147 | 0.590463 | 4.517423 | false | false | false | false |
Piwigo/Piwigo-Mobile
|
piwigo/Supporting Files/Macros/UIViewController+AppTools.swift
|
1
|
8858
|
//
// UIViewController+AppTools.swift
// piwigo
//
// Created by Eddy Lelièvre-Berna on 13/04/2021.
// Copyright © 2021 Piwigo.org. All rights reserved.
//
import UIKit
@objc
extension UIViewController {
// MARK: - Top Most View Controller
func topMostViewController() -> UIViewController? {
// Look for the top most UIViewController
var topViewController: UIViewController? = self
while true {
if let presented = topViewController?.presentedViewController {
topViewController = presented
} else if let navController = topViewController as? UINavigationController {
topViewController = navController.topViewController
} else if let tabBarController = topViewController as? UITabBarController {
topViewController = tabBarController.selectedViewController
} else {
// Handle any other third party container in `else if` if required
break
}
}
return topViewController
}
// MARK: - MBProgressHUD
func showPiwigoHUD(withTitle title:String = "", detail:String = "",
buttonTitle:String = "", buttonTarget:UIViewController? = nil, buttonSelector:Selector? = nil,
inMode mode:MBProgressHUDMode = .indeterminate) {
DispatchQueue.main.async {
// Create the login HUD if needed
var hud = self.view.viewWithTag(loadingViewTag) as? MBProgressHUD
if hud == nil {
// Create the HUD
hud = MBProgressHUD.showAdded(to: self.view, animated: true)
hud?.tag = loadingViewTag
// Change the background view shape, style and color.
hud?.isSquare = false
hud?.animationType = MBProgressHUDAnimation.fade
hud?.backgroundView.style = MBProgressHUDBackgroundStyle.solidColor
hud?.backgroundView.color = UIColor(white: 0.0, alpha: 0.5)
hud?.contentColor = .piwigoColorText()
hud?.bezelView.color = .piwigoColorText()
hud?.bezelView.style = MBProgressHUDBackgroundStyle.solidColor
hud?.bezelView.backgroundColor = .piwigoColorCellBackground()
// Will look best, if we set a minimum size.
hud?.minSize = CGSize(width: 200.0, height: 100.0)
}
// Change mode
hud?.mode = mode
// Set title if needed
if title.count > 0 {
hud?.label.text = title
hud?.label.font = .piwigoFontNormal()
}
// Set details label if needed
if detail.count > 0 {
hud?.detailsLabel.text = detail
hud?.detailsLabel.font = .piwigoFontSmall()
}
// Set button if needed
if buttonTitle.count > 0, let target = buttonTarget, let selector = buttonSelector {
hud?.button.setTitle(buttonTitle, for: .normal)
hud?.button.addTarget(target, action:selector, for: .touchUpInside)
}
}
}
func isShowingPiwigoHUD() -> Bool {
if let _ = self.view.viewWithTag(loadingViewTag) as? MBProgressHUD {
return true
}
return false
}
func updatePiwigoHUD(withProgress progress:Float) {
DispatchQueue.main.async {
let hud = self.view.viewWithTag(loadingViewTag) as? MBProgressHUD
hud?.progress = progress
}
}
func updatePiwigoHUDwithSuccess(completion: @escaping () -> Void) {
DispatchQueue.main.async {
// Show "Completed" icon
if let hud = self.view.viewWithTag(loadingViewTag) as? MBProgressHUD {
if #available(iOS 11, *) {
// An iPod on iOS 9.3 enters an infinite loop when creating imageView
let image = UIImage(named: "completed")?.withRenderingMode(.alwaysTemplate)
let imageView = UIImageView(image: image)
hud.customView = imageView
}
hud.mode = MBProgressHUDMode.customView
hud.label.text = NSLocalizedString("completeHUD_label", comment: "Complete")
}
completion()
}
}
func hidePiwigoHUD(afterDelay delay:Int, completion: @escaping () -> Void) {
let deadlineTime = DispatchTime.now() + .milliseconds(delay)
DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
// Hide and remove the HUD
self.hidePiwigoHUD(completion: { completion() })
}
}
func hidePiwigoHUD(completion: @escaping () -> Void) {
DispatchQueue.main.async {
// Hide and remove the HUD
let hud = self.view.viewWithTag(loadingViewTag) as? MBProgressHUD
hud?.hide(animated: true)
completion()
}
}
// MARK: - Dismiss Alert Views
func dismissPiwigoError(withTitle title:String, message:String = "", errorMessage:String = "",
completion: @escaping () -> Void) {
// Prepare message
var wholeMessage = message
if errorMessage.count > 0 {
wholeMessage.append("\n(" + errorMessage + ")")
}
// Prepare actions
let dismissAction = UIAlertAction(title: NSLocalizedString("alertDismissButton", comment:"Dismiss"),
style: .cancel) { _ in completion() }
// Present alert
self.presentPiwigoAlert(withTitle: title, message: wholeMessage,
actions: [dismissAction])
}
func dismissRetryPiwigoError(withTitle title:String, message:String = "", errorMessage:String = "",
dismiss: @escaping () -> Void, retry: @escaping () -> Void) {
// Prepare message
var wholeMessage = message
if errorMessage.count > 0 {
wholeMessage.append("\n(" + errorMessage + ")")
}
// Prepare actions
let dismissAction = UIAlertAction(title: NSLocalizedString("alertDismissButton", comment:"Dismiss"),
style: .cancel) { _ in dismiss() }
let retryAction = UIAlertAction(title: NSLocalizedString("alertRetryButton", comment:"Retry"),
style: .default) { _ in retry() }
// Present alert
self.presentPiwigoAlert(withTitle: title, message: wholeMessage,
actions: [dismissAction, retryAction])
}
func cancelDismissRetryPiwigoError(withTitle title:String, message:String = "", errorMessage:String = "",
cancel: @escaping () -> Void, dismiss: @escaping () -> Void, retry: @escaping () -> Void) {
// Prepare message
var wholeMessage = message
if errorMessage.count > 0 {
wholeMessage.append("\n(" + errorMessage + ")")
}
// Prepare actions
let cancelAction = UIAlertAction(title: NSLocalizedString("alertCancelButton", comment:"Cancel"),
style: .cancel) { _ in cancel() }
let dismissAction = UIAlertAction(title: NSLocalizedString("alertDismissButton", comment:"Dismiss"),
style: .default) { _ in dismiss() }
let retryAction = UIAlertAction(title: NSLocalizedString("alertRetryButton", comment:"Retry"),
style: .default) { _ in retry() }
// Present alert
self.presentPiwigoAlert(withTitle: title, message: wholeMessage,
actions: [cancelAction, dismissAction, retryAction])
}
func presentPiwigoAlert(withTitle title:String, message:String, actions:[UIAlertAction]) {
DispatchQueue.main.async {
// Create alert view controller
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
// Add actions
for action in actions {
alert.addAction(action)
}
// Present alert
alert.view.tintColor = .piwigoColorOrange()
if #available(iOS 13.0, *) {
alert.overrideUserInterfaceStyle = AppVars.shared.isDarkPaletteActive ? .dark : .light
} else {
// Fallback on earlier versions
}
self.present(alert, animated: true) {
// Bugfix: iOS9 - Tint not fully Applied without Reapplying
alert.view.tintColor = .piwigoColorOrange()
}
}
}
}
|
mit
|
d9935d00ead16e1e54cc1024c4b00877
| 40.577465 | 117 | 0.562669 | 5.50404 | false | false | false | false |
sessionm/ios-smp-example
|
Referrals/ReferralsTableViewController.swift
|
1
|
3004
|
//
// ReferralsTableViewController.swift
// SMPExample
//
// Copyright © 2018 SessionM. All rights reserved.
//
import SessionMReferralsKit
import UIKit
class ReferralCell: UITableViewCell {
@IBOutlet var referralID: UILabel!
@IBOutlet var status: UILabel!
@IBOutlet var pendingTime: UILabel!
@IBOutlet var referee: UILabel!
@IBOutlet var email: UILabel!
@IBOutlet var phoneNumber: UILabel!
}
class ReferralsTableViewController: UITableViewController {
private var referralsManager = SMReferralsManager.instance()
private var referrals: [SMReferral] = []
@IBAction private func onRefresh(_ sender: UIRefreshControl) {
fetchReferrals()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
fetchReferrals()
}
private func fetchReferrals() {
self.refreshControl?.beginRefreshing()
referralsManager.fetchReferrals(completionHandler: { (referrals: [SMReferral]?, error: SMError?) in
if let err = error {
Util.failed(self, message: err.message)
} else if let newReferrals = referrals {
self.referrals = newReferrals
self.tableView.reloadData()
}
self.refreshControl?.endRefreshing()
})
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int { return 1 }
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return referrals.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let referral = referrals[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "ReferralCell", for: indexPath) as? ReferralCell
if let c = cell {
c.referralID.text = referral.referralID
c.status.text = SMReferral.string(from: referral.status)
c.pendingTime.text = referral.pendingTime
c.referee.text = referral.referee
c.email.text = referral.email
c.phoneNumber.text = referral.phoneNumber
c.tag = indexPath.row
}
return cell!
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destination = segue.destination as! ReferralDetailViewController
if sender is UIBarButtonItem {
destination.isAddingReferral = true
} else if sender is ReferralCell {
let cell = sender as! ReferralCell
destination.referral = referrals[cell.tag]
destination.isAddingReferral = false
}
}
@IBAction private func logout(_ sender: AnyObject) {
if let provider = SessionM.authenticationProvider() as? SessionMOAuthProvider {
provider.logOutUser { (authState, error) in
LoginViewController.loginIfNeeded(self)
}
}
}
}
|
mit
|
93d80a508f85778d1c5efb70031f9f8f
| 32.741573 | 113 | 0.651682 | 4.882927 | false | false | false | false |
cikelengfeng/HTTPIDL
|
Sources/Runtime/ResponseContent.swift
|
1
|
5626
|
//
// ResponseContent.swift
// Pods
//
// Created by 徐 东 on 2017/1/7//
//
import Foundation
public protocol ResponseContentConvertible {
init?(content: ResponseContent?)
}
public protocol ResponseContentKeyType: Hashable {
init(string: String)
}
public enum ResponseContent {
case number(value: NSNumber)
case string(value: String)
case data(value: Data, fileName: String?, mimeType: String)
case array(value: [ResponseContent])
case dictionary(value: [String: ResponseContent])
case file(value: URL, fileName: String?, mimeType: String)
}
extension Int64: ResponseContentConvertible {
public init?(content: ResponseContent?) {
guard let content = content else {
return nil
}
switch content {
case .number(let value):
self.init(truncating: value)
case .string(let value):
self.init(value)
case .array, .dictionary, .data, .file:
return nil
}
}
}
extension UInt64: ResponseContentConvertible {
public init?(content: ResponseContent?) {
guard let content = content else {
return nil
}
switch content {
case .number(let value):
self.init(truncating: value)
case .string(let value):
self.init(value)
case .array, .dictionary, .data, .file:
return nil
}
}
}
extension Int32: ResponseContentConvertible {
public init?(content: ResponseContent?) {
guard let content = content else {
return nil
}
switch content {
case .number(let value):
self.init(truncating: value)
case .string(let value):
self.init(value)
case .array, .dictionary, .data, .file:
return nil
}
}
}
extension UInt32: ResponseContentConvertible {
public init?(content: ResponseContent?) {
guard let content = content else {
return nil
}
switch content {
case .number(let value):
self.init(truncating: value)
case .string(let value):
self.init(value)
case .array, .dictionary, .data, .file:
return nil
}
}
}
extension Int: ResponseContentConvertible {
public init?(content: ResponseContent?) {
guard let content = content else {
return nil
}
switch content {
case .number(let value):
self.init(truncating: value)
case .string(let value):
self.init(value)
case .array, .dictionary, .data, .file:
return nil
}
}
}
extension UInt: ResponseContentConvertible {
public init?(content: ResponseContent?) {
guard let content = content else {
return nil
}
switch content {
case .number(let value):
self.init(truncating: value)
case .string(let value):
self.init(value)
case .array, .dictionary, .data, .file:
return nil
}
}
}
extension Bool: ResponseContentConvertible {
public init?(content: ResponseContent?) {
guard let content = content else {
return nil
}
switch content {
case .number(let value):
self.init(truncating: value)
case .array, .dictionary, .data, .string, .file:
return nil
}
}
}
extension Double: ResponseContentConvertible {
public init?(content: ResponseContent?) {
guard let content = content else {
return nil
}
switch content {
case .number(let value):
self.init(truncating: value)
case .string(let value):
self.init(value)
case .array, .dictionary, .data, .file:
return nil
}
}
}
extension String: ResponseContentConvertible {
public init?(content: ResponseContent?) {
guard let content = content else {
return nil
}
switch content {
case .number(let value):
self.init(value.stringValue)
case .string(let value):
self.init(value)
case .data(let value, _, _):
self.init(data: value, encoding: String.Encoding.utf8)
case .array, .dictionary, .file:
return nil
}
}
}
public extension Array where Element: ResponseContentConvertible {
init?(content: ResponseContent?) {
guard let content = content else {
return nil
}
switch content {
case .array(let value):
self.init(value.compactMap({
return Element(content: $0)
}))
case .dictionary, .data, .string, .number, .file:
return nil
}
}
}
extension String: ResponseContentKeyType {
public init(string: String) {
self = string
}
}
public extension Dictionary where Key: ResponseContentKeyType, Value: ResponseContentConvertible {
init?(content: ResponseContent?) {
guard let content = content else {
return nil
}
switch content {
case .dictionary(let value):
self = value.reduce([Key: Value](), { (soFar, soGood) in
guard let v = Value(content: soGood.value) else {
return soFar
}
var ret = soFar
ret[Key(string: soGood.key)] = v
return ret
})
case .array, .data, .string, .number, .file:
return nil
}
}
}
|
mit
|
5ee42b0786f177f72f8552d9dbf08f56
| 25.518868 | 98 | 0.559409 | 4.62716 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/FeatureApp/Sources/FeatureAppUI/QRCodeScanner/QRCodeScannerAdapter.swift
|
1
|
7510
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import FeatureQRCodeScannerDomain
import FeatureQRCodeScannerUI
import FeatureTransactionDomain
import FeatureTransactionUI
import PlatformKit
import PlatformUIKit
import UIComponentsKit
final class QRCodeScannerAdapter {
enum QRScannerAdapterError: Error {
case noAccountSelected
}
private let accountPickerAccountProvider: AccountPickerAccountProviding
private let navigationRouter: NavigationRouterAPI
private let payloadFactory: CryptoTargetPayloadFactoryAPI
private let qrCodeScannerRouter: QRCodeScannerRouting
private let topMostViewControllerProvider: TopMostViewControllerProviding
private var router: AccountPickerRouting?
private var accountPickerBridge: QRCodeScannerAccountPickerBridge?
private var cancellables = Set<AnyCancellable>()
init(
qrCodeScannerRouter: QRCodeScannerRouting,
payloadFactory: CryptoTargetPayloadFactoryAPI,
topMostViewControllerProvider: TopMostViewControllerProviding,
navigationRouter: NavigationRouterAPI
) {
self.qrCodeScannerRouter = qrCodeScannerRouter
self.payloadFactory = payloadFactory
self.topMostViewControllerProvider = topMostViewControllerProvider
self.navigationRouter = navigationRouter
accountPickerAccountProvider = AccountPickerAccountProvider(
singleAccountsOnly: true,
action: .send,
failSequence: false
)
}
}
extension QRCodeScannerAdapter: QRCodeScannerLinkerAPI {
func presentQRCodeScanner(
account: CryptoAccount,
completion: @escaping (Result<CryptoTargetQRCodeParserTarget, Error>) -> Void
) {
let builder = QRCodeScannerViewControllerBuilder(
types: [.cryptoTarget(sourceAccount: account)],
completed: { result in
switch result {
case .success(.cryptoTarget(let target)):
completion(.success(CryptoTargetQRCodeParserTarget(target: target)))
case .success:
completion(.failure(QRScannerError.unknown))
case .failure(let error):
completion(.failure(error))
}
}
)
guard let viewController = builder.build() else {
// No camera access, an alert will be displayed automatically.
return
}
topMostViewControllerProvider
.topMostViewController?
.present(
viewController,
animated: true
)
}
}
extension QRCodeScannerAdapter: CryptoTargetQRCodeParserAdapter {
var availableAccounts: AnyPublisher<[BlockchainAccount], QRScannerError> {
accountPickerAccountProvider
.accounts
.asPublisher()
.mapError(QRScannerError.parserError)
.eraseToAnyPublisher()
}
func presentAccountPicker(
accounts: [QRCodeParserTarget]
) -> AnyPublisher<QRCodeParserTarget, QRScannerError> {
/// Creates a QRCodeScannerAccountPickerBridge and connects its events to this Adapter.
let accountPickerBridge = QRCodeScannerAccountPickerBridge(targets: accounts)
accountPickerBridge.events
.sink { [weak self] event in
self?.handleAccountPickerBridge(event: event)
}
.store(in: &cancellables)
self.accountPickerBridge = accountPickerBridge
let builder = AccountPickerBuilder(
accountProvider: accountPickerBridge,
action: .send
)
let router = builder.build(
listener: .listener(accountPickerBridge),
navigationModel: ScreenNavigationModel.AccountPicker.modal(),
headerModel: .none
)
self.router = router
router.interactable.activate()
router.load()
let viewController = router.viewControllable.uiviewController
viewController.isModalInPresentation = true
navigationRouter.present(viewController: viewController)
return accountPickerBridge.selectedTarget
}
func create(
fromString string: String?,
account: CryptoAccount
) -> AnyPublisher<QRCodeParserTarget, QRScannerError> {
payloadFactory
.create(fromString: string, asset: account.asset)
.map { target in
QRCodeParserTarget(account: account, target: target)
}
.mapError(QRScannerError.parserError)
.eraseToAnyPublisher()
}
func createAndValidate(
fromString string: String?,
account: CryptoAccount
) -> AnyPublisher<QRCodeParserTarget, QRScannerError> {
payloadFactory
.create(fromString: string, asset: account.asset)
.map { target in
QRCodeParserTarget(account: account, target: target)
}
.mapError(QRScannerError.parserError)
.flatMap { target -> AnyPublisher<QRCodeParserTarget, QRScannerError> in
switch target {
case .bitpay(let address):
return BitPayInvoiceTarget
.make(from: address, asset: account.asset)
.map { target in
FeatureQRCodeScannerDomain
.QRCodeParserTarget
.address(account, target)
}
.mapError(QRScannerError.parserError)
.eraseToAnyPublisher()
case .address:
return .just(target)
}
}
.eraseToAnyPublisher()
}
}
extension QRCodeScannerAdapter {
private func handleAccountPickerBridge(event: QRCodeScannerAccountPickerBridge.Event) {
func dismiss(completion: (() -> Void)?) {
router?.viewControllable
.uiviewController
.dismiss(
animated: true,
completion: completion
)
}
switch event {
case .finished:
dismiss { [accountPickerBridge] in
accountPickerBridge?
.selectedTargetSubject
.send(completion: .failure(.parserError(QRScannerAdapterError.noAccountSelected)))
}
case .didSelect(let account, let receiveAddress):
dismiss { [accountPickerBridge] in
accountPickerBridge?
.selectedTargetSubject
.send(.address(account, receiveAddress))
}
}
}
}
extension CryptoTargetQRCodeParserTarget {
init(target: QRCodeParserTarget) {
switch target {
case .address(_, let address):
self = .address(address)
case .bitpay(let address):
self = .bitpay(address)
}
}
}
extension QRCodeParserTarget {
init(account: CryptoAccount, target: CryptoTargetQRCodeParserTarget) {
switch target {
case .address(let address):
self = .address(account, address)
case .bitpay(let address):
self = .bitpay(address)
}
}
var account: CryptoAccount? {
switch self {
case .bitpay:
return nil
case .address(let account, _):
return account
}
}
}
|
lgpl-3.0
|
7984597d57c45582db0be946778ea12b
| 32.977376 | 102 | 0.614063 | 5.754023 | false | false | false | false |
M2Mobi/Marky-Mark
|
markymark/Classes/Rules/Block/HeaderRule.swift
|
1
|
832
|
//
// Created by Jim van Zummeren on 22/04/16.
// Copyright (c) 2016 M2mobi. All rights reserved.
//
import Foundation
import UIKit
open class HeaderRule: RegExRule, HasLevel {
public init() {}
/// Example: # Header 1
open var expression = NSRegularExpression.expressionWithPattern("^(#{1,6}) (.*?)$")
// MARK: Rule
open func createMarkDownItemWithLines(_ lines: [String]) -> MarkDownItem {
let line = lines.first ?? ""
let content = line.subStringWithExpression(expression, ofGroup: 2)
let level = getLevel(line)
return HeaderMarkDownItem(lines: lines, content: content, level: level)
}
// MARK: Private
open func getLevel(_ string: String) -> Int {
let range = expression.rangeInString(string, forGroup: 1)
return range?.length ?? 0
}
}
|
mit
|
4bdb652330f700e8c1286a74b6d754df
| 25 | 87 | 0.644231 | 4.098522 | false | false | false | false |
muhamed-hafez/twitter-feed
|
Twitter Feed/Twitter Feed/ViewController.swift
|
1
|
6673
|
//
// ViewController.swift
// Twitter Feed
//
// Created by Muhamed Hafez on 12/16/16.
// Copyright © 2016 Muhamed Hafez. All rights reserved.
//
import UIKit
import Foundation
import Alamofire
import SVPullToRefresh
class ViewController: UIViewController, UITableViewDataSource, UISearchBarDelegate, TFTweetCellDelegate {
@IBOutlet weak var tweetTableView: UITableView!
var tweets = [TFTweet]()
var refreshTimer:Timer?
var lastQuery = TFQuery(query: "#startup")
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
initComponents()
searchForTweets()
}
func initComponents() {
self.tweetTableView.dataSource = self
self.tweetTableView.rowHeight = UITableViewAutomaticDimension
self.tweetTableView.estimatedRowHeight = 130.0
self.tweetTableView.tableFooterView = UIView()
self.tweetTableView.addPullToRefresh {
self.lastQuery.maxID = ""
self.searchForTweets()
}
self.tweetTableView.addInfiniteScrolling {
self.lastQuery.sinceID = ""
self.searchForTweets()
}
let searchBar = UISearchBar()
searchBar.sizeToFit()
searchBar.delegate = self
searchBar.autocorrectionType = .no
searchBar.autocapitalizationType = .none
searchBar.placeholder = "#hashtag_to_search"
navigationItem.titleView = searchBar
view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)))
}
func dismissKeyboard() {
let searchBar = navigationItem.titleView as? UISearchBar
searchBar?.showsCancelButton = false
searchBar?.resignFirstResponder()
}
func searchForTweets() {
let searchBar = navigationItem.titleView as? UISearchBar
searchBar?.text = lastQuery.textQuery
let header = ["Authorization": "Bearer AAAAAAAAAAAAAAAAAAAAAGypyQAAAAAAsVjOEduC%2BTXBM6imanaJSM8PSaI%3DRd7E9j1akp3SX7thVr2s3kkh5PwKxCAgYCpjelTeSxgQFXrDDz"]
let urlString = "https://api.twitter.com/1.1/search/tweets.json?" + lastQuery.constructParameters()
Alamofire.request(urlString, headers: header)
.validate()
.responseJSON {
[weak self] response in
guard let dictionary = response.result.value as? [String: AnyObject] else { return }
guard let statuses = dictionary["statuses"] as? Array<NSDictionary> else { return }
var newTweets = TFTweet.instancesFromArray(array: statuses) as! [TFTweet]
if self?.lastQuery.sinceID.isEmpty == false {
self?.tweets.insert(contentsOf: newTweets, at: 0)
self?.tweetTableView.pullToRefreshView.stopAnimating()
}
else {
if newTweets.first?.ID == self?.lastQuery.maxID {
newTweets.removeFirst()
}
self?.tweets.append(contentsOf: newTweets)
self?.tweetTableView.infiniteScrollingView.stopAnimating()
}
self?.lastQuery.sinceID = self?.tweets.first?.ID ?? ""
self?.lastQuery.maxID = self?.tweets.last?.ID ?? ""
self?.tweetTableView.reloadData()
}
}
func setRefreshRate(_ interval: Int) {
self.refreshTimer?.invalidate()
if interval > 0 {
self.refreshTimer = Timer.scheduledTimer(timeInterval: TimeInterval(interval), target: self, selector: #selector(searchForTweets), userInfo: nil, repeats: true)
}
self.tweetTableView.showsPullToRefresh = (interval == 0)
}
@IBAction func changeRefreshRate(_ sender: UIBarButtonItem) {
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let timeIntervals = [0, 2, 5, 30, 60]
timeIntervals.forEach {
interval in
var message = "No Refresh"
if interval > 0 {
message = "\(interval) Secs"
}
let refreshOption = UIAlertAction(title: message, style: .default) {
[weak self] action in
self?.setRefreshRate(interval)
}
alertController.addAction(refreshOption)
}
let cancelOption = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(cancelOption)
present(alertController, animated: true)
}
// MARK: - UITableViewDataSource methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tweets.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tweetCell", for: indexPath) as! TFTweetTableViewCell
cell.bind(tweet: tweets[indexPath.row])
cell.tapDelegate = self
return cell
}
// MARK: - UISearchBarDelegate methods
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
searchBar.text = ""
searchBar.showsCancelButton = true
return true
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.showsCancelButton = false
searchBar.resignFirstResponder()
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.showsCancelButton = false
searchBar.resignFirstResponder()
// Though, search button won't be enabled unless there is a search query
// it is good practice to check
if searchBar.text?.isEmpty == false {
lastQuery.textQuery = searchBar.text!
tweets.removeAll()
searchForTweets()
}
}
// MARK: - TFTweetCellDelegate methods
func didTap(onCell cell: UITableViewCell, atIndex index: Int) {
guard let indexPath = tweetTableView.indexPath(for: cell) else { return }
let tweet = tweets[indexPath.row]
let clickedHashtag = tweet.hashtags?.filter {
return $0.from <= index && index <= $0.to
}.first
if let hashtag = clickedHashtag {
lastQuery.textQuery = "#" + hashtag.text
tweets.removeAll()
searchForTweets()
}
}
deinit {
refreshTimer?.invalidate()
}
}
|
mit
|
bdc5b719a9f4fa06624579694df05c0e
| 34.870968 | 172 | 0.617206 | 5.062215 | false | false | false | false |
swiftmi/swiftmi-app
|
swiftmi/swiftmi/ArticleDetailController.swift
|
2
|
5975
|
//
// ArticleDetailController.swift
// swiftmi
//
// Created by yangyin on 16/2/3.
// Copyright © 2016年 swiftmi. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
import Kingfisher
class ArticleDetailController: UIViewController,UIWebViewDelegate {
@IBOutlet weak var webView: UIWebView!
var article:AnyObject?
var newArticle:JSON?
var articleId:Int?
override func viewDidLoad() {
super.viewDidLoad()
self.setViews()
// Do any additional setup after loading the view.
}
fileprivate func setViews(){
self.view.backgroundColor=UIColor.white
self.webView.backgroundColor=UIColor.clear
self.webView.delegate = self
self.startLoading()
if let art = self.article {
self.articleId = art.value(forKey: "articleId") as? Int
}
self.loadData()
}
fileprivate func GetLoadData() -> JSON {
if self.newArticle != nil {
return self.newArticle!
}
//use old data
return JSON(self.article!)
}
override func viewDidAppear(_ animated: Bool) {
self.userActivity = NSUserActivity(activityType: "com.swiftmi.handoff.view-web")
self.userActivity?.title = "view article on mac"
self.userActivity?.webpageURL = URL(string: ServiceApi.getArticlesDetail(self.articleId!))
self.userActivity?.becomeCurrent()
}
override func viewWillDisappear(_ animated: Bool) {
self.userActivity?.invalidate()
self.clearAllNotice()
}
fileprivate func loadData(){
Alamofire.request(Router.articleDetail(articleId: self.articleId!)).responseJSON{
closureResponse in
if(closureResponse.result.isFailure){
self.notice("网络异常", type: NoticeType.error, autoClear: true)
}
else {
let json = closureResponse.result.value
let result = JSON(json!)
if result["isSuc"].boolValue {
self.newArticle = result["result"]
}
}
let path=Bundle.main.path(forResource: "next", ofType: "html")
let url=NSURL.fileURL(withPath: path!)
let request = NSURLRequest(url:url)
DispatchQueue.main.async {
self.webView.loadRequest(request as URLRequest)
}
}
}
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool
{
let reqUrl=request.url!.absoluteString
var params = reqUrl.components(separatedBy: "://")
DispatchQueue.main.async(execute: {
if(params.count>=2){
if(params[0].compare("html")==ComparisonResult.orderedSame && params[1].compare("docready") == ComparisonResult.orderedSame ){
let data = self.GetLoadData()
self.webView.stringByEvaluatingJavaScript(from: "article.render("+data.rawString()!+");")
//add article to index
SplotlightHelper.AddItemToCoreSpotlight("next-\(data["articleId"].intValue)", title: data["title"].stringValue, contentDescription: data["content"].stringValue)
}
else if(params[0].compare("html")==ComparisonResult.orderedSame && params[1].compare("contentready")==ComparisonResult.orderedSame){
//doc content ok
self.stopLoading()
}
else if params[0].compare("http") == ComparisonResult.orderedSame || params[0].compare("https") == ComparisonResult.orderedSame {
let webViewController:WebViewController = Utility.GetViewController("webViewController")
webViewController.webUrl = reqUrl
self.present(webViewController, animated: true, completion: nil)
}
}
})
if params[0].compare("http") == ComparisonResult.orderedSame || params[0].compare("https") == ComparisonResult.orderedSame {
return false
}
return true;
}
fileprivate func startLoading(){
self.pleaseWait()
self.webView.isHidden=true
}
fileprivate func stopLoading(){
self.webView.isHidden=false
self.clearAllNotice()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
fileprivate func share() {
var data = GetLoadData()
let title = data["title"].stringValue
let url = ServiceApi.getArticlesShareDetail(self.articleId!)
let desc = data["desc"].stringValue
let preview = data["imageUrl"].stringValue
Utility.share(title, desc: desc, imgUrl: preview, linkUrl: url)
}
@IBAction func shareArticle(_ sender: AnyObject) {
share()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
76b086550896728feae3afc8e6cbadb5
| 29.901554 | 180 | 0.551979 | 5.615819 | false | false | false | false |
rhcad/ShapeAnimation-Swift
|
ShapeAnimation/View/ShapeView+HitTest.swift
|
3
|
2787
|
//
// ShapeView+HitTest.swift
// ShapeAnimation
//
// Created by Zhang Yungui on 2/8/15.
// Copyright (c) 2015 github.com/rhcad. All rights reserved.
//
import SwiftGraphics
public extension CALayer {
public func enumerateLayers(block:(CALayer) -> Void) {
if let sublayers = sublayers {
for layer in sublayers {
if !layer.isKindOfClass(CAGradientLayer) {
block(layer as CALayer)
}
}
}
}
}
public extension ShapeView {
public func enumerateLayers(block:(CALayer) -> Void) {
sublayer.enumerateLayers(block)
}
public func hitTest(point:CGPoint, filter:((CALayer) -> Bool)? = nil) -> CALayer? {
var ret:CALayer?
var defaultShape:CALayer?
var minFrame:CGRect!
func area(rect:CGRect) -> CGFloat { return rect.width * rect.height }
enumerateLayers { layer in
if layer.frame.contains(point) && (filter == nil || filter!(layer)) {
defaultShape = layer
if let shape = layer as? CAShapeLayer {
if shape.hitTestPath(point) {
if ret == nil || area(shape.frame) < area(minFrame) {
ret = shape
minFrame = shape.frame
}
}
}
else {
ret = layer
minFrame = layer.frame
}
}
}
return ret != nil ? ret : defaultShape
}
public func intersects(rect:CGRect, filter:((CALayer) -> Bool)? = nil) -> [CALayer] {
var ret:[CALayer] = []
enumerateLayers { layer in
if let shape = layer as? CAShapeLayer {
if shape.intersects(rect) && (filter == nil || filter!(shape)) {
ret.append(shape)
}
}
else if layer.frame.contains(rect) && (filter == nil || filter!(layer)) {
ret.append(layer)
}
}
return ret
}
}
public extension CAShapeLayer {
public var isFilled : Bool {
return path!.isClosed && (paintStyle.fillColor != nil || gradient?.colors != nil)
}
public func hitTestPath(point:CGPoint) -> Bool {
let path = isFilled ? self.path : strokingPath(max(lineWidth, 10))
var xf = affineTransform().inverted() + CGAffineTransform(translation: -position)
return CGPathContainsPoint(path, &xf, point, false)
}
public func intersects(rect:CGRect) -> Bool {
let xf = affineTransform().inverted() + CGAffineTransform(translation: -position)
return path!.intersects(rect * xf)
}
}
|
bsd-2-clause
|
1996ce7cec8f04539679df07ea24ef9f
| 30.670455 | 89 | 0.522067 | 4.691919 | false | false | false | false |
allevato/swift-protobuf
|
Sources/SwiftProtobuf/JSONDecoder.swift
|
1
|
19091
|
// Sources/SwiftProtobuf/JSONDecoder.swift - JSON format decoding
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// JSON format decoding engine.
///
// -----------------------------------------------------------------------------
import Foundation
internal struct JSONDecoder: Decoder {
internal var scanner: JSONScanner
internal var options: JSONDecodingOptions
private var fieldCount = 0
private var isMapKey = false
private var fieldNameMap: _NameMap?
mutating func handleConflictingOneOf() throws {
throw JSONDecodingError.conflictingOneOf
}
internal init(source: UnsafeBufferPointer<UInt8>, options: JSONDecodingOptions) {
self.options = options
self.scanner = JSONScanner(source: source, messageDepthLimit: self.options.messageDepthLimit)
}
private init(decoder: JSONDecoder) {
// The scanner is copied over along with the options.
scanner = decoder.scanner
options = decoder.options
}
mutating func nextFieldNumber() throws -> Int? {
if scanner.skipOptionalObjectEnd() {
return nil
}
if fieldCount > 0 {
try scanner.skipRequiredComma()
}
if let fieldNumber = try scanner.nextFieldNumber(names: fieldNameMap!) {
fieldCount += 1
return fieldNumber
}
return nil
}
mutating func decodeSingularFloatField(value: inout Float) throws {
if scanner.skipOptionalNull() {
value = 0
return
}
value = try scanner.nextFloat()
}
mutating func decodeSingularFloatField(value: inout Float?) throws {
if scanner.skipOptionalNull() {
value = nil
return
}
value = try scanner.nextFloat()
}
mutating func decodeRepeatedFloatField(value: inout [Float]) throws {
if scanner.skipOptionalNull() {
return
}
try scanner.skipRequiredArrayStart()
if scanner.skipOptionalArrayEnd() {
return
}
while true {
let n = try scanner.nextFloat()
value.append(n)
if scanner.skipOptionalArrayEnd() {
return
}
try scanner.skipRequiredComma()
}
}
mutating func decodeSingularDoubleField(value: inout Double) throws {
if scanner.skipOptionalNull() {
value = 0
return
}
value = try scanner.nextDouble()
}
mutating func decodeSingularDoubleField(value: inout Double?) throws {
if scanner.skipOptionalNull() {
value = nil
return
}
value = try scanner.nextDouble()
}
mutating func decodeRepeatedDoubleField(value: inout [Double]) throws {
if scanner.skipOptionalNull() {
return
}
try scanner.skipRequiredArrayStart()
if scanner.skipOptionalArrayEnd() {
return
}
while true {
let n = try scanner.nextDouble()
value.append(n)
if scanner.skipOptionalArrayEnd() {
return
}
try scanner.skipRequiredComma()
}
}
mutating func decodeSingularInt32Field(value: inout Int32) throws {
if scanner.skipOptionalNull() {
value = 0
return
}
let n = try scanner.nextSInt()
if n > Int64(Int32.max) || n < Int64(Int32.min) {
throw JSONDecodingError.numberRange
}
value = Int32(extendingOrTruncating: n)
}
mutating func decodeSingularInt32Field(value: inout Int32?) throws {
if scanner.skipOptionalNull() {
value = nil
return
}
let n = try scanner.nextSInt()
if n > Int64(Int32.max) || n < Int64(Int32.min) {
throw JSONDecodingError.numberRange
}
value = Int32(extendingOrTruncating: n)
}
mutating func decodeRepeatedInt32Field(value: inout [Int32]) throws {
if scanner.skipOptionalNull() {
return
}
try scanner.skipRequiredArrayStart()
if scanner.skipOptionalArrayEnd() {
return
}
while true {
let n = try scanner.nextSInt()
if n > Int64(Int32.max) || n < Int64(Int32.min) {
throw JSONDecodingError.numberRange
}
value.append(Int32(extendingOrTruncating: n))
if scanner.skipOptionalArrayEnd() {
return
}
try scanner.skipRequiredComma()
}
}
mutating func decodeSingularInt64Field(value: inout Int64) throws {
if scanner.skipOptionalNull() {
value = 0
return
}
value = try scanner.nextSInt()
}
mutating func decodeSingularInt64Field(value: inout Int64?) throws {
if scanner.skipOptionalNull() {
value = nil
return
}
value = try scanner.nextSInt()
}
mutating func decodeRepeatedInt64Field(value: inout [Int64]) throws {
if scanner.skipOptionalNull() {
return
}
try scanner.skipRequiredArrayStart()
if scanner.skipOptionalArrayEnd() {
return
}
while true {
let n = try scanner.nextSInt()
value.append(n)
if scanner.skipOptionalArrayEnd() {
return
}
try scanner.skipRequiredComma()
}
}
mutating func decodeSingularUInt32Field(value: inout UInt32) throws {
if scanner.skipOptionalNull() {
value = 0
return
}
let n = try scanner.nextUInt()
if n > UInt64(UInt32.max) {
throw JSONDecodingError.numberRange
}
value = UInt32(extendingOrTruncating: n)
}
mutating func decodeSingularUInt32Field(value: inout UInt32?) throws {
if scanner.skipOptionalNull() {
value = nil
return
}
let n = try scanner.nextUInt()
if n > UInt64(UInt32.max) {
throw JSONDecodingError.numberRange
}
value = UInt32(extendingOrTruncating: n)
}
mutating func decodeRepeatedUInt32Field(value: inout [UInt32]) throws {
if scanner.skipOptionalNull() {
return
}
try scanner.skipRequiredArrayStart()
if scanner.skipOptionalArrayEnd() {
return
}
while true {
let n = try scanner.nextUInt()
if n > UInt64(UInt32.max) {
throw JSONDecodingError.numberRange
}
value.append(UInt32(extendingOrTruncating: n))
if scanner.skipOptionalArrayEnd() {
return
}
try scanner.skipRequiredComma()
}
}
mutating func decodeSingularUInt64Field(value: inout UInt64) throws {
if scanner.skipOptionalNull() {
value = 0
return
}
value = try scanner.nextUInt()
}
mutating func decodeSingularUInt64Field(value: inout UInt64?) throws {
if scanner.skipOptionalNull() {
value = nil
return
}
value = try scanner.nextUInt()
}
mutating func decodeRepeatedUInt64Field(value: inout [UInt64]) throws {
if scanner.skipOptionalNull() {
return
}
try scanner.skipRequiredArrayStart()
if scanner.skipOptionalArrayEnd() {
return
}
while true {
let n = try scanner.nextUInt()
value.append(n)
if scanner.skipOptionalArrayEnd() {
return
}
try scanner.skipRequiredComma()
}
}
mutating func decodeSingularSInt32Field(value: inout Int32) throws {
try decodeSingularInt32Field(value: &value)
}
mutating func decodeSingularSInt32Field(value: inout Int32?) throws {
try decodeSingularInt32Field(value: &value)
}
mutating func decodeRepeatedSInt32Field(value: inout [Int32]) throws {
try decodeRepeatedInt32Field(value: &value)
}
mutating func decodeSingularSInt64Field(value: inout Int64) throws {
try decodeSingularInt64Field(value: &value)
}
mutating func decodeSingularSInt64Field(value: inout Int64?) throws {
try decodeSingularInt64Field(value: &value)
}
mutating func decodeRepeatedSInt64Field(value: inout [Int64]) throws {
try decodeRepeatedInt64Field(value: &value)
}
mutating func decodeSingularFixed32Field(value: inout UInt32) throws {
try decodeSingularUInt32Field(value: &value)
}
mutating func decodeSingularFixed32Field(value: inout UInt32?) throws {
try decodeSingularUInt32Field(value: &value)
}
mutating func decodeRepeatedFixed32Field(value: inout [UInt32]) throws {
try decodeRepeatedUInt32Field(value: &value)
}
mutating func decodeSingularFixed64Field(value: inout UInt64) throws {
try decodeSingularUInt64Field(value: &value)
}
mutating func decodeSingularFixed64Field(value: inout UInt64?) throws {
try decodeSingularUInt64Field(value: &value)
}
mutating func decodeRepeatedFixed64Field(value: inout [UInt64]) throws {
try decodeRepeatedUInt64Field(value: &value)
}
mutating func decodeSingularSFixed32Field(value: inout Int32) throws {
try decodeSingularInt32Field(value: &value)
}
mutating func decodeSingularSFixed32Field(value: inout Int32?) throws {
try decodeSingularInt32Field(value: &value)
}
mutating func decodeRepeatedSFixed32Field(value: inout [Int32]) throws {
try decodeRepeatedInt32Field(value: &value)
}
mutating func decodeSingularSFixed64Field(value: inout Int64) throws {
try decodeSingularInt64Field(value: &value)
}
mutating func decodeSingularSFixed64Field(value: inout Int64?) throws {
try decodeSingularInt64Field(value: &value)
}
mutating func decodeRepeatedSFixed64Field(value: inout [Int64]) throws {
try decodeRepeatedInt64Field(value: &value)
}
mutating func decodeSingularBoolField(value: inout Bool) throws {
if scanner.skipOptionalNull() {
value = false
return
}
if isMapKey {
value = try scanner.nextQuotedBool()
} else {
value = try scanner.nextBool()
}
}
mutating func decodeSingularBoolField(value: inout Bool?) throws {
if scanner.skipOptionalNull() {
value = nil
return
}
if isMapKey {
value = try scanner.nextQuotedBool()
} else {
value = try scanner.nextBool()
}
}
mutating func decodeRepeatedBoolField(value: inout [Bool]) throws {
if scanner.skipOptionalNull() {
return
}
try scanner.skipRequiredArrayStart()
if scanner.skipOptionalArrayEnd() {
return
}
while true {
let n = try scanner.nextBool()
value.append(n)
if scanner.skipOptionalArrayEnd() {
return
}
try scanner.skipRequiredComma()
}
}
mutating func decodeSingularStringField(value: inout String) throws {
if scanner.skipOptionalNull() {
value = String()
return
}
value = try scanner.nextQuotedString()
}
mutating func decodeSingularStringField(value: inout String?) throws {
if scanner.skipOptionalNull() {
value = nil
return
}
value = try scanner.nextQuotedString()
}
mutating func decodeRepeatedStringField(value: inout [String]) throws {
if scanner.skipOptionalNull() {
return
}
try scanner.skipRequiredArrayStart()
if scanner.skipOptionalArrayEnd() {
return
}
while true {
let n = try scanner.nextQuotedString()
value.append(n)
if scanner.skipOptionalArrayEnd() {
return
}
try scanner.skipRequiredComma()
}
}
mutating func decodeSingularBytesField(value: inout Data) throws {
if scanner.skipOptionalNull() {
value = Internal.emptyData
return
}
value = try scanner.nextBytesValue()
}
mutating func decodeSingularBytesField(value: inout Data?) throws {
if scanner.skipOptionalNull() {
value = nil
return
}
value = try scanner.nextBytesValue()
}
mutating func decodeRepeatedBytesField(value: inout [Data]) throws {
if scanner.skipOptionalNull() {
return
}
try scanner.skipRequiredArrayStart()
if scanner.skipOptionalArrayEnd() {
return
}
while true {
let n = try scanner.nextBytesValue()
value.append(n)
if scanner.skipOptionalArrayEnd() {
return
}
try scanner.skipRequiredComma()
}
}
mutating func decodeSingularEnumField<E: Enum>(value: inout E?) throws
where E.RawValue == Int {
if scanner.skipOptionalNull() {
value = nil
return
}
value = try scanner.nextEnumValue() as E
}
mutating func decodeSingularEnumField<E: Enum>(value: inout E) throws
where E.RawValue == Int {
if scanner.skipOptionalNull() {
value = E()
return
}
value = try scanner.nextEnumValue()
}
mutating func decodeRepeatedEnumField<E: Enum>(value: inout [E]) throws
where E.RawValue == Int {
if scanner.skipOptionalNull() {
return
}
try scanner.skipRequiredArrayStart()
if scanner.skipOptionalArrayEnd() {
return
}
while true {
let e: E = try scanner.nextEnumValue()
value.append(e)
if scanner.skipOptionalArrayEnd() {
return
}
try scanner.skipRequiredComma()
}
}
internal mutating func decodeFullObject<M: Message>(message: inout M) throws {
guard let nameProviding = (M.self as? _ProtoNameProviding.Type) else {
throw JSONDecodingError.missingFieldNames
}
fieldNameMap = nameProviding._protobuf_nameMap
if let m = message as? _CustomJSONCodable {
var customCodable = m
try customCodable.decodeJSON(from: &self)
message = customCodable as! M
} else {
try scanner.skipRequiredObjectStart()
if scanner.skipOptionalObjectEnd() {
return
}
try message.decodeMessage(decoder: &self)
}
}
mutating func decodeSingularMessageField<M: Message>(value: inout M?) throws {
if scanner.skipOptionalNull() {
if M.self is _CustomJSONCodable.Type {
value =
try (M.self as! _CustomJSONCodable.Type).decodedFromJSONNull() as? M
return
}
// All other message field types treat 'null' as an unset
value = nil
return
}
if value == nil {
value = M()
}
var subDecoder = JSONDecoder(decoder: self)
try subDecoder.decodeFullObject(message: &value!)
assert(scanner.recursionBudget == subDecoder.scanner.recursionBudget)
scanner = subDecoder.scanner
}
mutating func decodeRepeatedMessageField<M: Message>(
value: inout [M]
) throws {
if scanner.skipOptionalNull() {
return
}
try scanner.skipRequiredArrayStart()
if scanner.skipOptionalArrayEnd() {
return
}
while true {
if scanner.skipOptionalNull() {
var appended = false
if M.self is _CustomJSONCodable.Type {
if let message = try (M.self as! _CustomJSONCodable.Type)
.decodedFromJSONNull() as? M {
value.append(message)
appended = true
}
}
if !appended {
throw JSONDecodingError.illegalNull
}
} else {
var message = M()
var subDecoder = JSONDecoder(decoder: self)
try subDecoder.decodeFullObject(message: &message)
value.append(message)
assert(scanner.recursionBudget == subDecoder.scanner.recursionBudget)
scanner = subDecoder.scanner
}
if scanner.skipOptionalArrayEnd() {
return
}
try scanner.skipRequiredComma()
}
}
mutating func decodeSingularGroupField<G: Message>(value: inout G?) throws {
throw JSONDecodingError.schemaMismatch
}
mutating func decodeRepeatedGroupField<G: Message>(value: inout [G]) throws {
throw JSONDecodingError.schemaMismatch
}
mutating func decodeMapField<KeyType, ValueType: MapValueType>(
fieldType: _ProtobufMap<KeyType, ValueType>.Type,
value: inout _ProtobufMap<KeyType, ValueType>.BaseType
) throws {
if scanner.skipOptionalNull() {
return
}
try scanner.skipRequiredObjectStart()
if scanner.skipOptionalObjectEnd() {
return
}
while true {
// Next character must be double quote, because
// map keys must always be quoted strings.
let c = try scanner.peekOneCharacter()
if c != "\"" {
throw JSONDecodingError.unquotedMapKey
}
isMapKey = true
var keyField: KeyType.BaseType?
try KeyType.decodeSingular(value: &keyField, from: &self)
isMapKey = false
try scanner.skipRequiredColon()
var valueField: ValueType.BaseType?
try ValueType.decodeSingular(value: &valueField, from: &self)
if let keyField = keyField, let valueField = valueField {
value[keyField] = valueField
} else {
throw JSONDecodingError.malformedMap
}
if scanner.skipOptionalObjectEnd() {
return
}
try scanner.skipRequiredComma()
}
}
mutating func decodeMapField<KeyType, ValueType>(
fieldType: _ProtobufEnumMap<KeyType, ValueType>.Type,
value: inout _ProtobufEnumMap<KeyType, ValueType>.BaseType
) throws where ValueType.RawValue == Int {
if scanner.skipOptionalNull() {
return
}
try scanner.skipRequiredObjectStart()
if scanner.skipOptionalObjectEnd() {
return
}
while true {
// Next character must be double quote, because
// map keys must always be quoted strings.
let c = try scanner.peekOneCharacter()
if c != "\"" {
throw JSONDecodingError.unquotedMapKey
}
isMapKey = true
var keyField: KeyType.BaseType?
try KeyType.decodeSingular(value: &keyField, from: &self)
isMapKey = false
try scanner.skipRequiredColon()
var valueField: ValueType?
try decodeSingularEnumField(value: &valueField)
if let keyField = keyField, let valueField = valueField {
value[keyField] = valueField
} else {
throw JSONDecodingError.malformedMap
}
if scanner.skipOptionalObjectEnd() {
return
}
try scanner.skipRequiredComma()
}
}
mutating func decodeMapField<KeyType, ValueType>(
fieldType: _ProtobufMessageMap<KeyType, ValueType>.Type,
value: inout _ProtobufMessageMap<KeyType, ValueType>.BaseType
) throws {
if scanner.skipOptionalNull() {
return
}
try scanner.skipRequiredObjectStart()
if scanner.skipOptionalObjectEnd() {
return
}
while true {
// Next character must be double quote, because
// map keys must always be quoted strings.
let c = try scanner.peekOneCharacter()
if c != "\"" {
throw JSONDecodingError.unquotedMapKey
}
isMapKey = true
var keyField: KeyType.BaseType?
try KeyType.decodeSingular(value: &keyField, from: &self)
isMapKey = false
try scanner.skipRequiredColon()
var valueField: ValueType?
try decodeSingularMessageField(value: &valueField)
if let keyField = keyField, let valueField = valueField {
value[keyField] = valueField
} else {
throw JSONDecodingError.malformedMap
}
if scanner.skipOptionalObjectEnd() {
return
}
try scanner.skipRequiredComma()
}
}
mutating func decodeExtensionField(
values: inout ExtensionFieldValueSet,
messageType: Message.Type,
fieldNumber: Int
) throws {
throw JSONDecodingError.schemaMismatch
}
}
|
apache-2.0
|
f823a0985d5be89ef0ee712d81088d75
| 26.272857 | 97 | 0.658059 | 4.439767 | false | false | false | false |
ryanbooker/SwiftCheck
|
SwiftCheckTests/LambdaSpec.swift
|
1
|
4376
|
//
// LambdaSpec.swift
// SwiftCheck
//
// Created by Robert Widmann on 1/6/16.
// Copyright © 2016 Robert Widmann. All rights reserved.
//
import SwiftCheck
struct Name : Arbitrary, Equatable, Hashable, CustomStringConvertible {
let unName : String
static var arbitrary : Gen<Name> {
let gc : Gen<Character> = Gen<Character>.fromElementsIn("a"..."z")
return gc.map { Name(unName: String($0)) }
}
var description : String {
return self.unName
}
var hashValue : Int {
return self.unName.hashValue
}
}
func == (l : Name, r : Name) -> Bool {
return l.unName == r.unName
}
private func liftM2<A, B, C>(f : (A, B) -> C, _ m1 : Gen<A>, _ m2 : Gen<B>) -> Gen<C> {
return m1.flatMap { x1 in
return m2.flatMap { x2 in
return Gen.pure(f(x1, x2))
}
}
}
indirect enum Exp : Equatable {
case Lam(Name, Exp)
case App(Exp, Exp)
case Var(Name)
}
func == (l : Exp, r : Exp) -> Bool {
switch (l, r) {
case let (.Lam(ln, le), .Lam(rn, re)):
return ln == rn && le == re
case let (.App(ln, le), .App(rn, re)):
return ln == rn && le == re
case let (.Var(n1), .Var(n2)):
return n1 == n2
default:
return false
}
}
extension Exp : Arbitrary {
private static func arbExpr(n : Int) -> Gen<Exp> {
return Gen<Exp>.frequency([
(2, liftM(Exp.Var, Name.arbitrary)),
] + ((n <= 0) ? [] : [
(5, liftM2(Exp.Lam, Name.arbitrary, arbExpr(n.predecessor()))),
(5, liftM2(Exp.App, arbExpr(n/2), arbExpr(n/2))),
]))
}
static var arbitrary : Gen<Exp> {
return Gen<Exp>.sized(self.arbExpr)
}
static func shrink(e : Exp) -> [Exp] {
switch e {
case .Var(_):
return []
case let .Lam(x, a):
return [a] + Exp.shrink(a).map { .Lam(x, $0) }
case let .App(a, b):
let part1 : [Exp] = [a, b]
+ [a].flatMap({ (expr : Exp) -> Exp? in
if case let .Lam(x, a) = expr {
return a.subst(x, b)
}
return nil
})
let part2 : [Exp] = Exp.shrink(a).map { App($0, b) }
+ Exp.shrink(b).map { App(a, $0) }
return part1 + part2
}
}
var free : Set<Name> {
switch self {
case let .Var(x):
return Set([x])
case let .Lam(x, a):
return a.free.subtract([x])
case let .App(a, b):
return a.free.union(b.free)
}
}
func rename(x : Name, _ y : Name) -> Exp {
if x == y {
return self
}
return self.subst(x, .Var(y))
}
func subst(x : Name, _ c : Exp) -> Exp {
switch self {
case let .Var(y) where x == y :
return c
case let .Lam(y, a) where x != y:
return .Lam(y, a.subst(x, c))
case let .App(a, b):
return .App(a.subst(x, c), b.subst(x, c))
default:
return self
}
}
var eval : Exp {
switch self {
case .Var(_):
fatalError("Cannot evaluate free variable!")
case let .App(a, b):
switch a.eval {
case let .Lam(x, aPrime):
return aPrime.subst(x, b)
default:
return .App(a.eval, b.eval)
}
default:
return self
}
}
}
extension Exp : CustomStringConvertible {
var description : String {
switch self {
case let .Var(x):
return "$" + x.description
case let .Lam(x, t):
return "(λ $\(x.description).\(t.description))"
case let .App(a, b):
return "(\(a.description) \(b.description))"
}
}
}
extension Name {
func fresh(ys : Set<Name>) -> Name {
let zz = "abcdefghijklmnopqrstuvwxyz".unicodeScalars.map { Name(unName: String($0)) }
return Set(zz).subtract(ys).first ?? self
}
}
private func showResult<A>(x : A, f : A -> Testable) -> Property {
return f(x).whenFail {
print("Result: \(x)")
}
}
class LambdaSpec : XCTestCase {
func testAll() {
let tiny = CheckerArguments(maxTestCaseSize: 10)
property("Free variable capture occurs", arguments: tiny) <- forAll { (a : Exp, x : Name, b : Exp) in
return showResult(a.subst(x, b)) { subst_x_b_a in
return a.free.contains(x)
==> subst_x_b_a.free == a.free.subtract([x]).union(b.free)
}
}.expectFailure
property("Substitution of a free variable into a fresh expr is idempotent", arguments: tiny) <- forAll { (a : Exp, x : Name, b : Exp) in
return showResult(a.subst(x, b)) { subst_x_b_a in
return !a.free.contains(x) ==> subst_x_b_a == a
}
}
property("Substitution of a free variable into a fresh expr is idempotent", arguments: tiny) <- forAll { (a : Exp, x : Name, b : Exp) in
return showResult(a.subst(x, b)) { subst_x_b_a in
return !a.free.contains(x) ==> subst_x_b_a.free == a.free
}
}
}
}
|
mit
|
f63053fe8a522df4e6460aad28899951
| 21.900524 | 138 | 0.590535 | 2.614465 | false | false | false | false |
RobotsAndPencils/Scythe
|
Dependencies/HarvestKit-Swift/HarvestKit-Shared/Client.swift
|
1
|
3389
|
//
// Client.swift
// HarvestKit
//
// Created by Matthew Cheetham on 19/11/2015.
// Copyright © 2015 Matt Cheetham. All rights reserved.
//
import Foundation
/**
A struct representation of a client in the harvest system
*/
public struct Client {
/**
A unique identifier for this Client
*/
public var identifier: Int?
/**
The clients name
*/
public var name: String?
/**
The same as the `address` property. This property will take precedence over the `address` property despite `address` technically being what is displayed on the website for Harvest. You can use either property to set the fields
*/
public var details: String?
/**
The currency that the client makes/recieves payments in. As a full length description.
*/
public var currencyName: String?
/**
The currency symbol representing the currency that the client makes/recieves payments in
*/
public var currencySymbol: String?
/**
A boolean to indicate whether or not the client is active in the system. If false, this client has been archived
*/
public var active: Bool?
public var defaultInvoiceKind: String?
public var lastInvoiceKind: String?
public var defaultInvoiceTimeframe: String?
/**
The date that the client was created
*/
public var created: Date?
/**
The date that this client was last updated
*/
public var updated: Date?
public var highriseId: Int?
/**
The clients address that they can be contacted at. Same as the `details` property although if setting both to different values which isn't possible, the details property will take precedence.
*/
public var address: String?
public var cacheVersion: Int?
public var statementKey: String?
internal init?(dictionary: [String: AnyObject]) {
guard let clientDictionary = dictionary["client"] as? [String: AnyObject] else {
print("Dictionary was missing client key")
return nil
}
identifier = clientDictionary["id"] as? Int
name = clientDictionary["name"] as? String
details = clientDictionary["details"] as? String
currencyName = clientDictionary["currency"] as? String
currencySymbol = clientDictionary["currency_symbol"] as? String
active = clientDictionary["active"] as? Bool
lastInvoiceKind = clientDictionary["last_invoice_kind"] as? String
defaultInvoiceKind = clientDictionary["default_invoice_kind"] as? String
cacheVersion = clientDictionary["cache_version"] as? Int
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
if let createdDateString = clientDictionary["created_at"] as? String {
created = dateFormatter.date(from: createdDateString)
}
if let updatedDateString = clientDictionary["updated_at"] as? String {
updated = dateFormatter.date(from: updatedDateString)
}
highriseId = clientDictionary["highrise_id"] as? Int
defaultInvoiceTimeframe = clientDictionary["default_invoice_timeframe"] as? String
statementKey = clientDictionary["statement_key"] as? String
}
}
|
mit
|
2eed87345ee517073048fd85a8fc78ea
| 30.962264 | 231 | 0.64876 | 4.833096 | false | false | false | false |
sgr-ksmt/FirstAppearing
|
Demo/Demo/AppDelegate.swift
|
1
|
3280
|
//
// AppDelegate.swift
// Demo
//
// Created by Suguru Kishimoto on 2016/01/29.
//
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
splitViewController.delegate = self
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:.
}
// MARK: - Split view
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool {
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false }
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
return false
}
}
|
mit
|
caab919a48ead9d633541fa76754f801
| 52.770492 | 285 | 0.764939 | 6.235741 | false | false | false | false |
AaronMT/firefox-ios
|
Shared/Extensions/UIBarButtonItemExtensions.swift
|
9
|
1877
|
/* 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 UIKit
// https://medium.com/@BeauNouvelle/adding-a-closure-to-uibarbuttonitem-24dfc217fe72
extension UIBarButtonItem {
private class UIBarButtonItemClosureWrapper: NSObject {
let closure: (UIBarButtonItem) -> ()
init(_ closure: @escaping (UIBarButtonItem) -> ()) {
self.closure = closure
}
}
private struct AssociatedKeys {
static var targetClosure = "targetClosure"
}
private var targetClosure: ((UIBarButtonItem) -> ())? {
get {
guard let closureWrapper = objc_getAssociatedObject(self, &AssociatedKeys.targetClosure) as? UIBarButtonItemClosureWrapper else { return nil }
return closureWrapper.closure
}
set(newValue) {
guard let newValue = newValue else { return }
objc_setAssociatedObject(self, &AssociatedKeys.targetClosure, UIBarButtonItemClosureWrapper(newValue), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
public convenience init(title: String?, style: UIBarButtonItem.Style, closure: @escaping (UIBarButtonItem) -> ()) {
self.init(title: title, style: style, target: nil, action: #selector(UIBarButtonItem.closureAction))
self.target = self
targetClosure = closure
}
public convenience init(barButtonSystemItem systemItem: UIBarButtonItem.SystemItem, closure: @escaping (UIBarButtonItem) -> ()) {
self.init(barButtonSystemItem: systemItem, target: nil, action: #selector(UIBarButtonItem.closureAction))
self.target = self
targetClosure = closure
}
@objc func closureAction() {
targetClosure?(self)
}
}
|
mpl-2.0
|
b0083ad22162183d61a23c3a120c911d
| 39.804348 | 172 | 0.680341 | 4.6925 | false | false | false | false |
MaartenBrijker/project
|
project/External/AudioKit-master/AudioKit/iOS/AudioKit/AudioKit.playground/Pages/Splitting Nodes.xcplaygroundpage/Contents.swift
|
4
|
1172
|
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
//:
//: ---
//:
//: ## Splitting Nodes
//: ### All nodes in AudioKit can have multiple destinations, the only caveat is that all of the destinations do have to eventually be mixed back together and none of the parallel signal paths can have any time stretching.
import XCPlayground
import AudioKit
//: Prepare the source audio player
let bundle = NSBundle.mainBundle()
let file = bundle.pathForResource("drumloop", ofType: "wav")
var player = AKAudioPlayer(file!)
player.looping = true
//: The following nodes are both acting on the original player node
var ringMod = AKRingModulator(player)
var delay = AKDelay(player)
delay.time = 0.01
delay.feedback = 0.8
delay.dryWetMix = 1
//: Any number of inputs can be equally summed into one output, including the original player, allowing us to create dry/wet mixes even for effects that don't have that property by default
let mixer = AKMixer(player, delay)
AudioKit.output = mixer
AudioKit.start()
player.play()
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
|
apache-2.0
|
13bd9ac4981c3ed220e31c9d5c0535db
| 34.515152 | 222 | 0.74744 | 4 | false | false | false | false |
DrewKiino/Tide
|
TideDemo/TideDemo/ViewController.swift
|
1
|
3268
|
//
// ViewController.swift
// TideDemo
//
// Created by Andrew Aquino on 6/4/16.
// Copyright © 2016 Andrew Aquino. All rights reserved.
//
import UIKit
import SwiftyTimer
public class ViewController: UIViewController {
public var imageView: UIImageView?
public var button: UIButton?
override public func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// imageView = UIImageView(frame: CGRectMake(0, 0, 256, 256))
// imageView?.backgroundColor = .redColor()
// imageView?.contentMode = .Center
// imageView?.image = UIImage(named: "tide-example.jpg")
// view.addSubview(imageView!)
// imageView?.imageFromUrl("http://www.planwallpaper.com/static/images/001_Fish-Wallpaper-HD.jpg", maskWithEllipse: true)
button = UIButton(frame: CGRectMake(0, 0, 100, 100))
button?.backgroundColor = .redColor()
view.addSubview(button!)
button?.imageFromSource("http://www.planwallpaper.com/static/images/001_Fish-Wallpaper-HD.jpg", forState: .Normal)
button?.imageFromSource("http://www.planwallpaper.com/static/images/a601cb579cc9a289bc51cd41d8bcf478_large.jpg", mask: .Rounded, forState: .Highlighted)
// test0()
//
// NSTimer.every(10.0) { [weak self] in
// self?.test0()
// }
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
public func test0(imageView: UIImageView?) {
imageView?.image = UIImage(named: "tide-example.jpg")
test()
NSTimer.after(5.0) { [weak self] in
self?.imageView?.image = UIImage(named: "profile-pic-example.jpg")
self?.test()
}
NSTimer.after(10.0) { [weak self] in
self?.imageView?.image = UIImage(named: "profile-pic-example2.jpg")
self?.test()
}
}
public func test() {
NSTimer.after(3.0) { [weak self] in
self?.imageView?.fitClip()
}
NSTimer.after(4.0) { [weak self] in
self?.imageView?.backgroundColor = .whiteColor()
self?.imageView?.rounded()
}
}
}
import SDWebImage
extension UIImageView {
public func imageFromUrl (
url: String?,
placeholder: UIImage? = nil,
maskWithEllipse: Bool = false,
block: ((image: UIImage?) -> Void)? = nil)
{
if let url = url, let nsurl = NSURL(string: url) {
// set the tag with the url's unique hash value
if tag == url.hashValue { return }
// else set the new tag as the new url's hash value
tag = url.hashValue
image = nil
// show activity
// showActivityView(nil, width: frame.width, height: frame.height)
// begin image download
SDWebImageManager.sharedManager().downloadImageWithURL(nsurl, options: [], progress: { (received: NSInteger, actual: NSInteger) -> Void in
}) { [weak self] (image, error, cache, finished, nsurl) -> Void in
block?(image: image)
if maskWithEllipse {
self?.fitClip(image) { [weak self] image in self?.rounded(image) }
} else {
self?.fitClip(image)
}
// self?.dismissActivityView()
}
} else {
image = placeholder
fitClip()
}
}
}
|
mit
|
c60a488bfecd27f5bf78690d37b6a530
| 29.259259 | 156 | 0.63667 | 3.843529 | false | true | false | false |
material-components/material-components-ios
|
components/NavigationBar/tests/unit/NavigationBarRectForItemTests.swift
|
2
|
5267
|
// Copyright 2019-present the Material Components for iOS authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import XCTest
import MaterialComponents.MaterialButtons
import MaterialComponents.MaterialNavigationBar
// Tests for Navigation Bar's rectFor*ItemAtIndex:inCoordinateSpace: APIs.
class NavigationBarRectForItemTests: XCTestCase {
var navigationBar: MDCNavigationBar!
override func setUp() {
super.setUp()
navigationBar = MDCNavigationBar()
navigationBar.frame = CGRect(x: 0, y: 0, width: 200, height: 100)
}
override func tearDown() {
navigationBar = nil
super.tearDown()
}
func testLeadingShortTextButtonMatchesExpectedFrame() {
// Given
let items = [UIBarButtonItem(title: "Text", style: .plain, target: nil, action: nil)]
navigationBar.leadingBarButtonItems = items
navigationBar.layoutIfNeeded()
// When
let rect = navigationBar.rect(forLeading: items[0], in: navigationBar)
// Then
XCTAssertEqual(rect, CGRect(x: 0, y: 0, width: 68, height: 56))
}
func testTrailingShortTextButtonMatchesExpectedFrame() {
// Given
let items = [UIBarButtonItem(title: "Text", style: .plain, target: nil, action: nil)]
navigationBar.trailingBarButtonItems = items
navigationBar.layoutIfNeeded()
// When
let rect = navigationBar.rect(forTrailing: items[0], in: navigationBar)
// Then
XCTAssertEqual(rect, CGRect(x: 132, y: 0, width: 68, height: 56))
}
func testLeadingLongTextButtonMatchesExpectedFrame() {
// Given
let items = [
UIBarButtonItem(
title: "Text that is relatively long",
style: .plain,
target: nil,
action: nil)
]
navigationBar.leadingBarButtonItems = items
navigationBar.layoutIfNeeded()
// When
let rect = navigationBar.rect(forLeading: items[0], in: navigationBar)
// Then
XCTAssertEqual(rect, CGRect(x: 0, y: 0, width: 252, height: 56))
}
func testTrailingLongTextButtonMatchesExpectedFrame() {
// Given
let items = [
UIBarButtonItem(
title: "Text that is relatively long",
style: .plain,
target: nil,
action: nil)
]
navigationBar.trailingBarButtonItems = items
navigationBar.layoutIfNeeded()
// When
let rect = navigationBar.rect(forTrailing: items[0], in: navigationBar)
// Then
XCTAssertEqual(rect, CGRect(x: -52, y: 0, width: 252, height: 56))
}
func testOriginOfEachLeadingButtonIncreases() {
// Given
let items = [
UIBarButtonItem(title: "Text", style: .plain, target: nil, action: nil),
UIBarButtonItem(title: "Text 2", style: .plain, target: nil, action: nil),
]
navigationBar.leadingBarButtonItems = items
navigationBar.layoutIfNeeded()
// When
let origins = items.map { item in
navigationBar.rect(forLeading: item, in: navigationBar).origin
}
// Then
XCTAssertEqual(origins, [CGPoint(x: 0, y: 0), CGPoint(x: 64, y: 0)])
}
func testOriginOfEachTrailingButtonDecreases() {
// Given
let items = [
UIBarButtonItem(title: "Text", style: .plain, target: nil, action: nil),
UIBarButtonItem(title: "Text 2", style: .plain, target: nil, action: nil),
]
navigationBar.trailingBarButtonItems = items
navigationBar.layoutIfNeeded()
// When
let origins = items.map { item in
navigationBar.rect(forTrailing: item, in: navigationBar).origin
}
// Then
XCTAssertEqual(origins, [CGPoint(x: 136, y: 0), CGPoint(x: 60, y: 0)])
}
func testLeadingRectInParentCoordinateSpaceFactorsInNavigationBarOrigin() {
// Given
let items = [UIBarButtonItem(title: "Text", style: .plain, target: nil, action: nil)]
navigationBar.leadingBarButtonItems = items
navigationBar.layoutIfNeeded()
let containerView = UIView()
navigationBar.frame.origin.x += 10
navigationBar.frame.origin.y += 20
containerView.addSubview(navigationBar)
// When
let rect = navigationBar.rect(forLeading: items[0], in: containerView)
// Then
XCTAssertEqual(rect, CGRect(x: 10, y: 20, width: 68, height: 56))
}
func testTrailingRectInParentCoordinateSpaceFactorsInNavigationBarOrigin() {
// Given
let items = [UIBarButtonItem(title: "Text", style: .plain, target: nil, action: nil)]
navigationBar.trailingBarButtonItems = items
navigationBar.layoutIfNeeded()
let containerView = UIView()
navigationBar.frame.origin.x += 10
navigationBar.frame.origin.y += 20
containerView.addSubview(navigationBar)
// When
let rect = navigationBar.rect(forTrailing: items[0], in: containerView)
// Then
XCTAssertEqual(rect, CGRect(x: 142, y: 20, width: 68, height: 56))
}
}
|
apache-2.0
|
17e0d221a89e5ddefdc27e2ca15a4de3
| 29.982353 | 89 | 0.688437 | 4.271695 | false | true | false | false |
material-components/material-components-ios
|
catalog/MDCCatalog/AppDelegate.swift
|
2
|
4928
|
// Copyright 2015-present the Material Components for iOS authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import CatalogByConvention
import MaterialComponents.MaterialAppBar
import MaterialComponents.MaterialAppBar_ColorThemer
import MaterialComponents.MaterialAppBar_TypographyThemer
import MaterialComponents.MaterialBottomSheet
import MaterialComponents.MaterialCollections
import MaterialComponents.MaterialIcons_ic_more_horiz
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, MDCAppBarNavigationControllerDelegate {
private static let performPostLaunchSelector = "performPostLaunchSelector"
var window: UIWindow?
let navigationController = MDCAppBarNavigationController()
var tree: CBCNode?
func application(_ application: UIApplication, didFinishLaunchingWithOptions
launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
self.window = MDCCatalogWindow(frame: UIScreen.main.bounds)
// The navigation tree will only take examples that implement
// and return YES to catalogIsPresentable.
let tree = CBCCreatePresentableNavigationTree()
self.tree = tree
navigationController.delegate = self
let rootNodeViewController = MDCCatalogComponentsController(node: tree)
navigationController.pushViewController(rootNodeViewController, animated: false)
self.window?.rootViewController = navigationController
self.window?.makeKeyAndVisible()
NotificationCenter.default.addObserver(
self,
selector: #selector(self.themeDidChange),
name: AppTheme.didChangeGlobalThemeNotificationName,
object: nil)
if self.responds(to: Selector((AppDelegate.performPostLaunchSelector))) {
self.perform(Selector((AppDelegate.performPostLaunchSelector)))
}
return true
}
// This method is exposed solely for the purposes of UI test runners to be able to fetch the
// catalog by convention example tree.
@objc func navigationTree() -> CBCNode? {
return self.tree
}
@objc func themeDidChange(notification: NSNotification) {
let colorScheme = AppTheme.containerScheme.colorScheme
for viewController in navigationController.children {
guard let appBar = navigationController.appBar(for: viewController) else {
continue
}
MDCAppBarColorThemer.applySemanticColorScheme(colorScheme, to: appBar)
}
}
// MARK: MDCAppBarNavigationControllerInjectorDelegate
func appBarNavigationController(_ navigationController: MDCAppBarNavigationController,
willAdd appBarViewController: MDCAppBarViewController,
asChildOf viewController: UIViewController) {
MDCAppBarColorThemer.applyColorScheme(AppTheme.containerScheme.colorScheme,
to: appBarViewController)
MDCAppBarTypographyThemer.applyTypographyScheme(AppTheme.containerScheme.typographyScheme,
to: appBarViewController)
if let injectee = viewController as? CatalogAppBarInjectee {
injectee.appBarNavigationControllerInjector(willAdd: appBarViewController)
}
}
}
extension UINavigationController: UIGestureRecognizerDelegate {
public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
return viewControllers.count > 1
}
}
protocol CatalogAppBarInjectee {
func appBarNavigationControllerInjector(willAdd appBarViewController: MDCAppBarViewController)
}
extension UINavigationController {
@objc func presentMenu() {
let menuViewController = MDCMenuViewController(style: .plain)
let bottomSheet = MDCBottomSheetController(contentViewController: menuViewController)
self.present(bottomSheet, animated: true, completion: nil)
}
func setMenuBarButton(for viewController: UIViewController) {
let dotsImage = MDCIcons.imageFor_ic_more_horiz()?.withRenderingMode(.alwaysTemplate)
let menuItem = UIBarButtonItem(image: dotsImage,
style: .plain,
target: self,
action: #selector(presentMenu))
menuItem.accessibilityLabel = "Menu"
menuItem.accessibilityHint = "Opens catalog configuration options."
viewController.navigationItem.rightBarButtonItem = menuItem
}
}
|
apache-2.0
|
da41eefe72235b7b2e664957bea69ba6
| 38.424 | 96 | 0.742898 | 5.537079 | false | false | false | false |
apple/swift
|
stdlib/public/core/KeyPath.swift
|
1
|
148949
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import SwiftShims
internal func _abstract(
methodName: StaticString = #function,
file: StaticString = #file, line: UInt = #line
) -> Never {
#if INTERNAL_CHECKS_ENABLED
_fatalErrorMessage("abstract method", methodName, file: file, line: line,
flags: _fatalErrorFlags())
#else
_conditionallyUnreachable()
#endif
}
// MARK: Type-erased abstract base classes
// NOTE: older runtimes had Swift.AnyKeyPath as the ObjC name.
// The two must coexist, so it was renamed. The old name must not be
// used in the new runtime. _TtCs11_AnyKeyPath is the mangled name for
// Swift._AnyKeyPath.
/// A type-erased key path, from any root type to any resulting value
/// type.
@_objcRuntimeName(_TtCs11_AnyKeyPath)
public class AnyKeyPath: Hashable, _AppendKeyPath {
/// The root type for this key path.
@inlinable
public static var rootType: Any.Type {
return _rootAndValueType.root
}
/// The value type for this key path.
@inlinable
public static var valueType: Any.Type {
return _rootAndValueType.value
}
/// Used to store the offset from the root to the value
/// in the case of a pure struct KeyPath.
/// It's a regular kvcKeyPathStringPtr otherwise.
internal final var _kvcKeyPathStringPtr: UnsafePointer<CChar>?
/// The hash value.
final public var hashValue: Int {
return _hashValue(for: self)
}
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
@_effects(releasenone)
final public func hash(into hasher: inout Hasher) {
ObjectIdentifier(type(of: self)).hash(into: &hasher)
return withBuffer {
var buffer = $0
if buffer.data.isEmpty { return }
while true {
let (component, type) = buffer.next()
hasher.combine(component.value)
if let type = type {
hasher.combine(unsafeBitCast(type, to: Int.self))
} else {
break
}
}
}
}
public static func ==(a: AnyKeyPath, b: AnyKeyPath) -> Bool {
// Fast-path identical objects
if a === b {
return true
}
// Short-circuit differently-typed key paths
if type(of: a) != type(of: b) {
return false
}
return a.withBuffer {
var aBuffer = $0
return b.withBuffer {
var bBuffer = $0
// Two equivalent key paths should have the same reference prefix
if aBuffer.hasReferencePrefix != bBuffer.hasReferencePrefix {
return false
}
// Identity is equal to identity
if aBuffer.data.isEmpty {
return bBuffer.data.isEmpty
}
while true {
let (aComponent, aType) = aBuffer.next()
let (bComponent, bType) = bBuffer.next()
if aComponent.header.endOfReferencePrefix
!= bComponent.header.endOfReferencePrefix
|| aComponent.value != bComponent.value
|| aType != bType {
return false
}
if aType == nil {
return true
}
}
}
}
}
/*
The following pertains to 32-bit architectures only.
We assume everything is a valid pointer to a potential
_kvcKeyPathStringPtr except for the first 4KB page which is reserved
for the nil pointer. Note that we have to distinguish between a valid
keypath offset of 0, and the nil pointer itself.
We use maximumOffsetOn32BitArchitecture + 1 for this case.
The variable maximumOffsetOn32BitArchitecture is duplicated in the two
functions below since having it as a global would make accesses slower,
given getOffsetFromStorage() gets called on each KeyPath read. Further,
having it as an instance variable in AnyKeyPath would increase the size
of AnyKeyPath by 8 bytes.
TODO: Find a better method of refactoring this variable if possible.
*/
func assignOffsetToStorage(offset: Int) {
let maximumOffsetOn32BitArchitecture = 4094
guard offset >= 0 else {
return
}
// TODO: This just gets the architecture size (32 or 64 bits).
// Is there a more efficient way? Something in Builtin maybe?
let architectureSize = MemoryLayout<Int>.size
if architectureSize == 8 {
_kvcKeyPathStringPtr = UnsafePointer<CChar>(bitPattern: -offset - 1)
}
else {
if offset <= maximumOffsetOn32BitArchitecture {
_kvcKeyPathStringPtr = UnsafePointer<CChar>(bitPattern: (offset + 1))
}
else {
_kvcKeyPathStringPtr = nil
}
}
}
func getOffsetFromStorage() -> Int? {
let maximumOffsetOn32BitArchitecture = 4094
guard _kvcKeyPathStringPtr != nil else {
return nil
}
let architectureSize = MemoryLayout<Int>.size
if architectureSize == 8 {
let offset = -Int(bitPattern: _kvcKeyPathStringPtr) - 1
guard offset >= 0 else {
// This happens to be an actual _kvcKeyPathStringPtr, not an offset, if we get here.
return nil
}
return offset
}
else {
let offset = Int(bitPattern: _kvcKeyPathStringPtr) - 1
if (offset <= maximumOffsetOn32BitArchitecture) {
return offset
}
return nil
}
}
// SPI for the Foundation overlay to allow interop with KVC keypath-based
// APIs.
public var _kvcKeyPathString: String? {
@_semantics("keypath.kvcKeyPathString")
get {
guard self.getOffsetFromStorage() == nil else {
return nil
}
guard let ptr = _kvcKeyPathStringPtr else { return nil }
return String(validatingUTF8: ptr)
}
}
// MARK: Implementation details
// Prevent normal initialization. We use tail allocation via
// allocWithTailElems().
@available(*, unavailable)
internal init() {
_internalInvariantFailure("use _create(...)")
}
@usableFromInline
internal class var _rootAndValueType: (root: Any.Type, value: Any.Type) {
_abstract()
}
internal static func _create(
capacityInBytes bytes: Int,
initializedBy body: (UnsafeMutableRawBufferPointer) -> Void
) -> Self {
_internalInvariant(bytes > 0 && bytes % 4 == 0,
"capacity must be multiple of 4 bytes")
let result = Builtin.allocWithTailElems_1(self, (bytes/4)._builtinWordValue,
Int32.self)
result._kvcKeyPathStringPtr = nil
let base = UnsafeMutableRawPointer(Builtin.projectTailElems(result,
Int32.self))
body(UnsafeMutableRawBufferPointer(start: base, count: bytes))
return result
}
final internal func withBuffer<T>(_ f: (KeyPathBuffer) throws -> T) rethrows -> T {
defer { _fixLifetime(self) }
let base = UnsafeRawPointer(Builtin.projectTailElems(self, Int32.self))
return try f(KeyPathBuffer(base: base))
}
@usableFromInline // Exposed as public API by MemoryLayout<Root>.offset(of:)
internal var _storedInlineOffset: Int? {
return withBuffer {
var buffer = $0
// The identity key path is effectively a stored keypath of type Self
// at offset zero
if buffer.data.isEmpty { return 0 }
var offset = 0
while true {
let (rawComponent, optNextType) = buffer.next()
switch rawComponent.header.kind {
case .struct:
offset += rawComponent._structOrClassOffset
case .class, .computed, .optionalChain, .optionalForce, .optionalWrap, .external:
return .none
}
if optNextType == nil { return .some(offset) }
}
}
}
}
/// A partially type-erased key path, from a concrete root type to any
/// resulting value type.
public class PartialKeyPath<Root>: AnyKeyPath { }
// MARK: Concrete implementations
internal enum KeyPathKind { case readOnly, value, reference }
/// A key path from a specific root type to a specific resulting value type.
///
/// The most common way to make an instance of this type
/// is by using a key-path expression like `\SomeClass.someProperty`.
/// For more information,
/// see [Key-Path Expressions][keypath] in *[The Swift Programming Language][tspl]*.
///
/// [keypath]: https://docs.swift.org/swift-book/ReferenceManual/Expressions.html#ID563
/// [tspl]: https://docs.swift.org/swift-book/
public class KeyPath<Root, Value>: PartialKeyPath<Root> {
@usableFromInline
internal final override class var _rootAndValueType: (
root: Any.Type,
value: Any.Type
) {
return (Root.self, Value.self)
}
// MARK: Implementation
internal typealias Kind = KeyPathKind
internal class var kind: Kind { return .readOnly }
internal static func appendedType<AppendedValue>(
with t: KeyPath<Value, AppendedValue>.Type
) -> KeyPath<Root, AppendedValue>.Type {
let resultKind: Kind
switch (self.kind, t.kind) {
case (_, .reference):
resultKind = .reference
case (let x, .value):
resultKind = x
default:
resultKind = .readOnly
}
switch resultKind {
case .readOnly:
return KeyPath<Root, AppendedValue>.self
case .value:
return WritableKeyPath.self
case .reference:
return ReferenceWritableKeyPath.self
}
}
@usableFromInline
internal final func _projectReadOnly(from root: Root) -> Value {
// One performance improvement is to skip right to Value
// if this keypath traverses through structs only.
if let offset = getOffsetFromStorage() {
return withUnsafeBytes(of: root) {
let pointer = $0.baseAddress.unsafelyUnwrapped.advanced(by: offset)
return pointer.assumingMemoryBound(to: Value.self).pointee
}
}
// TODO: For perf, we could use a local growable buffer instead of Any
var curBase: Any = root
return withBuffer {
var buffer = $0
if buffer.data.isEmpty {
return unsafeBitCast(root, to: Value.self)
}
while true {
let (rawComponent, optNextType) = buffer.next()
let valueType = optNextType ?? Value.self
let isLast = optNextType == nil
func project<CurValue>(_ base: CurValue) -> Value? {
func project2<NewValue>(_: NewValue.Type) -> Value? {
switch rawComponent._projectReadOnly(base,
to: NewValue.self, endingWith: Value.self) {
case .continue(let newBase):
if isLast {
_internalInvariant(NewValue.self == Value.self,
"key path does not terminate in correct type")
return unsafeBitCast(newBase, to: Value.self)
} else {
curBase = newBase
return nil
}
case .break(let result):
return result
}
}
return _openExistential(valueType, do: project2)
}
if let result = _openExistential(curBase, do: project) {
return result
}
}
}
}
deinit {
withBuffer { $0.destroy() }
}
}
/// A key path that supports reading from and writing to the resulting value.
public class WritableKeyPath<Root, Value>: KeyPath<Root, Value> {
// MARK: Implementation detail
internal override class var kind: Kind { return .value }
// `base` is assumed to be undergoing a formal access for the duration of the
// call, so must not be mutated by an alias
@usableFromInline
internal func _projectMutableAddress(from base: UnsafePointer<Root>)
-> (pointer: UnsafeMutablePointer<Value>, owner: AnyObject?) {
// One performance improvement is to skip right to Value
// if this keypath traverses through structs only.
// Don't declare "p" above this if-statement; it may slow things down.
if let offset = getOffsetFromStorage()
{
let p = UnsafeRawPointer(base).advanced(by: offset)
return (pointer: UnsafeMutablePointer(
mutating: p.assumingMemoryBound(to: Value.self)), owner: nil)
}
var p = UnsafeRawPointer(base)
var type: Any.Type = Root.self
var keepAlive: AnyObject?
return withBuffer {
var buffer = $0
_internalInvariant(!buffer.hasReferencePrefix,
"WritableKeyPath should not have a reference prefix")
if buffer.data.isEmpty {
return (
UnsafeMutablePointer<Value>(
mutating: p.assumingMemoryBound(to: Value.self)),
nil)
}
while true {
let (rawComponent, optNextType) = buffer.next()
let nextType = optNextType ?? Value.self
func project<CurValue>(_: CurValue.Type) {
func project2<NewValue>(_: NewValue.Type) {
p = rawComponent._projectMutableAddress(p,
from: CurValue.self,
to: NewValue.self,
isRoot: p == UnsafeRawPointer(base),
keepAlive: &keepAlive)
}
_openExistential(nextType, do: project2)
}
_openExistential(type, do: project)
if optNextType == nil { break }
type = nextType
}
// TODO: With coroutines, it would be better to yield here, so that
// we don't need the hack of the keepAlive reference to manage closing
// accesses.
let typedPointer = p.assumingMemoryBound(to: Value.self)
return (pointer: UnsafeMutablePointer(mutating: typedPointer),
owner: keepAlive)
}
}
}
/// A key path that supports reading from and writing to the resulting value
/// with reference semantics.
public class ReferenceWritableKeyPath<
Root, Value
>: WritableKeyPath<Root, Value> {
// MARK: Implementation detail
internal final override class var kind: Kind { return .reference }
@usableFromInline
internal final func _projectMutableAddress(from origBase: Root)
-> (pointer: UnsafeMutablePointer<Value>, owner: AnyObject?) {
var keepAlive: AnyObject?
let address: UnsafeMutablePointer<Value> = withBuffer {
var buffer = $0
// Project out the reference prefix.
var base: Any = origBase
while buffer.hasReferencePrefix {
let (rawComponent, optNextType) = buffer.next()
_internalInvariant(optNextType != nil,
"reference prefix should not go to end of buffer")
let nextType = optNextType.unsafelyUnwrapped
func project<NewValue>(_: NewValue.Type) -> Any {
func project2<CurValue>(_ base: CurValue) -> Any {
return rawComponent._projectReadOnly(
base, to: NewValue.self, endingWith: Value.self)
.assumingContinue
}
return _openExistential(base, do: project2)
}
base = _openExistential(nextType, do: project)
}
// Start formal access to the mutable value, based on the final base
// value.
func formalMutation<MutationRoot>(_ base: MutationRoot)
-> UnsafeMutablePointer<Value> {
var base2 = base
return withUnsafeBytes(of: &base2) { baseBytes in
var p = baseBytes.baseAddress.unsafelyUnwrapped
var curType: Any.Type = MutationRoot.self
while true {
let (rawComponent, optNextType) = buffer.next()
let nextType = optNextType ?? Value.self
func project<CurValue>(_: CurValue.Type) {
func project2<NewValue>(_: NewValue.Type) {
p = rawComponent._projectMutableAddress(p,
from: CurValue.self,
to: NewValue.self,
isRoot: p == baseBytes.baseAddress,
keepAlive: &keepAlive)
}
_openExistential(nextType, do: project2)
}
_openExistential(curType, do: project)
if optNextType == nil { break }
curType = nextType
}
let typedPointer = p.assumingMemoryBound(to: Value.self)
return UnsafeMutablePointer(mutating: typedPointer)
}
}
return _openExistential(base, do: formalMutation)
}
return (address, keepAlive)
}
}
// MARK: Implementation details
internal enum KeyPathComponentKind {
/// The keypath references an externally-defined property or subscript whose
/// component describes how to interact with the key path.
case external
/// The keypath projects within the storage of the outer value, like a
/// stored property in a struct.
case `struct`
/// The keypath projects from the referenced pointer, like a
/// stored property in a class.
case `class`
/// The keypath projects using a getter/setter pair.
case computed
/// The keypath optional-chains, returning nil immediately if the input is
/// nil, or else proceeding by projecting the value inside.
case optionalChain
/// The keypath optional-forces, trapping if the input is
/// nil, or else proceeding by projecting the value inside.
case optionalForce
/// The keypath wraps a value in an optional.
case optionalWrap
}
internal struct ComputedPropertyID: Hashable {
internal var value: Int
internal var kind: KeyPathComputedIDKind
internal static func ==(
x: ComputedPropertyID, y: ComputedPropertyID
) -> Bool {
return x.value == y.value
&& x.kind == y.kind
}
internal func hash(into hasher: inout Hasher) {
hasher.combine(value)
hasher.combine(kind)
}
}
internal struct ComputedAccessorsPtr {
#if INTERNAL_CHECKS_ENABLED
internal let header: RawKeyPathComponent.Header
#endif
internal let _value: UnsafeRawPointer
init(header: RawKeyPathComponent.Header, value: UnsafeRawPointer) {
#if INTERNAL_CHECKS_ENABLED
self.header = header
#endif
self._value = value
}
@_transparent
static var getterPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_Getter)
}
@_transparent
static var nonmutatingSetterPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_NonmutatingSetter)
}
@_transparent
static var mutatingSetterPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_MutatingSetter)
}
internal typealias Getter<CurValue, NewValue> = @convention(thin)
(CurValue, UnsafeRawPointer, Int) -> NewValue
internal typealias NonmutatingSetter<CurValue, NewValue> = @convention(thin)
(NewValue, CurValue, UnsafeRawPointer, Int) -> ()
internal typealias MutatingSetter<CurValue, NewValue> = @convention(thin)
(NewValue, inout CurValue, UnsafeRawPointer, Int) -> ()
internal var getterPtr: UnsafeRawPointer {
#if INTERNAL_CHECKS_ENABLED
_internalInvariant(header.kind == .computed,
"not a computed property")
#endif
return _value
}
internal var setterPtr: UnsafeRawPointer {
#if INTERNAL_CHECKS_ENABLED
_internalInvariant(header.isComputedSettable,
"not a settable property")
#endif
return _value + MemoryLayout<Int>.size
}
internal func getter<CurValue, NewValue>()
-> Getter<CurValue, NewValue> {
return getterPtr._loadAddressDiscriminatedFunctionPointer(
as: Getter.self,
discriminator: ComputedAccessorsPtr.getterPtrAuthKey)
}
internal func nonmutatingSetter<CurValue, NewValue>()
-> NonmutatingSetter<CurValue, NewValue> {
#if INTERNAL_CHECKS_ENABLED
_internalInvariant(header.isComputedSettable && !header.isComputedMutating,
"not a nonmutating settable property")
#endif
return setterPtr._loadAddressDiscriminatedFunctionPointer(
as: NonmutatingSetter.self,
discriminator: ComputedAccessorsPtr.nonmutatingSetterPtrAuthKey)
}
internal func mutatingSetter<CurValue, NewValue>()
-> MutatingSetter<CurValue, NewValue> {
#if INTERNAL_CHECKS_ENABLED
_internalInvariant(header.isComputedSettable && header.isComputedMutating,
"not a mutating settable property")
#endif
return setterPtr._loadAddressDiscriminatedFunctionPointer(
as: MutatingSetter.self,
discriminator: ComputedAccessorsPtr.mutatingSetterPtrAuthKey)
}
}
internal struct ComputedArgumentWitnessesPtr {
internal let _value: UnsafeRawPointer
init(_ value: UnsafeRawPointer) {
self._value = value
}
@_transparent
static var destroyPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_ArgumentDestroy)
}
@_transparent
static var copyPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_ArgumentCopy)
}
@_transparent
static var equalsPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_ArgumentEquals)
}
@_transparent
static var hashPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_ArgumentHash)
}
@_transparent
static var layoutPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_ArgumentLayout)
}
@_transparent
static var initPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_ArgumentInit)
}
internal typealias Destroy = @convention(thin)
(_ instanceArguments: UnsafeMutableRawPointer, _ size: Int) -> ()
internal typealias Copy = @convention(thin)
(_ srcInstanceArguments: UnsafeRawPointer,
_ destInstanceArguments: UnsafeMutableRawPointer,
_ size: Int) -> ()
internal typealias Equals = @convention(thin)
(_ xInstanceArguments: UnsafeRawPointer,
_ yInstanceArguments: UnsafeRawPointer,
_ size: Int) -> Bool
// FIXME(hasher) Combine to an inout Hasher instead
internal typealias Hash = @convention(thin)
(_ instanceArguments: UnsafeRawPointer,
_ size: Int) -> Int
// The witnesses are stored as address-discriminated authenticated
// pointers.
internal var destroy: Destroy? {
return _value._loadAddressDiscriminatedFunctionPointer(
as: Optional<Destroy>.self,
discriminator: ComputedArgumentWitnessesPtr.destroyPtrAuthKey)
}
internal var copy: Copy {
return _value._loadAddressDiscriminatedFunctionPointer(
fromByteOffset: MemoryLayout<UnsafeRawPointer>.size,
as: Copy.self,
discriminator: ComputedArgumentWitnessesPtr.copyPtrAuthKey)
}
internal var equals: Equals {
return _value._loadAddressDiscriminatedFunctionPointer(
fromByteOffset: 2*MemoryLayout<UnsafeRawPointer>.size,
as: Equals.self,
discriminator: ComputedArgumentWitnessesPtr.equalsPtrAuthKey)
}
internal var hash: Hash {
return _value._loadAddressDiscriminatedFunctionPointer(
fromByteOffset: 3*MemoryLayout<UnsafeRawPointer>.size,
as: Hash.self,
discriminator: ComputedArgumentWitnessesPtr.hashPtrAuthKey)
}
}
internal enum KeyPathComponent: Hashable {
internal struct ArgumentRef {
internal var data: UnsafeRawBufferPointer
internal var witnesses: ComputedArgumentWitnessesPtr
internal var witnessSizeAdjustment: Int
internal init(
data: UnsafeRawBufferPointer,
witnesses: ComputedArgumentWitnessesPtr,
witnessSizeAdjustment: Int
) {
self.data = data
self.witnesses = witnesses
self.witnessSizeAdjustment = witnessSizeAdjustment
}
}
/// The keypath projects within the storage of the outer value, like a
/// stored property in a struct.
case `struct`(offset: Int)
/// The keypath projects from the referenced pointer, like a
/// stored property in a class.
case `class`(offset: Int)
/// The keypath projects using a getter.
case get(id: ComputedPropertyID,
accessors: ComputedAccessorsPtr,
argument: ArgumentRef?)
/// The keypath projects using a getter/setter pair. The setter can mutate
/// the base value in-place.
case mutatingGetSet(id: ComputedPropertyID,
accessors: ComputedAccessorsPtr,
argument: ArgumentRef?)
/// The keypath projects using a getter/setter pair that does not mutate its
/// base.
case nonmutatingGetSet(id: ComputedPropertyID,
accessors: ComputedAccessorsPtr,
argument: ArgumentRef?)
/// The keypath optional-chains, returning nil immediately if the input is
/// nil, or else proceeding by projecting the value inside.
case optionalChain
/// The keypath optional-forces, trapping if the input is
/// nil, or else proceeding by projecting the value inside.
case optionalForce
/// The keypath wraps a value in an optional.
case optionalWrap
internal static func ==(a: KeyPathComponent, b: KeyPathComponent) -> Bool {
switch (a, b) {
case (.struct(offset: let a), .struct(offset: let b)),
(.class (offset: let a), .class (offset: let b)):
return a == b
case (.optionalChain, .optionalChain),
(.optionalForce, .optionalForce),
(.optionalWrap, .optionalWrap):
return true
case (.get(id: let id1, accessors: _, argument: let argument1),
.get(id: let id2, accessors: _, argument: let argument2)),
(.mutatingGetSet(id: let id1, accessors: _, argument: let argument1),
.mutatingGetSet(id: let id2, accessors: _, argument: let argument2)),
(.nonmutatingGetSet(id: let id1, accessors: _, argument: let argument1),
.nonmutatingGetSet(id: let id2, accessors: _, argument: let argument2)):
if id1 != id2 {
return false
}
if let arg1 = argument1, let arg2 = argument2 {
return arg1.witnesses.equals(
arg1.data.baseAddress.unsafelyUnwrapped,
arg2.data.baseAddress.unsafelyUnwrapped,
arg1.data.count - arg1.witnessSizeAdjustment)
}
// If only one component has arguments, that should indicate that the
// only arguments in that component were generic captures and therefore
// not affecting equality.
return true
case (.struct, _),
(.class, _),
(.optionalChain, _),
(.optionalForce, _),
(.optionalWrap, _),
(.get, _),
(.mutatingGetSet, _),
(.nonmutatingGetSet, _):
return false
}
}
@_effects(releasenone)
internal func hash(into hasher: inout Hasher) {
func appendHashFromArgument(
_ argument: KeyPathComponent.ArgumentRef?
) {
if let argument = argument {
let hash = argument.witnesses.hash(
argument.data.baseAddress.unsafelyUnwrapped,
argument.data.count - argument.witnessSizeAdjustment)
// Returning 0 indicates that the arguments should not impact the
// hash value of the overall key path.
// FIXME(hasher): hash witness should just mutate hasher directly
if hash != 0 {
hasher.combine(hash)
}
}
}
switch self {
case .struct(offset: let a):
hasher.combine(0)
hasher.combine(a)
case .class(offset: let b):
hasher.combine(1)
hasher.combine(b)
case .optionalChain:
hasher.combine(2)
case .optionalForce:
hasher.combine(3)
case .optionalWrap:
hasher.combine(4)
case .get(id: let id, accessors: _, argument: let argument):
hasher.combine(5)
hasher.combine(id)
appendHashFromArgument(argument)
case .mutatingGetSet(id: let id, accessors: _, argument: let argument):
hasher.combine(6)
hasher.combine(id)
appendHashFromArgument(argument)
case .nonmutatingGetSet(id: let id, accessors: _, argument: let argument):
hasher.combine(7)
hasher.combine(id)
appendHashFromArgument(argument)
}
}
}
// A class that maintains ownership of another object while a mutable projection
// into it is underway. The lifetime of the instance of this class is also used
// to begin and end exclusive 'modify' access to the projected address.
internal final class ClassHolder<ProjectionType> {
/// The type of the scratch record passed to the runtime to record
/// accesses to guarantee exclusive access.
internal typealias AccessRecord = Builtin.UnsafeValueBuffer
internal var previous: AnyObject?
internal var instance: AnyObject
internal init(previous: AnyObject?, instance: AnyObject) {
self.previous = previous
self.instance = instance
}
internal final class func _create(
previous: AnyObject?,
instance: AnyObject,
accessingAddress address: UnsafeRawPointer,
type: ProjectionType.Type
) -> ClassHolder {
// Tail allocate the UnsafeValueBuffer used as the AccessRecord.
// This avoids a second heap allocation since there is no source-level way to
// initialize a Builtin.UnsafeValueBuffer type and thus we cannot have a
// stored property of that type.
let holder: ClassHolder = Builtin.allocWithTailElems_1(self,
1._builtinWordValue,
AccessRecord.self)
// Initialize the ClassHolder's instance variables. This is done via
// withUnsafeMutablePointer(to:) because the instance was just allocated with
// allocWithTailElems_1 and so we need to make sure to use an initialization
// rather than an assignment.
withUnsafeMutablePointer(to: &holder.previous) {
$0.initialize(to: previous)
}
withUnsafeMutablePointer(to: &holder.instance) {
$0.initialize(to: instance)
}
let accessRecordPtr = Builtin.projectTailElems(holder, AccessRecord.self)
// Begin a 'modify' access to the address. This access is ended in
// ClassHolder's deinitializer.
Builtin.beginUnpairedModifyAccess(address._rawValue, accessRecordPtr, type)
return holder
}
deinit {
let accessRecordPtr = Builtin.projectTailElems(self, AccessRecord.self)
// Ends the access begun in _create().
Builtin.endUnpairedAccess(accessRecordPtr)
}
}
// A class that triggers writeback to a pointer when destroyed.
internal final class MutatingWritebackBuffer<CurValue, NewValue> {
internal let previous: AnyObject?
internal let base: UnsafeMutablePointer<CurValue>
internal let set: ComputedAccessorsPtr.MutatingSetter<CurValue, NewValue>
internal let argument: UnsafeRawPointer
internal let argumentSize: Int
internal var value: NewValue
deinit {
set(value, &base.pointee, argument, argumentSize)
}
internal init(previous: AnyObject?,
base: UnsafeMutablePointer<CurValue>,
set: @escaping ComputedAccessorsPtr.MutatingSetter<CurValue, NewValue>,
argument: UnsafeRawPointer,
argumentSize: Int,
value: NewValue) {
self.previous = previous
self.base = base
self.set = set
self.argument = argument
self.argumentSize = argumentSize
self.value = value
}
}
// A class that triggers writeback to a non-mutated value when destroyed.
internal final class NonmutatingWritebackBuffer<CurValue, NewValue> {
internal let previous: AnyObject?
internal let base: CurValue
internal let set: ComputedAccessorsPtr.NonmutatingSetter<CurValue, NewValue>
internal let argument: UnsafeRawPointer
internal let argumentSize: Int
internal var value: NewValue
deinit {
set(value, base, argument, argumentSize)
}
internal
init(previous: AnyObject?,
base: CurValue,
set: @escaping ComputedAccessorsPtr.NonmutatingSetter<CurValue, NewValue>,
argument: UnsafeRawPointer,
argumentSize: Int,
value: NewValue) {
self.previous = previous
self.base = base
self.set = set
self.argument = argument
self.argumentSize = argumentSize
self.value = value
}
}
internal typealias KeyPathComputedArgumentLayoutFn = @convention(thin)
(_ patternArguments: UnsafeRawPointer?) -> (size: Int, alignmentMask: Int)
internal typealias KeyPathComputedArgumentInitializerFn = @convention(thin)
(_ patternArguments: UnsafeRawPointer?,
_ instanceArguments: UnsafeMutableRawPointer) -> ()
internal enum KeyPathComputedIDKind {
case pointer
case storedPropertyIndex
case vtableOffset
}
internal enum KeyPathComputedIDResolution {
case resolved
case resolvedAbsolute
case indirectPointer
case functionCall
}
internal struct RawKeyPathComponent {
internal var header: Header
internal var body: UnsafeRawBufferPointer
internal init(header: Header, body: UnsafeRawBufferPointer) {
self.header = header
self.body = body
}
@_transparent
static var metadataAccessorPtrAuthKey: UInt64 {
return UInt64(_SwiftKeyPath_ptrauth_MetadataAccessor)
}
internal struct Header {
internal var _value: UInt32
init(discriminator: UInt32, payload: UInt32) {
_value = 0
self.discriminator = discriminator
self.payload = payload
}
internal var discriminator: UInt32 {
get {
return (_value & Header.discriminatorMask) >> Header.discriminatorShift
}
set {
let shifted = newValue << Header.discriminatorShift
_internalInvariant(shifted & Header.discriminatorMask == shifted,
"discriminator doesn't fit")
_value = _value & ~Header.discriminatorMask | shifted
}
}
internal var payload: UInt32 {
get {
return _value & Header.payloadMask
}
set {
_internalInvariant(newValue & Header.payloadMask == newValue,
"payload too big")
_value = _value & ~Header.payloadMask | newValue
}
}
internal var storedOffsetPayload: UInt32 {
get {
_internalInvariant(kind == .struct || kind == .class,
"not a stored component")
return _value & Header.storedOffsetPayloadMask
}
set {
_internalInvariant(kind == .struct || kind == .class,
"not a stored component")
_internalInvariant(newValue & Header.storedOffsetPayloadMask == newValue,
"payload too big")
_value = _value & ~Header.storedOffsetPayloadMask | newValue
}
}
internal var endOfReferencePrefix: Bool {
get {
return _value & Header.endOfReferencePrefixFlag != 0
}
set {
if newValue {
_value |= Header.endOfReferencePrefixFlag
} else {
_value &= ~Header.endOfReferencePrefixFlag
}
}
}
internal var kind: KeyPathComponentKind {
switch (discriminator, payload) {
case (Header.externalTag, _):
return .external
case (Header.structTag, _):
return .struct
case (Header.classTag, _):
return .class
case (Header.computedTag, _):
return .computed
case (Header.optionalTag, Header.optionalChainPayload):
return .optionalChain
case (Header.optionalTag, Header.optionalWrapPayload):
return .optionalWrap
case (Header.optionalTag, Header.optionalForcePayload):
return .optionalForce
default:
_internalInvariantFailure("invalid header")
}
}
internal static var payloadMask: UInt32 {
return _SwiftKeyPathComponentHeader_PayloadMask
}
internal static var discriminatorMask: UInt32 {
return _SwiftKeyPathComponentHeader_DiscriminatorMask
}
internal static var discriminatorShift: UInt32 {
return _SwiftKeyPathComponentHeader_DiscriminatorShift
}
internal static var externalTag: UInt32 {
return _SwiftKeyPathComponentHeader_ExternalTag
}
internal static var structTag: UInt32 {
return _SwiftKeyPathComponentHeader_StructTag
}
internal static var computedTag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedTag
}
internal static var classTag: UInt32 {
return _SwiftKeyPathComponentHeader_ClassTag
}
internal static var optionalTag: UInt32 {
return _SwiftKeyPathComponentHeader_OptionalTag
}
internal static var optionalChainPayload: UInt32 {
return _SwiftKeyPathComponentHeader_OptionalChainPayload
}
internal static var optionalWrapPayload: UInt32 {
return _SwiftKeyPathComponentHeader_OptionalWrapPayload
}
internal static var optionalForcePayload: UInt32 {
return _SwiftKeyPathComponentHeader_OptionalForcePayload
}
internal static var endOfReferencePrefixFlag: UInt32 {
return _SwiftKeyPathComponentHeader_EndOfReferencePrefixFlag
}
internal static var storedMutableFlag: UInt32 {
return _SwiftKeyPathComponentHeader_StoredMutableFlag
}
internal static var storedOffsetPayloadMask: UInt32 {
return _SwiftKeyPathComponentHeader_StoredOffsetPayloadMask
}
internal static var outOfLineOffsetPayload: UInt32 {
return _SwiftKeyPathComponentHeader_OutOfLineOffsetPayload
}
internal static var unresolvedFieldOffsetPayload: UInt32 {
return _SwiftKeyPathComponentHeader_UnresolvedFieldOffsetPayload
}
internal static var unresolvedIndirectOffsetPayload: UInt32 {
return _SwiftKeyPathComponentHeader_UnresolvedIndirectOffsetPayload
}
internal static var maximumOffsetPayload: UInt32 {
return _SwiftKeyPathComponentHeader_MaximumOffsetPayload
}
internal var isStoredMutable: Bool {
_internalInvariant(kind == .struct || kind == .class)
return _value & Header.storedMutableFlag != 0
}
internal static var computedMutatingFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedMutatingFlag
}
internal var isComputedMutating: Bool {
_internalInvariant(kind == .computed)
return _value & Header.computedMutatingFlag != 0
}
internal static var computedSettableFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedSettableFlag
}
internal var isComputedSettable: Bool {
_internalInvariant(kind == .computed)
return _value & Header.computedSettableFlag != 0
}
internal static var computedIDByStoredPropertyFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDByStoredPropertyFlag
}
internal static var computedIDByVTableOffsetFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDByVTableOffsetFlag
}
internal var computedIDKind: KeyPathComputedIDKind {
let storedProperty = _value & Header.computedIDByStoredPropertyFlag != 0
let vtableOffset = _value & Header.computedIDByVTableOffsetFlag != 0
switch (storedProperty, vtableOffset) {
case (true, true):
_internalInvariantFailure("not allowed")
case (true, false):
return .storedPropertyIndex
case (false, true):
return .vtableOffset
case (false, false):
return .pointer
}
}
internal static var computedHasArgumentsFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedHasArgumentsFlag
}
internal var hasComputedArguments: Bool {
_internalInvariant(kind == .computed)
return _value & Header.computedHasArgumentsFlag != 0
}
// If a computed component is instantiated from an external property
// descriptor, and both components carry arguments, we need to carry some
// extra matter to be able to map between the client and external generic
// contexts.
internal static var computedInstantiatedFromExternalWithArgumentsFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedInstantiatedFromExternalWithArgumentsFlag
}
internal var isComputedInstantiatedFromExternalWithArguments: Bool {
get {
_internalInvariant(kind == .computed)
return
_value & Header.computedInstantiatedFromExternalWithArgumentsFlag != 0
}
set {
_internalInvariant(kind == .computed)
_value =
_value & ~Header.computedInstantiatedFromExternalWithArgumentsFlag
| (newValue ? Header.computedInstantiatedFromExternalWithArgumentsFlag
: 0)
}
}
internal static var externalWithArgumentsExtraSize: Int {
return MemoryLayout<Int>.size
}
internal static var computedIDResolutionMask: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDResolutionMask
}
internal static var computedIDResolved: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDResolved
}
internal static var computedIDResolvedAbsolute: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDResolvedAbsolute
}
internal static var computedIDUnresolvedIndirectPointer: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDUnresolvedIndirectPointer
}
internal static var computedIDUnresolvedFunctionCall: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDUnresolvedFunctionCall
}
internal var computedIDResolution: KeyPathComputedIDResolution {
switch payload & Header.computedIDResolutionMask {
case Header.computedIDResolved:
return .resolved
case Header.computedIDResolvedAbsolute:
return .resolvedAbsolute
case Header.computedIDUnresolvedIndirectPointer:
return .indirectPointer
case Header.computedIDUnresolvedFunctionCall:
return .functionCall
default:
_internalInvariantFailure("invalid key path resolution")
}
}
// The component header is 4 bytes, but may be followed by an aligned
// pointer field for some kinds of component, forcing padding.
internal static var pointerAlignmentSkew: Int {
return MemoryLayout<Int>.size - MemoryLayout<Int32>.size
}
internal var isTrivialPropertyDescriptor: Bool {
return _value ==
_SwiftKeyPathComponentHeader_TrivialPropertyDescriptorMarker
}
/// If this is the header for a component in a key path pattern, return
/// the size of the body of the component.
internal var patternComponentBodySize: Int {
return _componentBodySize(forPropertyDescriptor: false)
}
/// If this is the header for a property descriptor, return
/// the size of the body of the component.
internal var propertyDescriptorBodySize: Int {
if isTrivialPropertyDescriptor { return 0 }
return _componentBodySize(forPropertyDescriptor: true)
}
internal func _componentBodySize(forPropertyDescriptor: Bool) -> Int {
switch kind {
case .struct, .class:
if storedOffsetPayload == Header.unresolvedFieldOffsetPayload
|| storedOffsetPayload == Header.outOfLineOffsetPayload
|| storedOffsetPayload == Header.unresolvedIndirectOffsetPayload {
// A 32-bit offset is stored in the body.
return MemoryLayout<UInt32>.size
}
// Otherwise, there's no body.
return 0
case .external:
// The body holds a pointer to the external property descriptor,
// and some number of substitution arguments, the count of which is
// in the payload.
return 4 * (1 + Int(payload))
case .computed:
// The body holds at minimum the id and getter.
var size = 8
// If settable, it also holds the setter.
if isComputedSettable {
size += 4
}
// If there are arguments, there's also a layout function,
// witness table, and initializer function.
// Property descriptors never carry argument information, though.
if !forPropertyDescriptor && hasComputedArguments {
size += 12
}
return size
case .optionalForce, .optionalChain, .optionalWrap:
// Otherwise, there's no body.
return 0
}
}
init(optionalForce: ()) {
self.init(discriminator: Header.optionalTag,
payload: Header.optionalForcePayload)
}
init(optionalWrap: ()) {
self.init(discriminator: Header.optionalTag,
payload: Header.optionalWrapPayload)
}
init(optionalChain: ()) {
self.init(discriminator: Header.optionalTag,
payload: Header.optionalChainPayload)
}
init(stored kind: KeyPathStructOrClass,
mutable: Bool,
inlineOffset: UInt32) {
let discriminator: UInt32
switch kind {
case .struct: discriminator = Header.structTag
case .class: discriminator = Header.classTag
}
_internalInvariant(inlineOffset <= Header.maximumOffsetPayload)
let payload = inlineOffset
| (mutable ? Header.storedMutableFlag : 0)
self.init(discriminator: discriminator,
payload: payload)
}
init(storedWithOutOfLineOffset kind: KeyPathStructOrClass,
mutable: Bool) {
let discriminator: UInt32
switch kind {
case .struct: discriminator = Header.structTag
case .class: discriminator = Header.classTag
}
let payload = Header.outOfLineOffsetPayload
| (mutable ? Header.storedMutableFlag : 0)
self.init(discriminator: discriminator,
payload: payload)
}
init(computedWithIDKind kind: KeyPathComputedIDKind,
mutating: Bool,
settable: Bool,
hasArguments: Bool,
instantiatedFromExternalWithArguments: Bool) {
let discriminator = Header.computedTag
var payload =
(mutating ? Header.computedMutatingFlag : 0)
| (settable ? Header.computedSettableFlag : 0)
| (hasArguments ? Header.computedHasArgumentsFlag : 0)
| (instantiatedFromExternalWithArguments
? Header.computedInstantiatedFromExternalWithArgumentsFlag : 0)
switch kind {
case .pointer:
break
case .storedPropertyIndex:
payload |= Header.computedIDByStoredPropertyFlag
case .vtableOffset:
payload |= Header.computedIDByVTableOffsetFlag
}
self.init(discriminator: discriminator,
payload: payload)
}
}
internal var bodySize: Int {
let ptrSize = MemoryLayout<Int>.size
switch header.kind {
case .struct, .class:
if header.storedOffsetPayload == Header.outOfLineOffsetPayload {
return 4 // overflowed
}
return 0
case .external:
_internalInvariantFailure("should be instantiated away")
case .optionalChain, .optionalForce, .optionalWrap:
return 0
case .computed:
// align to pointer, minimum two pointers for id and get
var total = Header.pointerAlignmentSkew + ptrSize * 2
// additional word for a setter
if header.isComputedSettable {
total += ptrSize
}
// include the argument size
if header.hasComputedArguments {
// two words for argument header: size, witnesses
total += ptrSize * 2
// size of argument area
total += _computedArgumentSize
if header.isComputedInstantiatedFromExternalWithArguments {
total += Header.externalWithArgumentsExtraSize
}
}
return total
}
}
internal var _structOrClassOffset: Int {
_internalInvariant(header.kind == .struct || header.kind == .class,
"no offset for this kind")
// An offset too large to fit inline is represented by a signal and stored
// in the body.
if header.storedOffsetPayload == Header.outOfLineOffsetPayload {
// Offset overflowed into body
_internalInvariant(body.count >= MemoryLayout<UInt32>.size,
"component not big enough")
return Int(body.load(as: UInt32.self))
}
return Int(header.storedOffsetPayload)
}
internal var _computedIDValue: Int {
_internalInvariant(header.kind == .computed,
"not a computed property")
return body.load(fromByteOffset: Header.pointerAlignmentSkew,
as: Int.self)
}
internal var _computedID: ComputedPropertyID {
_internalInvariant(header.kind == .computed,
"not a computed property")
return ComputedPropertyID(
value: _computedIDValue,
kind: header.computedIDKind)
}
internal var _computedAccessors: ComputedAccessorsPtr {
_internalInvariant(header.kind == .computed,
"not a computed property")
return ComputedAccessorsPtr(
header: header,
value: body.baseAddress.unsafelyUnwrapped +
Header.pointerAlignmentSkew + MemoryLayout<Int>.size)
}
internal var _computedArgumentHeaderPointer: UnsafeRawPointer {
_internalInvariant(header.hasComputedArguments, "no arguments")
return body.baseAddress.unsafelyUnwrapped
+ Header.pointerAlignmentSkew
+ MemoryLayout<Int>.size *
(header.isComputedSettable ? 3 : 2)
}
internal var _computedArgumentSize: Int {
return _computedArgumentHeaderPointer.load(as: Int.self)
}
internal
var _computedArgumentWitnesses: ComputedArgumentWitnessesPtr {
return _computedArgumentHeaderPointer.load(
fromByteOffset: MemoryLayout<Int>.size,
as: ComputedArgumentWitnessesPtr.self)
}
internal var _computedArguments: UnsafeRawPointer {
var base = _computedArgumentHeaderPointer + MemoryLayout<Int>.size * 2
// If the component was instantiated from an external property descriptor
// with its own arguments, we include some additional capture info to
// be able to map to the original argument context by adjusting the size
// passed to the witness operations.
if header.isComputedInstantiatedFromExternalWithArguments {
base += Header.externalWithArgumentsExtraSize
}
return base
}
internal var _computedMutableArguments: UnsafeMutableRawPointer {
return UnsafeMutableRawPointer(mutating: _computedArguments)
}
internal var _computedArgumentWitnessSizeAdjustment: Int {
if header.isComputedInstantiatedFromExternalWithArguments {
return _computedArguments.load(
fromByteOffset: -Header.externalWithArgumentsExtraSize,
as: Int.self)
}
return 0
}
internal var value: KeyPathComponent {
switch header.kind {
case .struct:
return .struct(offset: _structOrClassOffset)
case .class:
return .class(offset: _structOrClassOffset)
case .optionalChain:
return .optionalChain
case .optionalForce:
return .optionalForce
case .optionalWrap:
return .optionalWrap
case .computed:
let isSettable = header.isComputedSettable
let isMutating = header.isComputedMutating
let id = _computedID
let accessors = _computedAccessors
// Argument value is unused if there are no arguments.
let argument: KeyPathComponent.ArgumentRef?
if header.hasComputedArguments {
argument = KeyPathComponent.ArgumentRef(
data: UnsafeRawBufferPointer(start: _computedArguments,
count: _computedArgumentSize),
witnesses: _computedArgumentWitnesses,
witnessSizeAdjustment: _computedArgumentWitnessSizeAdjustment)
} else {
argument = nil
}
switch (isSettable, isMutating) {
case (false, false):
return .get(id: id, accessors: accessors, argument: argument)
case (true, false):
return .nonmutatingGetSet(id: id,
accessors: accessors,
argument: argument)
case (true, true):
return .mutatingGetSet(id: id,
accessors: accessors,
argument: argument)
case (false, true):
_internalInvariantFailure("impossible")
}
case .external:
_internalInvariantFailure("should have been instantiated away")
}
}
internal func destroy() {
switch header.kind {
case .struct,
.class,
.optionalChain,
.optionalForce,
.optionalWrap:
// trivial
break
case .computed:
// Run destructor, if any
if header.hasComputedArguments,
let destructor = _computedArgumentWitnesses.destroy {
destructor(_computedMutableArguments,
_computedArgumentSize - _computedArgumentWitnessSizeAdjustment)
}
case .external:
_internalInvariantFailure("should have been instantiated away")
}
}
internal func clone(into buffer: inout UnsafeMutableRawBufferPointer,
endOfReferencePrefix: Bool) {
var newHeader = header
newHeader.endOfReferencePrefix = endOfReferencePrefix
var componentSize = MemoryLayout<Header>.size
buffer.storeBytes(of: newHeader, as: Header.self)
switch header.kind {
case .struct,
.class:
if header.storedOffsetPayload == Header.outOfLineOffsetPayload {
let overflowOffset = body.load(as: UInt32.self)
buffer.storeBytes(of: overflowOffset, toByteOffset: 4,
as: UInt32.self)
componentSize += 4
}
case .optionalChain,
.optionalForce,
.optionalWrap:
break
case .computed:
// Fields are pointer-aligned after the header
componentSize += Header.pointerAlignmentSkew
buffer.storeBytes(of: _computedIDValue,
toByteOffset: componentSize,
as: Int.self)
componentSize += MemoryLayout<Int>.size
let accessors = _computedAccessors
(buffer.baseAddress.unsafelyUnwrapped + MemoryLayout<Int>.size * 2)
._copyAddressDiscriminatedFunctionPointer(
from: accessors.getterPtr,
discriminator: ComputedAccessorsPtr.getterPtrAuthKey)
componentSize += MemoryLayout<Int>.size
if header.isComputedSettable {
(buffer.baseAddress.unsafelyUnwrapped + MemoryLayout<Int>.size * 3)
._copyAddressDiscriminatedFunctionPointer(
from: accessors.setterPtr,
discriminator: header.isComputedMutating
? ComputedAccessorsPtr.mutatingSetterPtrAuthKey
: ComputedAccessorsPtr.nonmutatingSetterPtrAuthKey)
componentSize += MemoryLayout<Int>.size
}
if header.hasComputedArguments {
let arguments = _computedArguments
let argumentSize = _computedArgumentSize
buffer.storeBytes(of: argumentSize,
toByteOffset: componentSize,
as: Int.self)
componentSize += MemoryLayout<Int>.size
buffer.storeBytes(of: _computedArgumentWitnesses,
toByteOffset: componentSize,
as: ComputedArgumentWitnessesPtr.self)
componentSize += MemoryLayout<Int>.size
if header.isComputedInstantiatedFromExternalWithArguments {
// Include the extra matter for components instantiated from
// external property descriptors with arguments.
buffer.storeBytes(of: _computedArgumentWitnessSizeAdjustment,
toByteOffset: componentSize,
as: Int.self)
componentSize += MemoryLayout<Int>.size
}
let adjustedSize = argumentSize - _computedArgumentWitnessSizeAdjustment
let argumentDest =
buffer.baseAddress.unsafelyUnwrapped + componentSize
_computedArgumentWitnesses.copy(
arguments,
argumentDest,
adjustedSize)
if header.isComputedInstantiatedFromExternalWithArguments {
// The extra information for external property descriptor arguments
// can always be memcpy'd.
_memcpy(dest: argumentDest + adjustedSize,
src: arguments + adjustedSize,
size: UInt(_computedArgumentWitnessSizeAdjustment))
}
componentSize += argumentSize
}
case .external:
_internalInvariantFailure("should have been instantiated away")
}
buffer = UnsafeMutableRawBufferPointer(
start: buffer.baseAddress.unsafelyUnwrapped + componentSize,
count: buffer.count - componentSize)
}
internal enum ProjectionResult<NewValue, LeafValue> {
/// Continue projecting the key path with the given new value.
case `continue`(NewValue)
/// Stop projecting the key path and use the given value as the final
/// result of the projection.
case `break`(LeafValue)
internal var assumingContinue: NewValue {
switch self {
case .continue(let x):
return x
case .break:
_internalInvariantFailure("should not have stopped key path projection")
}
}
}
internal func _projectReadOnly<CurValue, NewValue, LeafValue>(
_ base: CurValue,
to: NewValue.Type,
endingWith: LeafValue.Type
) -> ProjectionResult<NewValue, LeafValue> {
switch value {
case .struct(let offset):
var base2 = base
return .continue(withUnsafeBytes(of: &base2) {
let p = $0.baseAddress.unsafelyUnwrapped.advanced(by: offset)
// The contents of the struct should be well-typed, so we can assume
// typed memory here.
return p.assumingMemoryBound(to: NewValue.self).pointee
})
case .class(let offset):
_internalInvariant(CurValue.self is AnyObject.Type,
"base is not a class")
let baseObj = unsafeBitCast(base, to: AnyObject.self)
let basePtr = UnsafeRawPointer(Builtin.bridgeToRawPointer(baseObj))
defer { _fixLifetime(baseObj) }
let offsetAddress = basePtr.advanced(by: offset)
// Perform an instantaneous record access on the address in order to
// ensure that the read will not conflict with an already in-progress
// 'modify' access.
Builtin.performInstantaneousReadAccess(offsetAddress._rawValue,
NewValue.self)
return .continue(offsetAddress
.assumingMemoryBound(to: NewValue.self)
.pointee)
case .get(id: _, accessors: let accessors, argument: let argument),
.mutatingGetSet(id: _, accessors: let accessors, argument: let argument),
.nonmutatingGetSet(id: _, accessors: let accessors, argument: let argument):
return .continue(accessors.getter()(base,
argument?.data.baseAddress ?? accessors._value,
argument?.data.count ?? 0))
case .optionalChain:
_internalInvariant(CurValue.self == Optional<NewValue>.self,
"should be unwrapping optional value")
_internalInvariant(_isOptional(LeafValue.self),
"leaf result should be optional")
if let baseValue = unsafeBitCast(base, to: Optional<NewValue>.self) {
return .continue(baseValue)
} else {
// TODO: A more efficient way of getting the `none` representation
// of a dynamically-optional type...
return .break((Optional<()>.none as Any) as! LeafValue)
}
case .optionalForce:
_internalInvariant(CurValue.self == Optional<NewValue>.self,
"should be unwrapping optional value")
return .continue(unsafeBitCast(base, to: Optional<NewValue>.self)!)
case .optionalWrap:
_internalInvariant(NewValue.self == Optional<CurValue>.self,
"should be wrapping optional value")
return .continue(
unsafeBitCast(base as Optional<CurValue>, to: NewValue.self))
}
}
internal func _projectMutableAddress<CurValue, NewValue>(
_ base: UnsafeRawPointer,
from _: CurValue.Type,
to _: NewValue.Type,
isRoot: Bool,
keepAlive: inout AnyObject?
) -> UnsafeRawPointer {
switch value {
case .struct(let offset):
return base.advanced(by: offset)
case .class(let offset):
// A class dereference should only occur at the root of a mutation,
// since otherwise it would be part of the reference prefix.
_internalInvariant(isRoot,
"class component should not appear in the middle of mutation")
// AnyObject memory can alias any class reference memory, so we can
// assume type here
let object = base.assumingMemoryBound(to: AnyObject.self).pointee
let offsetAddress = UnsafeRawPointer(Builtin.bridgeToRawPointer(object))
.advanced(by: offset)
// Keep the base alive for the duration of the derived access and also
// enforce exclusive access to the address.
keepAlive = ClassHolder._create(previous: keepAlive, instance: object,
accessingAddress: offsetAddress,
type: NewValue.self)
return offsetAddress
case .mutatingGetSet(id: _, accessors: let accessors,
argument: let argument):
let baseTyped = UnsafeMutablePointer(
mutating: base.assumingMemoryBound(to: CurValue.self))
let argValue = argument?.data.baseAddress ?? accessors._value
let argSize = argument?.data.count ?? 0
let writeback = MutatingWritebackBuffer<CurValue, NewValue>(
previous: keepAlive,
base: baseTyped,
set: accessors.mutatingSetter(),
argument: argValue,
argumentSize: argSize,
value: accessors.getter()(baseTyped.pointee, argValue, argSize))
keepAlive = writeback
// A maximally-abstracted, final, stored class property should have
// a stable address.
return UnsafeRawPointer(Builtin.addressof(&writeback.value))
case .nonmutatingGetSet(id: _, accessors: let accessors,
argument: let argument):
// A nonmutating property should only occur at the root of a mutation,
// since otherwise it would be part of the reference prefix.
_internalInvariant(isRoot,
"nonmutating component should not appear in the middle of mutation")
let baseValue = base.assumingMemoryBound(to: CurValue.self).pointee
let argValue = argument?.data.baseAddress ?? accessors._value
let argSize = argument?.data.count ?? 0
let writeback = NonmutatingWritebackBuffer<CurValue, NewValue>(
previous: keepAlive,
base: baseValue,
set: accessors.nonmutatingSetter(),
argument: argValue,
argumentSize: argSize,
value: accessors.getter()(baseValue, argValue, argSize))
keepAlive = writeback
// A maximally-abstracted, final, stored class property should have
// a stable address.
return UnsafeRawPointer(Builtin.addressof(&writeback.value))
case .optionalForce:
_internalInvariant(CurValue.self == Optional<NewValue>.self,
"should be unwrapping an optional value")
// Optional's layout happens to always put the payload at the start
// address of the Optional value itself, if a value is present at all.
let baseOptionalPointer
= base.assumingMemoryBound(to: Optional<NewValue>.self)
// Assert that a value exists
_ = baseOptionalPointer.pointee!
return base
case .optionalChain, .optionalWrap, .get:
_internalInvariantFailure("not a mutable key path component")
}
}
}
internal func _pop<T>(from: inout UnsafeRawBufferPointer,
as type: T.Type) -> T {
let buffer = _pop(from: &from, as: type, count: 1)
return buffer.baseAddress.unsafelyUnwrapped.pointee
}
internal func _pop<T>(from: inout UnsafeRawBufferPointer,
as: T.Type,
count: Int) -> UnsafeBufferPointer<T> {
_internalInvariant(_isPOD(T.self), "should be POD")
from = MemoryLayout<T>._roundingUpBaseToAlignment(from)
let byteCount = MemoryLayout<T>.stride * count
let result = UnsafeBufferPointer(
start: from.baseAddress.unsafelyUnwrapped.assumingMemoryBound(to: T.self),
count: count)
from = UnsafeRawBufferPointer(
start: from.baseAddress.unsafelyUnwrapped + byteCount,
count: from.count - byteCount)
return result
}
internal struct KeyPathBuffer {
internal var data: UnsafeRawBufferPointer
internal var trivial: Bool
internal var hasReferencePrefix: Bool
internal init(base: UnsafeRawPointer) {
let header = base.load(as: Header.self)
data = UnsafeRawBufferPointer(
start: base + MemoryLayout<Int>.size,
count: header.size)
trivial = header.trivial
hasReferencePrefix = header.hasReferencePrefix
}
internal init(partialData: UnsafeRawBufferPointer,
trivial: Bool = false,
hasReferencePrefix: Bool = false) {
self.data = partialData
self.trivial = trivial
self.hasReferencePrefix = hasReferencePrefix
}
internal var mutableData: UnsafeMutableRawBufferPointer {
return UnsafeMutableRawBufferPointer(mutating: data)
}
internal struct Builder {
internal var buffer: UnsafeMutableRawBufferPointer
internal init(_ buffer: UnsafeMutableRawBufferPointer) {
self.buffer = buffer
}
internal mutating func pushRaw(size: Int, alignment: Int)
-> UnsafeMutableRawBufferPointer {
var baseAddress = buffer.baseAddress.unsafelyUnwrapped
var misalign = Int(bitPattern: baseAddress) & (alignment - 1)
if misalign != 0 {
misalign = alignment - misalign
baseAddress = baseAddress.advanced(by: misalign)
}
let result = UnsafeMutableRawBufferPointer(
start: baseAddress,
count: size)
buffer = UnsafeMutableRawBufferPointer(
start: baseAddress + size,
count: buffer.count - size - misalign)
return result
}
internal mutating func push<T>(_ value: T) {
let buf = pushRaw(size: MemoryLayout<T>.size,
alignment: MemoryLayout<T>.alignment)
buf.storeBytes(of: value, as: T.self)
}
internal mutating func pushHeader(_ header: Header) {
push(header)
// Start the components at pointer alignment
_ = pushRaw(size: RawKeyPathComponent.Header.pointerAlignmentSkew,
alignment: 4)
}
}
internal struct Header {
internal var _value: UInt32
internal init(size: Int, trivial: Bool, hasReferencePrefix: Bool) {
_internalInvariant(size <= Int(Header.sizeMask), "key path too big")
_value = UInt32(size)
| (trivial ? Header.trivialFlag : 0)
| (hasReferencePrefix ? Header.hasReferencePrefixFlag : 0)
}
internal static var sizeMask: UInt32 {
return _SwiftKeyPathBufferHeader_SizeMask
}
internal static var reservedMask: UInt32 {
return _SwiftKeyPathBufferHeader_ReservedMask
}
internal static var trivialFlag: UInt32 {
return _SwiftKeyPathBufferHeader_TrivialFlag
}
internal static var hasReferencePrefixFlag: UInt32 {
return _SwiftKeyPathBufferHeader_HasReferencePrefixFlag
}
internal var size: Int { return Int(_value & Header.sizeMask) }
internal var trivial: Bool { return _value & Header.trivialFlag != 0 }
internal var hasReferencePrefix: Bool {
get {
return _value & Header.hasReferencePrefixFlag != 0
}
set {
if newValue {
_value |= Header.hasReferencePrefixFlag
} else {
_value &= ~Header.hasReferencePrefixFlag
}
}
}
// In a key path pattern, the "trivial" flag is used to indicate
// "instantiable in-line"
internal var instantiableInLine: Bool {
return trivial
}
internal func validateReservedBits() {
_precondition(_value & Header.reservedMask == 0,
"Reserved bits set to an unexpected bit pattern")
}
}
internal func destroy() {
// Short-circuit if nothing in the object requires destruction.
if trivial { return }
var bufferToDestroy = self
while true {
let (component, type) = bufferToDestroy.next()
component.destroy()
guard let _ = type else { break }
}
}
internal mutating func next() -> (RawKeyPathComponent, Any.Type?) {
let header = _pop(from: &data, as: RawKeyPathComponent.Header.self)
// Track if this is the last component of the reference prefix.
if header.endOfReferencePrefix {
_internalInvariant(self.hasReferencePrefix,
"beginMutation marker in non-reference-writable key path?")
self.hasReferencePrefix = false
}
var component = RawKeyPathComponent(header: header, body: data)
// Shrinkwrap the component buffer size.
let size = component.bodySize
component.body = UnsafeRawBufferPointer(start: component.body.baseAddress,
count: size)
_ = _pop(from: &data, as: Int8.self, count: size)
// fetch type, which is in the buffer unless it's the final component
let nextType: Any.Type?
if data.isEmpty {
nextType = nil
} else {
nextType = _pop(from: &data, as: Any.Type.self)
}
return (component, nextType)
}
}
// MARK: Library intrinsics for projecting key paths.
@_silgen_name("swift_getAtPartialKeyPath")
public // COMPILER_INTRINSIC
func _getAtPartialKeyPath<Root>(
root: Root,
keyPath: PartialKeyPath<Root>
) -> Any {
func open<Value>(_: Value.Type) -> Any {
return _getAtKeyPath(root: root,
keyPath: unsafeDowncast(keyPath, to: KeyPath<Root, Value>.self))
}
return _openExistential(type(of: keyPath).valueType, do: open)
}
@_silgen_name("swift_getAtAnyKeyPath")
public // COMPILER_INTRINSIC
func _getAtAnyKeyPath<RootValue>(
root: RootValue,
keyPath: AnyKeyPath
) -> Any? {
let (keyPathRoot, keyPathValue) = type(of: keyPath)._rootAndValueType
func openRoot<KeyPathRoot>(_: KeyPathRoot.Type) -> Any? {
guard let rootForKeyPath = root as? KeyPathRoot else {
return nil
}
func openValue<Value>(_: Value.Type) -> Any {
return _getAtKeyPath(root: rootForKeyPath,
keyPath: unsafeDowncast(keyPath, to: KeyPath<KeyPathRoot, Value>.self))
}
return _openExistential(keyPathValue, do: openValue)
}
return _openExistential(keyPathRoot, do: openRoot)
}
@_silgen_name("swift_getAtKeyPath")
public // COMPILER_INTRINSIC
func _getAtKeyPath<Root, Value>(
root: Root,
keyPath: KeyPath<Root, Value>
) -> Value {
return keyPath._projectReadOnly(from: root)
}
// The release that ends the access scope is guaranteed to happen
// immediately at the end_apply call because the continuation is a
// runtime call with a manual release (access scopes cannot be extended).
@_silgen_name("_swift_modifyAtWritableKeyPath_impl")
public // runtime entrypoint
func _modifyAtWritableKeyPath_impl<Root, Value>(
root: inout Root,
keyPath: WritableKeyPath<Root, Value>
) -> (UnsafeMutablePointer<Value>, AnyObject?) {
if type(of: keyPath).kind == .reference {
return _modifyAtReferenceWritableKeyPath_impl(root: root,
keyPath: _unsafeUncheckedDowncast(keyPath,
to: ReferenceWritableKeyPath<Root, Value>.self))
}
return _withUnprotectedUnsafePointer(to: &root) {
keyPath._projectMutableAddress(from: $0)
}
}
// The release that ends the access scope is guaranteed to happen
// immediately at the end_apply call because the continuation is a
// runtime call with a manual release (access scopes cannot be extended).
@_silgen_name("_swift_modifyAtReferenceWritableKeyPath_impl")
public // runtime entrypoint
func _modifyAtReferenceWritableKeyPath_impl<Root, Value>(
root: Root,
keyPath: ReferenceWritableKeyPath<Root, Value>
) -> (UnsafeMutablePointer<Value>, AnyObject?) {
return keyPath._projectMutableAddress(from: root)
}
@_silgen_name("swift_setAtWritableKeyPath")
public // COMPILER_INTRINSIC
func _setAtWritableKeyPath<Root, Value>(
root: inout Root,
keyPath: WritableKeyPath<Root, Value>,
value: __owned Value
) {
if type(of: keyPath).kind == .reference {
return _setAtReferenceWritableKeyPath(root: root,
keyPath: _unsafeUncheckedDowncast(keyPath,
to: ReferenceWritableKeyPath<Root, Value>.self),
value: value)
}
// TODO: we should be able to do this more efficiently than projecting.
let (addr, owner) = _withUnprotectedUnsafePointer(to: &root) {
keyPath._projectMutableAddress(from: $0)
}
addr.pointee = value
_fixLifetime(owner)
// FIXME: this needs a deallocation barrier to ensure that the
// release isn't extended, along with the access scope.
}
@_silgen_name("swift_setAtReferenceWritableKeyPath")
public // COMPILER_INTRINSIC
func _setAtReferenceWritableKeyPath<Root, Value>(
root: Root,
keyPath: ReferenceWritableKeyPath<Root, Value>,
value: __owned Value
) {
// TODO: we should be able to do this more efficiently than projecting.
let (addr, owner) = keyPath._projectMutableAddress(from: root)
addr.pointee = value
_fixLifetime(owner)
// FIXME: this needs a deallocation barrier to ensure that the
// release isn't extended, along with the access scope.
}
// MARK: Appending type system
// FIXME(ABI): The type relationships between KeyPath append operands are tricky
// and don't interact well with our overriding rules. Hack things by injecting
// a bunch of `appending` overloads as protocol extensions so they aren't
// constrained by being overrides, and so that we can use exact-type constraints
// on `Self` to prevent dynamically-typed methods from being inherited by
// statically-typed key paths.
/// An implementation detail of key path expressions; do not use this protocol
/// directly.
@_show_in_interface
public protocol _AppendKeyPath {}
extension _AppendKeyPath where Self == AnyKeyPath {
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Appending the key path passed as `path` is successful only if the
/// root type for `path` matches this key path's value type. This example
/// creates key paths from `Array<Int>` to `String` and from `String` to
/// `Int`, and then tries appending each to the other:
///
/// let arrayDescription: AnyKeyPath = \Array<Int>.description
/// let stringLength: AnyKeyPath = \String.count
///
/// // Creates a key path from `Array<Int>` to `Int`
/// let arrayDescriptionLength = arrayDescription.appending(path: stringLength)
///
/// let invalidKeyPath = stringLength.appending(path: arrayDescription)
/// // invalidKeyPath == nil
///
/// The second call to `appending(path:)` returns `nil`
/// because the root type of `arrayDescription`, `Array<Int>`, does not
/// match the value type of `stringLength`, `Int`.
///
/// - Parameter path: The key path to append.
/// - Returns: A key path from the root of this key path and the value type
/// of `path`, if `path` can be appended. If `path` can't be appended,
/// returns `nil`.
@inlinable
public func appending(path: AnyKeyPath) -> AnyKeyPath? {
return _tryToAppendKeyPaths(root: self, leaf: path)
}
}
extension _AppendKeyPath /* where Self == PartialKeyPath<T> */ {
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Appending the key path passed as `path` is successful only if the
/// root type for `path` matches this key path's value type. This example
/// creates key paths from `Array<Int>` to `String` and from `String` to
/// `Int`, and then tries appending each to the other:
///
/// let arrayDescription: PartialKeyPath<Array<Int>> = \.description
/// let stringLength: PartialKeyPath<String> = \.count
///
/// // Creates a key path from `Array<Int>` to `Int`
/// let arrayDescriptionLength = arrayDescription.appending(path: stringLength)
///
/// let invalidKeyPath = stringLength.appending(path: arrayDescription)
/// // invalidKeyPath == nil
///
/// The second call to `appending(path:)` returns `nil`
/// because the root type of `arrayDescription`, `Array<Int>`, does not
/// match the value type of `stringLength`, `Int`.
///
/// - Parameter path: The key path to append.
/// - Returns: A key path from the root of this key path and the value type
/// of `path`, if `path` can be appended. If `path` can't be appended,
/// returns `nil`.
@inlinable
public func appending<Root>(path: AnyKeyPath) -> PartialKeyPath<Root>?
where Self == PartialKeyPath<Root> {
return _tryToAppendKeyPaths(root: self, leaf: path)
}
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Appending the key path passed as `path` is successful only if the
/// root type for `path` matches this key path's value type. This example
/// creates a key path from `Array<Int>` to `String`, and then tries
/// appending compatible and incompatible key paths:
///
/// let arrayDescription: PartialKeyPath<Array<Int>> = \.description
///
/// // Creates a key path from `Array<Int>` to `Int`
/// let arrayDescriptionLength = arrayDescription.appending(path: \String.count)
///
/// let invalidKeyPath = arrayDescription.appending(path: \Double.isZero)
/// // invalidKeyPath == nil
///
/// The second call to `appending(path:)` returns `nil` because the root type
/// of the `path` parameter, `Double`, does not match the value type of
/// `arrayDescription`, `String`.
///
/// - Parameter path: The key path to append.
/// - Returns: A key path from the root of this key path to the value type
/// of `path`, if `path` can be appended. If `path` can't be appended,
/// returns `nil`.
@inlinable
public func appending<Root, AppendedRoot, AppendedValue>(
path: KeyPath<AppendedRoot, AppendedValue>
) -> KeyPath<Root, AppendedValue>?
where Self == PartialKeyPath<Root> {
return _tryToAppendKeyPaths(root: self, leaf: path)
}
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Appending the key path passed as `path` is successful only if the
/// root type for `path` matches this key path's value type.
///
/// - Parameter path: The reference writeable key path to append.
/// - Returns: A key path from the root of this key path to the value type
/// of `path`, if `path` can be appended. If `path` can't be appended,
/// returns `nil`.
@inlinable
public func appending<Root, AppendedRoot, AppendedValue>(
path: ReferenceWritableKeyPath<AppendedRoot, AppendedValue>
) -> ReferenceWritableKeyPath<Root, AppendedValue>?
where Self == PartialKeyPath<Root> {
return _tryToAppendKeyPaths(root: self, leaf: path)
}
}
extension _AppendKeyPath /* where Self == KeyPath<T,U> */ {
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Calling `appending(path:)` results in the same key path as if the
/// given key path had been specified using dot notation. In the following
/// example, `keyPath1` and `keyPath2` are equivalent:
///
/// let arrayDescription = \Array<Int>.description
/// let keyPath1 = arrayDescription.appending(path: \String.count)
///
/// let keyPath2 = \Array<Int>.description.count
///
/// - Parameter path: The key path to append.
/// - Returns: A key path from the root of this key path to the value type of
/// `path`.
@inlinable
public func appending<Root, Value, AppendedValue>(
path: KeyPath<Value, AppendedValue>
) -> KeyPath<Root, AppendedValue>
where Self: KeyPath<Root, Value> {
return _appendingKeyPaths(root: self, leaf: path)
}
/* TODO
public func appending<Root, Value, Leaf>(
path: Leaf,
// FIXME: Satisfy "Value generic param not used in signature" constraint
_: Value.Type = Value.self
) -> PartialKeyPath<Root>?
where Self: KeyPath<Root, Value>, Leaf == AnyKeyPath {
return _tryToAppendKeyPaths(root: self, leaf: path)
}
*/
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Calling `appending(path:)` results in the same key path as if the
/// given key path had been specified using dot notation.
///
/// - Parameter path: The key path to append.
/// - Returns: A key path from the root of this key path to the value type of
/// `path`.
@inlinable
public func appending<Root, Value, AppendedValue>(
path: ReferenceWritableKeyPath<Value, AppendedValue>
) -> ReferenceWritableKeyPath<Root, AppendedValue>
where Self == KeyPath<Root, Value> {
return _appendingKeyPaths(root: self, leaf: path)
}
}
extension _AppendKeyPath /* where Self == WritableKeyPath<T,U> */ {
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Calling `appending(path:)` results in the same key path as if the
/// given key path had been specified using dot notation.
///
/// - Parameter path: The key path to append.
/// - Returns: A key path from the root of this key path to the value type of
/// `path`.
@inlinable
public func appending<Root, Value, AppendedValue>(
path: WritableKeyPath<Value, AppendedValue>
) -> WritableKeyPath<Root, AppendedValue>
where Self == WritableKeyPath<Root, Value> {
return _appendingKeyPaths(root: self, leaf: path)
}
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Calling `appending(path:)` results in the same key path as if the
/// given key path had been specified using dot notation.
///
/// - Parameter path: The key path to append.
/// - Returns: A key path from the root of this key path to the value type of
/// `path`.
@inlinable
public func appending<Root, Value, AppendedValue>(
path: ReferenceWritableKeyPath<Value, AppendedValue>
) -> ReferenceWritableKeyPath<Root, AppendedValue>
where Self == WritableKeyPath<Root, Value> {
return _appendingKeyPaths(root: self, leaf: path)
}
}
extension _AppendKeyPath /* where Self == ReferenceWritableKeyPath<T,U> */ {
/// Returns a new key path created by appending the given key path to this
/// one.
///
/// Use this method to extend this key path to the value type of another key
/// path. Calling `appending(path:)` results in the same key path as if the
/// given key path had been specified using dot notation.
///
/// - Parameter path: The key path to append.
/// - Returns: A key path from the root of this key path to the value type of
/// `path`.
@inlinable
public func appending<Root, Value, AppendedValue>(
path: WritableKeyPath<Value, AppendedValue>
) -> ReferenceWritableKeyPath<Root, AppendedValue>
where Self == ReferenceWritableKeyPath<Root, Value> {
return _appendingKeyPaths(root: self, leaf: path)
}
}
/// Updates information pertaining to the types associated with each KeyPath.
///
/// Note: Currently we only distinguish between keypaths that traverse
/// only structs to get to the final value, and all other types.
/// This is done for performance reasons.
/// Other type information may be handled in the future to improve performance.
internal func _processOffsetForAppendedKeyPath(
appendedKeyPath: inout AnyKeyPath,
root: AnyKeyPath,
leaf: AnyKeyPath
) {
if let rootOffset = root.getOffsetFromStorage(),
let leafOffset = leaf.getOffsetFromStorage()
{
appendedKeyPath.assignOffsetToStorage(offset: rootOffset + leafOffset)
}
}
@usableFromInline
internal func _tryToAppendKeyPaths<Result: AnyKeyPath>(
root: AnyKeyPath,
leaf: AnyKeyPath
) -> Result? {
let (rootRoot, rootValue) = type(of: root)._rootAndValueType
let (leafRoot, leafValue) = type(of: leaf)._rootAndValueType
if rootValue != leafRoot {
return nil
}
func open<Root>(_: Root.Type) -> Result {
func open2<Value>(_: Value.Type) -> Result {
func open3<AppendedValue>(_: AppendedValue.Type) -> Result {
let typedRoot = unsafeDowncast(root, to: KeyPath<Root, Value>.self)
let typedLeaf = unsafeDowncast(leaf,
to: KeyPath<Value, AppendedValue>.self)
var result:AnyKeyPath = _appendingKeyPaths(root: typedRoot,
leaf: typedLeaf)
_processOffsetForAppendedKeyPath(appendedKeyPath: &result,
root: root, leaf: leaf)
return unsafeDowncast(result, to: Result.self)
}
return _openExistential(leafValue, do: open3)
}
return _openExistential(rootValue, do: open2)
}
return _openExistential(rootRoot, do: open)
}
@usableFromInline
internal func _appendingKeyPaths<
Root, Value, AppendedValue,
Result: KeyPath<Root, AppendedValue>
>(
root: KeyPath<Root, Value>,
leaf: KeyPath<Value, AppendedValue>
) -> Result {
let resultTy = type(of: root).appendedType(with: type(of: leaf))
var returnValue: AnyKeyPath = root.withBuffer {
var rootBuffer = $0
return leaf.withBuffer {
var leafBuffer = $0
// If either operand is the identity key path, then we should return
// the other operand back untouched.
if leafBuffer.data.isEmpty {
return unsafeDowncast(root, to: Result.self)
}
if rootBuffer.data.isEmpty {
return unsafeDowncast(leaf, to: Result.self)
}
// Reserve room for the appended KVC string, if both key paths are
// KVC-compatible.
let appendedKVCLength: Int, rootKVCLength: Int, leafKVCLength: Int
if root.getOffsetFromStorage() == nil, leaf.getOffsetFromStorage() == nil,
let rootPtr = root._kvcKeyPathStringPtr,
let leafPtr = leaf._kvcKeyPathStringPtr {
rootKVCLength = Int(_swift_stdlib_strlen(rootPtr))
leafKVCLength = Int(_swift_stdlib_strlen(leafPtr))
// root + "." + leaf
appendedKVCLength = rootKVCLength + 1 + leafKVCLength + 1
} else {
rootKVCLength = 0
leafKVCLength = 0
appendedKVCLength = 0
}
// Result buffer has room for both key paths' components, plus the
// header, plus space for the middle type.
// Align up the root so that we can put the component type after it.
let rootSize = MemoryLayout<Int>._roundingUpToAlignment(rootBuffer.data.count)
let resultSize = rootSize + leafBuffer.data.count
+ 2 * MemoryLayout<Int>.size
// Tail-allocate space for the KVC string.
let totalResultSize = MemoryLayout<Int32>
._roundingUpToAlignment(resultSize + appendedKVCLength)
var kvcStringBuffer: UnsafeMutableRawPointer? = nil
let result = resultTy._create(capacityInBytes: totalResultSize) {
var destBuffer = $0
// Remember where the tail-allocated KVC string buffer begins.
if appendedKVCLength > 0 {
kvcStringBuffer = destBuffer.baseAddress.unsafelyUnwrapped
.advanced(by: resultSize)
destBuffer = .init(start: destBuffer.baseAddress,
count: resultSize)
}
var destBuilder = KeyPathBuffer.Builder(destBuffer)
// Save space for the header.
let leafIsReferenceWritable = type(of: leaf).kind == .reference
destBuilder.pushHeader(KeyPathBuffer.Header(
size: resultSize - MemoryLayout<Int>.size,
trivial: rootBuffer.trivial && leafBuffer.trivial,
hasReferencePrefix: rootBuffer.hasReferencePrefix
|| leafIsReferenceWritable
))
let leafHasReferencePrefix = leafBuffer.hasReferencePrefix
// Clone the root components into the buffer.
while true {
let (component, type) = rootBuffer.next()
let isLast = type == nil
// If the leaf appended path has a reference prefix, then the
// entire root is part of the reference prefix.
let endOfReferencePrefix: Bool
if leafHasReferencePrefix {
endOfReferencePrefix = false
} else if isLast && leafIsReferenceWritable {
endOfReferencePrefix = true
} else {
endOfReferencePrefix = component.header.endOfReferencePrefix
}
component.clone(
into: &destBuilder.buffer,
endOfReferencePrefix: endOfReferencePrefix)
// Insert our endpoint type between the root and leaf components.
if let type = type {
destBuilder.push(type)
} else {
destBuilder.push(Value.self as Any.Type)
break
}
}
// Clone the leaf components into the buffer.
while true {
let (component, type) = leafBuffer.next()
component.clone(
into: &destBuilder.buffer,
endOfReferencePrefix: component.header.endOfReferencePrefix)
if let type = type {
destBuilder.push(type)
} else {
break
}
}
_internalInvariant(destBuilder.buffer.isEmpty,
"did not fill entire result buffer")
}
// Build the KVC string if there is one.
if root.getOffsetFromStorage() == nil,
leaf.getOffsetFromStorage() == nil {
if let kvcStringBuffer = kvcStringBuffer {
let rootPtr = root._kvcKeyPathStringPtr.unsafelyUnwrapped
let leafPtr = leaf._kvcKeyPathStringPtr.unsafelyUnwrapped
_memcpy(
dest: kvcStringBuffer,
src: rootPtr,
size: UInt(rootKVCLength))
kvcStringBuffer.advanced(by: rootKVCLength)
.storeBytes(of: 0x2E /* '.' */, as: CChar.self)
_memcpy(
dest: kvcStringBuffer.advanced(by: rootKVCLength + 1),
src: leafPtr,
size: UInt(leafKVCLength))
result._kvcKeyPathStringPtr =
UnsafePointer(kvcStringBuffer.assumingMemoryBound(to: CChar.self))
kvcStringBuffer.advanced(by: rootKVCLength + leafKVCLength + 1)
.storeBytes(of: 0 /* '\0' */, as: CChar.self)
}
}
return unsafeDowncast(result, to: Result.self)
}
}
_processOffsetForAppendedKeyPath(
appendedKeyPath: &returnValue,
root: root,
leaf: leaf
)
return returnValue as! Result
}
// The distance in bytes from the address point of a KeyPath object to its
// buffer header. Includes the size of the Swift heap object header and the
// pointer to the KVC string.
internal var keyPathObjectHeaderSize: Int {
return MemoryLayout<HeapObject>.size + MemoryLayout<Int>.size
}
internal var keyPathPatternHeaderSize: Int {
return 16
}
// Runtime entry point to instantiate a key path object.
// Note that this has a compatibility override shim in the runtime so that
// future compilers can backward-deploy support for instantiating new key path
// pattern features.
@_cdecl("swift_getKeyPathImpl")
public func _swift_getKeyPath(pattern: UnsafeMutableRawPointer,
arguments: UnsafeRawPointer)
-> UnsafeRawPointer {
// The key path pattern is laid out like a key path object, with a few
// modifications:
// - Pointers in the instantiated object are compressed into 32-bit
// relative offsets in the pattern.
// - The pattern begins with a field that's either zero, for a pattern that
// depends on instantiation arguments, or that's a relative reference to
// a global mutable pointer variable, which can be initialized to a single
// shared instantiation of this pattern.
// - Instead of the two-word object header with isa and refcount, two
// pointers to metadata accessors are provided for the root and leaf
// value types of the key path.
// - Components may have unresolved forms that require instantiation.
// - Type metadata and protocol conformance pointers are replaced with
// relative-referenced accessor functions that instantiate the
// needed generic argument when called.
//
// The pattern never precomputes the capabilities of the key path (readonly/
// writable/reference-writable), nor does it encode the reference prefix.
// These are resolved dynamically, so that they always reflect the dynamic
// capability of the properties involved.
let oncePtrPtr = pattern
let patternPtr = pattern.advanced(by: 4)
let bufferHeader = patternPtr.load(fromByteOffset: keyPathPatternHeaderSize,
as: KeyPathBuffer.Header.self)
bufferHeader.validateReservedBits()
// If the first word is nonzero, it relative-references a cache variable
// we can use to reference a single shared instantiation of this key path.
let oncePtrOffset = oncePtrPtr.load(as: Int32.self)
let oncePtr: UnsafeRawPointer?
if oncePtrOffset != 0 {
let theOncePtr = _resolveRelativeAddress(oncePtrPtr, oncePtrOffset)
oncePtr = theOncePtr
// See whether we already instantiated this key path.
// This is a non-atomic load because the instantiated pointer will be
// written with a release barrier, and loads of the instantiated key path
// ought to carry a dependency through this loaded pointer.
let existingInstance = theOncePtr.load(as: UnsafeRawPointer?.self)
if let existingInstance = existingInstance {
// Return the instantiated object at +1.
let object = Unmanaged<AnyKeyPath>.fromOpaque(existingInstance)
// TODO: This retain will be unnecessary once we support global objects
// with inert refcounting.
_ = object.retain()
return existingInstance
}
} else {
oncePtr = nil
}
// Instantiate a new key path object modeled on the pattern.
// Do a pass to determine the class of the key path we'll be instantiating
// and how much space we'll need for it.
let (keyPathClass, rootType, size, _)
= _getKeyPathClassAndInstanceSizeFromPattern(patternPtr, arguments)
var pureStructOffset: UInt32? = nil
// Allocate the instance.
let instance = keyPathClass._create(capacityInBytes: size) { instanceData in
// Instantiate the pattern into the instance.
pureStructOffset = _instantiateKeyPathBuffer(
patternPtr,
instanceData,
rootType,
arguments
)
}
// Adopt the KVC string from the pattern.
let kvcStringBase = patternPtr.advanced(by: 12)
let kvcStringOffset = kvcStringBase.load(as: Int32.self)
if kvcStringOffset == 0 {
// Null pointer.
instance._kvcKeyPathStringPtr = nil
} else {
let kvcStringPtr = _resolveRelativeAddress(kvcStringBase, kvcStringOffset)
instance._kvcKeyPathStringPtr =
kvcStringPtr.assumingMemoryBound(to: CChar.self)
}
if instance._kvcKeyPathStringPtr == nil, let offset = pureStructOffset {
instance.assignOffsetToStorage(offset: Int(offset))
}
// If we can cache this instance as a shared instance, do so.
if let oncePtr = oncePtr {
// Try to replace a null pointer in the cache variable with the instance
// pointer.
let instancePtr = Unmanaged.passRetained(instance)
while true {
let (oldValue, won) = Builtin.cmpxchg_seqcst_seqcst_Word(
oncePtr._rawValue,
0._builtinWordValue,
UInt(bitPattern: instancePtr.toOpaque())._builtinWordValue)
// If the exchange succeeds, then the instance we formed is the canonical
// one.
if Bool(won) {
break
}
// Otherwise, someone raced with us to instantiate the key path pattern
// and won. Their instance should be just as good as ours, so we can take
// that one and let ours get deallocated.
if let existingInstance = UnsafeRawPointer(bitPattern: Int(oldValue)) {
// Return the instantiated object at +1.
let object = Unmanaged<AnyKeyPath>.fromOpaque(existingInstance)
// TODO: This retain will be unnecessary once we support global objects
// with inert refcounting.
_ = object.retain()
// Release the instance we created.
instancePtr.release()
return existingInstance
} else {
// Try the cmpxchg again if it spuriously failed.
continue
}
}
}
return UnsafeRawPointer(Unmanaged.passRetained(instance).toOpaque())
}
// A reference to metadata, which is a pointer to a mangled name.
internal typealias MetadataReference = UnsafeRawPointer
// Determine the length of the given mangled name.
internal func _getSymbolicMangledNameLength(_ base: UnsafeRawPointer) -> Int {
var end = base
while let current = Optional(end.load(as: UInt8.self)), current != 0 {
// Skip the current character
end = end + 1
// Skip over a symbolic reference
if current >= 0x1 && current <= 0x17 {
end += 4
} else if current >= 0x18 && current <= 0x1F {
end += MemoryLayout<Int>.size
}
}
return end - base
}
// Resolve a mangled name in a generic environment, described by either a
// flat GenericEnvironment * (if the bottom tag bit is 0) or possibly-nested
// ContextDescriptor * (if the bottom tag bit is 1)
internal func _getTypeByMangledNameInEnvironmentOrContext(
_ name: UnsafePointer<UInt8>,
_ nameLength: UInt,
genericEnvironmentOrContext: UnsafeRawPointer?,
genericArguments: UnsafeRawPointer?)
-> Any.Type? {
let taggedPointer = UInt(bitPattern: genericEnvironmentOrContext)
if taggedPointer & 1 == 0 {
return _getTypeByMangledNameInEnvironment(name, nameLength,
genericEnvironment: genericEnvironmentOrContext,
genericArguments: genericArguments)
} else {
let context = UnsafeRawPointer(bitPattern: taggedPointer & ~1)
return _getTypeByMangledNameInContext(name, nameLength,
genericContext: context,
genericArguments: genericArguments)
}
}
// Resolve the given generic argument reference to a generic argument.
internal func _resolveKeyPathGenericArgReference(
_ reference: UnsafeRawPointer,
genericEnvironment: UnsafeRawPointer?,
arguments: UnsafeRawPointer?)
-> UnsafeRawPointer {
// If the low bit is clear, it's a direct reference to the argument.
if (UInt(bitPattern: reference) & 0x01 == 0) {
return reference
}
// Adjust the reference.
let referenceStart = reference - 1
// If we have a symbolic reference to an accessor, call it.
let first = referenceStart.load(as: UInt8.self)
if first == 255 && reference.load(as: UInt8.self) == 9 {
typealias MetadataAccessor =
@convention(c) (UnsafeRawPointer?) -> UnsafeRawPointer
// Unaligned load of the offset.
let pointerReference = reference + 1
var offset: Int32 = 0
_memcpy(dest: &offset, src: pointerReference, size: 4)
let accessorPtrRaw = _resolveCompactFunctionPointer(pointerReference, offset)
let accessorPtrSigned =
_PtrAuth.sign(pointer: accessorPtrRaw,
key: .processIndependentCode,
discriminator: _PtrAuth.discriminator(for: MetadataAccessor.self))
let accessor = unsafeBitCast(accessorPtrSigned, to: MetadataAccessor.self)
return accessor(arguments)
}
let nameLength = _getSymbolicMangledNameLength(referenceStart)
let namePtr = referenceStart.bindMemory(to: UInt8.self,
capacity: nameLength + 1)
// FIXME: Could extract this information from the mangled name.
guard let result =
_getTypeByMangledNameInEnvironmentOrContext(namePtr, UInt(nameLength),
genericEnvironmentOrContext: genericEnvironment,
genericArguments: arguments)
else {
let nameStr = String._fromUTF8Repairing(
UnsafeBufferPointer(start: namePtr, count: nameLength)
).0
fatalError("could not demangle keypath type from '\(nameStr)'")
}
return unsafeBitCast(result, to: UnsafeRawPointer.self)
}
// Resolve the given metadata reference to (type) metadata.
internal func _resolveKeyPathMetadataReference(
_ reference: UnsafeRawPointer,
genericEnvironment: UnsafeRawPointer?,
arguments: UnsafeRawPointer?)
-> Any.Type {
return unsafeBitCast(
_resolveKeyPathGenericArgReference(
reference,
genericEnvironment: genericEnvironment,
arguments: arguments),
to: Any.Type.self)
}
internal enum KeyPathStructOrClass {
case `struct`, `class`
}
internal enum KeyPathPatternStoredOffset {
case inline(UInt32)
case outOfLine(UInt32)
case unresolvedFieldOffset(UInt32)
case unresolvedIndirectOffset(UnsafePointer<UInt>)
}
internal struct KeyPathPatternComputedArguments {
var getLayout: KeyPathComputedArgumentLayoutFn
var witnesses: ComputedArgumentWitnessesPtr
var initializer: KeyPathComputedArgumentInitializerFn
}
internal protocol KeyPathPatternVisitor {
mutating func visitHeader(genericEnvironment: UnsafeRawPointer?,
rootMetadataRef: MetadataReference,
leafMetadataRef: MetadataReference,
kvcCompatibilityString: UnsafeRawPointer?)
mutating func visitStoredComponent(kind: KeyPathStructOrClass,
mutable: Bool,
offset: KeyPathPatternStoredOffset)
mutating func visitComputedComponent(mutating: Bool,
idKind: KeyPathComputedIDKind,
idResolution: KeyPathComputedIDResolution,
idValueBase: UnsafeRawPointer,
idValue: Int32,
getter: UnsafeRawPointer,
setter: UnsafeRawPointer?,
arguments: KeyPathPatternComputedArguments?,
externalArgs: UnsafeBufferPointer<Int32>?)
mutating func visitOptionalChainComponent()
mutating func visitOptionalForceComponent()
mutating func visitOptionalWrapComponent()
mutating func visitIntermediateComponentType(metadataRef: MetadataReference)
mutating func finish()
}
internal func _resolveRelativeAddress(_ base: UnsafeRawPointer,
_ offset: Int32) -> UnsafeRawPointer {
// Sign-extend the offset to pointer width and add with wrap on overflow.
return UnsafeRawPointer(bitPattern: Int(bitPattern: base) &+ Int(offset))
.unsafelyUnwrapped
}
internal func _resolveRelativeIndirectableAddress(_ base: UnsafeRawPointer,
_ offset: Int32)
-> UnsafeRawPointer {
// Low bit indicates whether the reference is indirected or not.
if offset & 1 != 0 {
let ptrToPtr = _resolveRelativeAddress(base, offset - 1)
return ptrToPtr.load(as: UnsafeRawPointer.self)
}
return _resolveRelativeAddress(base, offset)
}
internal func _resolveCompactFunctionPointer(_ base: UnsafeRawPointer, _ offset: Int32)
-> UnsafeRawPointer {
#if SWIFT_COMPACT_ABSOLUTE_FUNCTION_POINTER
return UnsafeRawPointer(bitPattern: Int(offset)).unsafelyUnwrapped
#else
return _resolveRelativeAddress(base, offset)
#endif
}
internal func _loadRelativeAddress<T>(at: UnsafeRawPointer,
fromByteOffset: Int = 0,
as: T.Type) -> T {
let offset = at.load(fromByteOffset: fromByteOffset, as: Int32.self)
return unsafeBitCast(_resolveRelativeAddress(at + fromByteOffset, offset),
to: T.self)
}
internal func _walkKeyPathPattern<W: KeyPathPatternVisitor>(
_ pattern: UnsafeRawPointer,
walker: inout W) {
// Visit the header.
let genericEnvironment = _loadRelativeAddress(at: pattern,
as: UnsafeRawPointer.self)
let rootMetadataRef = _loadRelativeAddress(at: pattern, fromByteOffset: 4,
as: MetadataReference.self)
let leafMetadataRef = _loadRelativeAddress(at: pattern, fromByteOffset: 8,
as: MetadataReference.self)
let kvcString = _loadRelativeAddress(at: pattern, fromByteOffset: 12,
as: UnsafeRawPointer.self)
walker.visitHeader(genericEnvironment: genericEnvironment,
rootMetadataRef: rootMetadataRef,
leafMetadataRef: leafMetadataRef,
kvcCompatibilityString: kvcString)
func visitStored(header: RawKeyPathComponent.Header,
componentBuffer: inout UnsafeRawBufferPointer) {
// Decode a stored property. A small offset may be stored inline in the
// header word, or else be stored out-of-line, or need instantiation of some
// kind.
let offset: KeyPathPatternStoredOffset
switch header.storedOffsetPayload {
case RawKeyPathComponent.Header.outOfLineOffsetPayload:
offset = .outOfLine(_pop(from: &componentBuffer,
as: UInt32.self))
case RawKeyPathComponent.Header.unresolvedFieldOffsetPayload:
offset = .unresolvedFieldOffset(_pop(from: &componentBuffer,
as: UInt32.self))
case RawKeyPathComponent.Header.unresolvedIndirectOffsetPayload:
let base = componentBuffer.baseAddress.unsafelyUnwrapped
let relativeOffset = _pop(from: &componentBuffer,
as: Int32.self)
let ptr = _resolveRelativeIndirectableAddress(base, relativeOffset)
offset = .unresolvedIndirectOffset(
ptr.assumingMemoryBound(to: UInt.self))
default:
offset = .inline(header.storedOffsetPayload)
}
let kind: KeyPathStructOrClass = header.kind == .struct
? .struct : .class
walker.visitStoredComponent(kind: kind,
mutable: header.isStoredMutable,
offset: offset)
}
func popComputedAccessors(header: RawKeyPathComponent.Header,
componentBuffer: inout UnsafeRawBufferPointer)
-> (idValueBase: UnsafeRawPointer,
idValue: Int32,
getter: UnsafeRawPointer,
setter: UnsafeRawPointer?) {
let idValueBase = componentBuffer.baseAddress.unsafelyUnwrapped
let idValue = _pop(from: &componentBuffer, as: Int32.self)
let getterBase = componentBuffer.baseAddress.unsafelyUnwrapped
let getterRef = _pop(from: &componentBuffer, as: Int32.self)
let getter = _resolveCompactFunctionPointer(getterBase, getterRef)
let setter: UnsafeRawPointer?
if header.isComputedSettable {
let setterBase = componentBuffer.baseAddress.unsafelyUnwrapped
let setterRef = _pop(from: &componentBuffer, as: Int32.self)
setter = _resolveCompactFunctionPointer(setterBase, setterRef)
} else {
setter = nil
}
return (idValueBase: idValueBase, idValue: idValue,
getter: getter, setter: setter)
}
func popComputedArguments(header: RawKeyPathComponent.Header,
componentBuffer: inout UnsafeRawBufferPointer)
-> KeyPathPatternComputedArguments? {
if header.hasComputedArguments {
let getLayoutBase = componentBuffer.baseAddress.unsafelyUnwrapped
let getLayoutRef = _pop(from: &componentBuffer, as: Int32.self)
let getLayoutRaw = _resolveCompactFunctionPointer(getLayoutBase, getLayoutRef)
let getLayoutSigned = _PtrAuth.sign(pointer: getLayoutRaw,
key: .processIndependentCode,
discriminator: _PtrAuth.discriminator(for: KeyPathComputedArgumentLayoutFn.self))
let getLayout = unsafeBitCast(getLayoutSigned,
to: KeyPathComputedArgumentLayoutFn.self)
let witnessesBase = componentBuffer.baseAddress.unsafelyUnwrapped
let witnessesRef = _pop(from: &componentBuffer, as: Int32.self)
let witnesses: UnsafeRawPointer
if witnessesRef == 0 {
witnesses = __swift_keyPathGenericWitnessTable_addr()
} else {
witnesses = _resolveRelativeAddress(witnessesBase, witnessesRef)
}
let initializerBase = componentBuffer.baseAddress.unsafelyUnwrapped
let initializerRef = _pop(from: &componentBuffer, as: Int32.self)
let initializerRaw = _resolveCompactFunctionPointer(initializerBase,
initializerRef)
let initializerSigned = _PtrAuth.sign(pointer: initializerRaw,
key: .processIndependentCode,
discriminator: _PtrAuth.discriminator(for: KeyPathComputedArgumentInitializerFn.self))
let initializer = unsafeBitCast(initializerSigned,
to: KeyPathComputedArgumentInitializerFn.self)
return KeyPathPatternComputedArguments(getLayout: getLayout,
witnesses: ComputedArgumentWitnessesPtr(witnesses),
initializer: initializer)
} else {
return nil
}
}
// We declare this down here to avoid the temptation to use it within
// the functions above.
let bufferPtr = pattern.advanced(by: keyPathPatternHeaderSize)
let bufferHeader = bufferPtr.load(as: KeyPathBuffer.Header.self)
var buffer = UnsafeRawBufferPointer(start: bufferPtr + 4,
count: bufferHeader.size)
while !buffer.isEmpty {
let header = _pop(from: &buffer,
as: RawKeyPathComponent.Header.self)
// Ensure that we pop an amount of data consistent with what
// RawKeyPathComponent.Header.patternComponentBodySize computes.
var bufferSizeBefore = 0
var expectedPop = 0
_internalInvariant({
bufferSizeBefore = buffer.count
expectedPop = header.patternComponentBodySize
return true
}())
switch header.kind {
case .class, .struct:
visitStored(header: header, componentBuffer: &buffer)
case .computed:
let (idValueBase, idValue, getter, setter)
= popComputedAccessors(header: header,
componentBuffer: &buffer)
// If there are arguments, gather those too.
let arguments = popComputedArguments(header: header,
componentBuffer: &buffer)
walker.visitComputedComponent(mutating: header.isComputedMutating,
idKind: header.computedIDKind,
idResolution: header.computedIDResolution,
idValueBase: idValueBase,
idValue: idValue,
getter: getter,
setter: setter,
arguments: arguments,
externalArgs: nil)
case .optionalChain:
walker.visitOptionalChainComponent()
case .optionalWrap:
walker.visitOptionalWrapComponent()
case .optionalForce:
walker.visitOptionalForceComponent()
case .external:
// Look at the external property descriptor to see if we should take it
// over the component given in the pattern.
let genericParamCount = Int(header.payload)
let descriptorBase = buffer.baseAddress.unsafelyUnwrapped
let descriptorOffset = _pop(from: &buffer,
as: Int32.self)
let descriptor =
_resolveRelativeIndirectableAddress(descriptorBase, descriptorOffset)
let descriptorHeader =
descriptor.load(as: RawKeyPathComponent.Header.self)
if descriptorHeader.isTrivialPropertyDescriptor {
// If the descriptor is trivial, then use the local candidate.
// Skip the external generic parameter accessors to get to it.
_ = _pop(from: &buffer, as: Int32.self, count: genericParamCount)
continue
}
// Grab the generic parameter accessors to pass to the external component.
let externalArgs = _pop(from: &buffer, as: Int32.self,
count: genericParamCount)
// Grab the header for the local candidate in case we need it for
// a computed property.
let localCandidateHeader = _pop(from: &buffer,
as: RawKeyPathComponent.Header.self)
let localCandidateSize = localCandidateHeader.patternComponentBodySize
_internalInvariant({
expectedPop += localCandidateSize + 4
return true
}())
let descriptorSize = descriptorHeader.propertyDescriptorBodySize
var descriptorBuffer = UnsafeRawBufferPointer(start: descriptor + 4,
count: descriptorSize)
// Look at what kind of component the external property has.
switch descriptorHeader.kind {
case .struct, .class:
// A stored component. We can instantiate it
// without help from the local candidate.
_ = _pop(from: &buffer, as: UInt8.self, count: localCandidateSize)
visitStored(header: descriptorHeader,
componentBuffer: &descriptorBuffer)
case .computed:
// A computed component. The accessors come from the descriptor.
let (idValueBase, idValue, getter, setter)
= popComputedAccessors(header: descriptorHeader,
componentBuffer: &descriptorBuffer)
// Get the arguments from the external descriptor and/or local candidate
// component.
let arguments: KeyPathPatternComputedArguments?
if localCandidateHeader.kind == .computed
&& localCandidateHeader.hasComputedArguments {
// If both have arguments, then we have to build a bit of a chimera.
// The canonical identity and accessors come from the descriptor,
// but the argument equality/hash handling is still as described
// in the local candidate.
// We don't need the local candidate's accessors.
_ = popComputedAccessors(header: localCandidateHeader,
componentBuffer: &buffer)
// We do need the local arguments.
arguments = popComputedArguments(header: localCandidateHeader,
componentBuffer: &buffer)
} else {
// If the local candidate doesn't have arguments, we don't need
// anything from it at all.
_ = _pop(from: &buffer, as: UInt8.self, count: localCandidateSize)
arguments = nil
}
walker.visitComputedComponent(
mutating: descriptorHeader.isComputedMutating,
idKind: descriptorHeader.computedIDKind,
idResolution: descriptorHeader.computedIDResolution,
idValueBase: idValueBase,
idValue: idValue,
getter: getter,
setter: setter,
arguments: arguments,
externalArgs: genericParamCount > 0 ? externalArgs : nil)
case .optionalChain, .optionalWrap, .optionalForce, .external:
_internalInvariantFailure("not possible for property descriptor")
}
}
// Check that we consumed the expected amount of data from the pattern.
_internalInvariant(
{
// Round the amount of data we read up to alignment.
let popped = MemoryLayout<Int32>._roundingUpToAlignment(
bufferSizeBefore - buffer.count)
return expectedPop == popped
}(),
"""
component size consumed during pattern walk does not match \
component size returned by patternComponentBodySize
""")
// Break if this is the last component.
if buffer.isEmpty { break }
// Otherwise, pop the intermediate component type accessor and
// go around again.
let componentTypeBase = buffer.baseAddress.unsafelyUnwrapped
let componentTypeOffset = _pop(from: &buffer, as: Int32.self)
let componentTypeRef = _resolveRelativeAddress(componentTypeBase,
componentTypeOffset)
walker.visitIntermediateComponentType(metadataRef: componentTypeRef)
_internalInvariant(!buffer.isEmpty)
}
// We should have walked the entire pattern.
_internalInvariant(buffer.isEmpty, "did not walk entire pattern buffer")
walker.finish()
}
internal struct GetKeyPathClassAndInstanceSizeFromPattern
: KeyPathPatternVisitor {
var size: Int = MemoryLayout<Int>.size // start with one word for the header
var capability: KeyPathKind = .value
var didChain: Bool = false
var root: Any.Type!
var leaf: Any.Type!
var genericEnvironment: UnsafeRawPointer?
let patternArgs: UnsafeRawPointer?
var structOffset: UInt32 = 0
var isPureStruct: [Bool] = []
init(patternArgs: UnsafeRawPointer?) {
self.patternArgs = patternArgs
}
mutating func roundUpToPointerAlignment() {
size = MemoryLayout<Int>._roundingUpToAlignment(size)
}
mutating func visitHeader(genericEnvironment: UnsafeRawPointer?,
rootMetadataRef: MetadataReference,
leafMetadataRef: MetadataReference,
kvcCompatibilityString: UnsafeRawPointer?) {
self.genericEnvironment = genericEnvironment
// Get the root and leaf type metadata so we can form the class type
// for the entire key path.
root = _resolveKeyPathMetadataReference(
rootMetadataRef,
genericEnvironment: genericEnvironment,
arguments: patternArgs)
leaf = _resolveKeyPathMetadataReference(
leafMetadataRef,
genericEnvironment: genericEnvironment,
arguments: patternArgs)
}
mutating func visitStoredComponent(kind: KeyPathStructOrClass,
mutable: Bool,
offset: KeyPathPatternStoredOffset) {
// Mutable class properties can be the root of a reference mutation.
// Mutable struct properties pass through the existing capability.
if mutable {
switch kind {
case .class:
capability = .reference
case .struct:
break
}
} else {
// Immutable properties can only be read.
capability = .readOnly
}
// The size of the instantiated component depends on whether we can fit
// the offset inline.
switch offset {
case .inline:
size += 4
case .outOfLine, .unresolvedFieldOffset, .unresolvedIndirectOffset:
size += 8
}
}
mutating func visitComputedComponent(mutating: Bool,
idKind: KeyPathComputedIDKind,
idResolution: KeyPathComputedIDResolution,
idValueBase: UnsafeRawPointer,
idValue: Int32,
getter: UnsafeRawPointer,
setter: UnsafeRawPointer?,
arguments: KeyPathPatternComputedArguments?,
externalArgs: UnsafeBufferPointer<Int32>?) {
let settable = setter != nil
switch (settable, mutating) {
case (false, false):
// If the property is get-only, the capability becomes read-only, unless
// we get another reference-writable component.
capability = .readOnly
case (true, false):
capability = .reference
case (true, true):
// Writable if the base is. No effect.
break
case (false, true):
_internalInvariantFailure("unpossible")
}
// Save space for the header...
size += 4
roundUpToPointerAlignment()
// ...id, getter, and maybe setter...
size += MemoryLayout<Int>.size * 2
if settable {
size += MemoryLayout<Int>.size
}
// ...and the arguments, if any.
let argumentHeaderSize = MemoryLayout<Int>.size * 2
switch (arguments, externalArgs) {
case (nil, nil):
break
case (let arguments?, nil):
size += argumentHeaderSize
// If we have arguments, calculate how much space they need by invoking
// the layout function.
let (addedSize, addedAlignmentMask) = arguments.getLayout(patternArgs)
// TODO: Handle over-aligned values
_internalInvariant(addedAlignmentMask < MemoryLayout<Int>.alignment,
"overaligned computed property element not supported")
size += addedSize
case (let arguments?, let externalArgs?):
// If we're referencing an external declaration, and it takes captured
// arguments, then we have to build a bit of a chimera. The canonical
// identity and accessors come from the descriptor, but the argument
// handling is still as described in the local candidate.
size += argumentHeaderSize
let (addedSize, addedAlignmentMask) = arguments.getLayout(patternArgs)
// TODO: Handle over-aligned values
_internalInvariant(addedAlignmentMask < MemoryLayout<Int>.alignment,
"overaligned computed property element not supported")
size += addedSize
// We also need to store the size of the local arguments so we can
// find the external component arguments.
roundUpToPointerAlignment()
size += RawKeyPathComponent.Header.externalWithArgumentsExtraSize
size += MemoryLayout<Int>.size * externalArgs.count
case (nil, let externalArgs?):
// If we're instantiating an external property with a local
// candidate that has no arguments, then things are a little
// easier. We only need to instantiate the generic
// arguments for the external component's accessors.
size += argumentHeaderSize
size += MemoryLayout<Int>.size * externalArgs.count
}
}
mutating func visitOptionalChainComponent() {
// Optional chaining forces the entire keypath to be read-only, even if
// there are further reference-writable components.
didChain = true
capability = .readOnly
size += 4
}
mutating func visitOptionalWrapComponent() {
// Optional chaining forces the entire keypath to be read-only, even if
// there are further reference-writable components.
didChain = true
capability = .readOnly
size += 4
}
mutating func visitOptionalForceComponent() {
// Force-unwrapping passes through the mutability of the preceding keypath.
size += 4
}
mutating
func visitIntermediateComponentType(metadataRef _: MetadataReference) {
// The instantiated component type will be stored in the instantiated
// object.
roundUpToPointerAlignment()
size += MemoryLayout<Int>.size
}
mutating func finish() {
}
}
internal func _getKeyPathClassAndInstanceSizeFromPattern(
_ pattern: UnsafeRawPointer,
_ arguments: UnsafeRawPointer
) -> (
keyPathClass: AnyKeyPath.Type,
rootType: Any.Type,
size: Int,
alignmentMask: Int
) {
var walker = GetKeyPathClassAndInstanceSizeFromPattern(patternArgs: arguments)
_walkKeyPathPattern(pattern, walker: &walker)
// Chaining always renders the whole key path read-only.
if walker.didChain {
walker.capability = .readOnly
}
// Grab the class object for the key path type we'll end up with.
func openRoot<Root>(_: Root.Type) -> AnyKeyPath.Type {
func openLeaf<Leaf>(_: Leaf.Type) -> AnyKeyPath.Type {
switch walker.capability {
case .readOnly:
return KeyPath<Root, Leaf>.self
case .value:
return WritableKeyPath<Root, Leaf>.self
case .reference:
return ReferenceWritableKeyPath<Root, Leaf>.self
}
}
return _openExistential(walker.leaf!, do: openLeaf)
}
let classTy = _openExistential(walker.root!, do: openRoot)
return (keyPathClass: classTy,
rootType: walker.root!,
size: walker.size,
// FIXME: Handle overalignment
alignmentMask: MemoryLayout<Int>._alignmentMask)
}
internal struct InstantiateKeyPathBuffer: KeyPathPatternVisitor {
var destData: UnsafeMutableRawBufferPointer
var genericEnvironment: UnsafeRawPointer?
let patternArgs: UnsafeRawPointer?
var base: Any.Type
var structOffset: UInt32 = 0
var isPureStruct: [Bool] = []
init(destData: UnsafeMutableRawBufferPointer,
patternArgs: UnsafeRawPointer?,
root: Any.Type) {
self.destData = destData
self.patternArgs = patternArgs
self.base = root
}
// Track the triviality of the resulting object data.
var isTrivial: Bool = true
// Track where the reference prefix begins.
var endOfReferencePrefixComponent: UnsafeMutableRawPointer? = nil
var previousComponentAddr: UnsafeMutableRawPointer? = nil
mutating func adjustDestForAlignment<T>(of: T.Type) -> (
baseAddress: UnsafeMutableRawPointer,
misalign: Int
) {
let alignment = MemoryLayout<T>.alignment
var baseAddress = destData.baseAddress.unsafelyUnwrapped
var misalign = Int(bitPattern: baseAddress) & (alignment - 1)
if misalign != 0 {
misalign = alignment - misalign
baseAddress = baseAddress.advanced(by: misalign)
}
return (baseAddress, misalign)
}
mutating func pushDest<T>(_ value: T) {
_internalInvariant(_isPOD(T.self))
let size = MemoryLayout<T>.size
let (baseAddress, misalign) = adjustDestForAlignment(of: T.self)
_withUnprotectedUnsafeBytes(of: value) {
_memcpy(dest: baseAddress, src: $0.baseAddress.unsafelyUnwrapped,
size: UInt(size))
}
destData = UnsafeMutableRawBufferPointer(
start: baseAddress + size,
count: destData.count - size - misalign)
}
mutating func pushAddressDiscriminatedFunctionPointer(
_ unsignedPointer: UnsafeRawPointer,
discriminator: UInt64
) {
let size = MemoryLayout<UnsafeRawPointer>.size
let (baseAddress, misalign) =
adjustDestForAlignment(of: UnsafeRawPointer.self)
baseAddress._storeFunctionPointerWithAddressDiscrimination(
unsignedPointer, discriminator: discriminator)
destData = UnsafeMutableRawBufferPointer(
start: baseAddress + size,
count: destData.count - size - misalign)
}
mutating func updatePreviousComponentAddr() -> UnsafeMutableRawPointer? {
let oldValue = previousComponentAddr
previousComponentAddr = destData.baseAddress.unsafelyUnwrapped
return oldValue
}
mutating func visitHeader(genericEnvironment: UnsafeRawPointer?,
rootMetadataRef: MetadataReference,
leafMetadataRef: MetadataReference,
kvcCompatibilityString: UnsafeRawPointer?) {
self.genericEnvironment = genericEnvironment
}
mutating func visitStoredComponent(kind: KeyPathStructOrClass,
mutable: Bool,
offset: KeyPathPatternStoredOffset) {
let previous = updatePreviousComponentAddr()
switch kind {
case .struct:
isPureStruct.append(true)
default:
isPureStruct.append(false)
}
switch kind {
case .class:
// A mutable class property can end the reference prefix.
if mutable {
endOfReferencePrefixComponent = previous
}
fallthrough
case .struct:
// Resolve the offset.
switch offset {
case .inline(let value):
let header = RawKeyPathComponent.Header(stored: kind,
mutable: mutable,
inlineOffset: value)
pushDest(header)
switch kind {
case .struct:
structOffset += value
default:
break
}
case .outOfLine(let offset):
let header = RawKeyPathComponent.Header(storedWithOutOfLineOffset: kind,
mutable: mutable)
pushDest(header)
pushDest(offset)
case .unresolvedFieldOffset(let offsetOfOffset):
// Look up offset in the type metadata. The value in the pattern is
// the offset within the metadata object.
let metadataPtr = unsafeBitCast(base, to: UnsafeRawPointer.self)
let offset: UInt32
switch kind {
case .class:
offset = UInt32(metadataPtr.load(fromByteOffset: Int(offsetOfOffset),
as: UInt.self))
case .struct:
offset = UInt32(metadataPtr.load(fromByteOffset: Int(offsetOfOffset),
as: UInt32.self))
structOffset += offset
}
let header = RawKeyPathComponent.Header(storedWithOutOfLineOffset: kind,
mutable: mutable)
pushDest(header)
pushDest(offset)
case .unresolvedIndirectOffset(let pointerToOffset):
// Look up offset in the indirectly-referenced variable we have a
// pointer.
_internalInvariant(pointerToOffset.pointee <= UInt32.max)
let offset = UInt32(truncatingIfNeeded: pointerToOffset.pointee)
let header = RawKeyPathComponent.Header(storedWithOutOfLineOffset: kind,
mutable: mutable)
pushDest(header)
pushDest(offset)
}
}
}
mutating func visitComputedComponent(mutating: Bool,
idKind: KeyPathComputedIDKind,
idResolution: KeyPathComputedIDResolution,
idValueBase: UnsafeRawPointer,
idValue: Int32,
getter: UnsafeRawPointer,
setter: UnsafeRawPointer?,
arguments: KeyPathPatternComputedArguments?,
externalArgs: UnsafeBufferPointer<Int32>?) {
isPureStruct.append(false)
let previous = updatePreviousComponentAddr()
let settable = setter != nil
// A nonmutating settable property can end the reference prefix.
if settable && !mutating {
endOfReferencePrefixComponent = previous
}
// Resolve the ID.
let resolvedID: UnsafeRawPointer?
switch idKind {
case .storedPropertyIndex, .vtableOffset:
_internalInvariant(idResolution == .resolved)
// Zero-extend the integer value to get the instantiated id.
let value = UInt(UInt32(bitPattern: idValue))
resolvedID = UnsafeRawPointer(bitPattern: value)
case .pointer:
// If the pointer ID is unresolved, then it needs work to get to
// the final value.
switch idResolution {
case .resolved:
resolvedID = _resolveRelativeAddress(idValueBase, idValue)
break
case .resolvedAbsolute:
let value = UInt(UInt32(bitPattern: idValue))
resolvedID = UnsafeRawPointer(bitPattern: value)
break
case .indirectPointer:
// The pointer in the pattern is an indirect pointer to the real
// identifier pointer.
let absoluteID = _resolveRelativeAddress(idValueBase, idValue)
resolvedID = absoluteID
.load(as: UnsafeRawPointer?.self)
case .functionCall:
// The pointer in the pattern is to a function that generates the
// identifier pointer.
typealias Resolver = @convention(c) (UnsafeRawPointer?) -> UnsafeRawPointer?
let absoluteID = _resolveCompactFunctionPointer(idValueBase, idValue)
let resolverSigned = _PtrAuth.sign(
pointer: absoluteID,
key: .processIndependentCode,
discriminator: _PtrAuth.discriminator(for: Resolver.self))
let resolverFn = unsafeBitCast(resolverSigned,
to: Resolver.self)
resolvedID = resolverFn(patternArgs)
}
}
// Bring over the header, getter, and setter.
let header = RawKeyPathComponent.Header(computedWithIDKind: idKind,
mutating: mutating,
settable: settable,
hasArguments: arguments != nil || externalArgs != nil,
instantiatedFromExternalWithArguments:
arguments != nil && externalArgs != nil)
pushDest(header)
pushDest(resolvedID)
pushAddressDiscriminatedFunctionPointer(getter,
discriminator: ComputedAccessorsPtr.getterPtrAuthKey)
if let setter = setter {
pushAddressDiscriminatedFunctionPointer(setter,
discriminator: mutating ? ComputedAccessorsPtr.mutatingSetterPtrAuthKey
: ComputedAccessorsPtr.nonmutatingSetterPtrAuthKey)
}
if let arguments = arguments {
// Instantiate the arguments.
let (baseSize, alignmentMask) = arguments.getLayout(patternArgs)
_internalInvariant(alignmentMask < MemoryLayout<Int>.alignment,
"overaligned computed arguments not implemented yet")
// The real buffer stride will be rounded up to alignment.
var totalSize = (baseSize + alignmentMask) & ~alignmentMask
// If an external property descriptor also has arguments, they'll be
// added to the end with pointer alignment.
if let externalArgs = externalArgs {
totalSize = MemoryLayout<Int>._roundingUpToAlignment(totalSize)
totalSize += MemoryLayout<Int>.size * externalArgs.count
}
pushDest(totalSize)
pushDest(arguments.witnesses)
// A nonnull destructor in the witnesses file indicates the instantiated
// payload is nontrivial.
if let _ = arguments.witnesses.destroy {
isTrivial = false
}
// If the descriptor has arguments, store the size of its specific
// arguments here, so we can drop them when trying to invoke
// the component's witnesses.
if let externalArgs = externalArgs {
pushDest(externalArgs.count * MemoryLayout<Int>.size)
}
// Initialize the local candidate arguments here.
_internalInvariant(Int(bitPattern: destData.baseAddress) & alignmentMask == 0,
"argument destination not aligned")
arguments.initializer(patternArgs,
destData.baseAddress.unsafelyUnwrapped)
destData = UnsafeMutableRawBufferPointer(
start: destData.baseAddress.unsafelyUnwrapped + baseSize,
count: destData.count - baseSize)
}
if let externalArgs = externalArgs {
if arguments == nil {
// If we're instantiating an external property without any local
// arguments, then we only need to instantiate the arguments to the
// property descriptor.
let stride = MemoryLayout<Int>.size * externalArgs.count
pushDest(stride)
pushDest(__swift_keyPathGenericWitnessTable_addr())
}
// Write the descriptor's generic arguments, which should all be relative
// references to metadata accessor functions.
for i in externalArgs.indices {
let base = externalArgs.baseAddress.unsafelyUnwrapped + i
let offset = base.pointee
let metadataRef = _resolveRelativeAddress(UnsafeRawPointer(base), offset)
let result = _resolveKeyPathGenericArgReference(
metadataRef,
genericEnvironment: genericEnvironment,
arguments: patternArgs)
pushDest(result)
}
}
}
mutating func visitOptionalChainComponent() {
isPureStruct.append(false)
let _ = updatePreviousComponentAddr()
let header = RawKeyPathComponent.Header(optionalChain: ())
pushDest(header)
}
mutating func visitOptionalWrapComponent() {
isPureStruct.append(false)
let _ = updatePreviousComponentAddr()
let header = RawKeyPathComponent.Header(optionalWrap: ())
pushDest(header)
}
mutating func visitOptionalForceComponent() {
isPureStruct.append(false)
let _ = updatePreviousComponentAddr()
let header = RawKeyPathComponent.Header(optionalForce: ())
pushDest(header)
}
mutating func visitIntermediateComponentType(metadataRef: MetadataReference) {
// Get the metadata for the intermediate type.
let metadata = _resolveKeyPathMetadataReference(
metadataRef,
genericEnvironment: genericEnvironment,
arguments: patternArgs)
pushDest(metadata)
base = metadata
}
mutating func finish() {
// Should have filled the entire buffer by the time we reach the end of the
// pattern.
_internalInvariant(destData.isEmpty,
"should have filled entire destination buffer")
}
}
#if INTERNAL_CHECKS_ENABLED
// In debug builds of the standard library, check that instantiation produces
// components whose sizes are consistent with the sizing visitor pass.
internal struct ValidatingInstantiateKeyPathBuffer: KeyPathPatternVisitor {
var sizeVisitor: GetKeyPathClassAndInstanceSizeFromPattern
var instantiateVisitor: InstantiateKeyPathBuffer
let origDest: UnsafeMutableRawPointer
var structOffset: UInt32 = 0
var isPureStruct: [Bool] = []
init(sizeVisitor: GetKeyPathClassAndInstanceSizeFromPattern,
instantiateVisitor: InstantiateKeyPathBuffer) {
self.sizeVisitor = sizeVisitor
self.instantiateVisitor = instantiateVisitor
origDest = self.instantiateVisitor.destData.baseAddress.unsafelyUnwrapped
}
mutating func visitHeader(genericEnvironment: UnsafeRawPointer?,
rootMetadataRef: MetadataReference,
leafMetadataRef: MetadataReference,
kvcCompatibilityString: UnsafeRawPointer?) {
sizeVisitor.visitHeader(genericEnvironment: genericEnvironment,
rootMetadataRef: rootMetadataRef,
leafMetadataRef: leafMetadataRef,
kvcCompatibilityString: kvcCompatibilityString)
instantiateVisitor.visitHeader(genericEnvironment: genericEnvironment,
rootMetadataRef: rootMetadataRef,
leafMetadataRef: leafMetadataRef,
kvcCompatibilityString: kvcCompatibilityString)
}
mutating func visitStoredComponent(kind: KeyPathStructOrClass,
mutable: Bool,
offset: KeyPathPatternStoredOffset) {
sizeVisitor.visitStoredComponent(kind: kind, mutable: mutable,
offset: offset)
instantiateVisitor.visitStoredComponent(kind: kind, mutable: mutable,
offset: offset)
checkSizeConsistency()
structOffset = instantiateVisitor.structOffset
isPureStruct.append(contentsOf: instantiateVisitor.isPureStruct)
}
mutating func visitComputedComponent(mutating: Bool,
idKind: KeyPathComputedIDKind,
idResolution: KeyPathComputedIDResolution,
idValueBase: UnsafeRawPointer,
idValue: Int32,
getter: UnsafeRawPointer,
setter: UnsafeRawPointer?,
arguments: KeyPathPatternComputedArguments?,
externalArgs: UnsafeBufferPointer<Int32>?) {
sizeVisitor.visitComputedComponent(mutating: mutating,
idKind: idKind,
idResolution: idResolution,
idValueBase: idValueBase,
idValue: idValue,
getter: getter,
setter: setter,
arguments: arguments,
externalArgs: externalArgs)
instantiateVisitor.visitComputedComponent(mutating: mutating,
idKind: idKind,
idResolution: idResolution,
idValueBase: idValueBase,
idValue: idValue,
getter: getter,
setter: setter,
arguments: arguments,
externalArgs: externalArgs)
// Note: For this function and the ones below, modification of structOffset
// is omitted since these types of KeyPaths won't have a pureStruct
// offset anyway.
isPureStruct.append(contentsOf: instantiateVisitor.isPureStruct)
checkSizeConsistency()
}
mutating func visitOptionalChainComponent() {
sizeVisitor.visitOptionalChainComponent()
instantiateVisitor.visitOptionalChainComponent()
isPureStruct.append(contentsOf: instantiateVisitor.isPureStruct)
checkSizeConsistency()
}
mutating func visitOptionalWrapComponent() {
sizeVisitor.visitOptionalWrapComponent()
instantiateVisitor.visitOptionalWrapComponent()
isPureStruct.append(contentsOf: instantiateVisitor.isPureStruct)
checkSizeConsistency()
}
mutating func visitOptionalForceComponent() {
sizeVisitor.visitOptionalForceComponent()
instantiateVisitor.visitOptionalForceComponent()
isPureStruct.append(contentsOf: instantiateVisitor.isPureStruct)
checkSizeConsistency()
}
mutating func visitIntermediateComponentType(metadataRef: MetadataReference) {
sizeVisitor.visitIntermediateComponentType(metadataRef: metadataRef)
instantiateVisitor.visitIntermediateComponentType(metadataRef: metadataRef)
isPureStruct.append(contentsOf: instantiateVisitor.isPureStruct)
checkSizeConsistency()
}
mutating func finish() {
sizeVisitor.finish()
instantiateVisitor.finish()
isPureStruct.append(contentsOf: instantiateVisitor.isPureStruct)
checkSizeConsistency()
}
func checkSizeConsistency() {
let nextDest = instantiateVisitor.destData.baseAddress.unsafelyUnwrapped
let curSize = nextDest - origDest + MemoryLayout<Int>.size
_internalInvariant(curSize == sizeVisitor.size,
"size and instantiation visitors out of sync")
}
}
#endif // INTERNAL_CHECKS_ENABLED
internal func _instantiateKeyPathBuffer(
_ pattern: UnsafeRawPointer,
_ origDestData: UnsafeMutableRawBufferPointer,
_ rootType: Any.Type,
_ arguments: UnsafeRawPointer
) -> UInt32? {
let destHeaderPtr = origDestData.baseAddress.unsafelyUnwrapped
var destData = UnsafeMutableRawBufferPointer(
start: destHeaderPtr.advanced(by: MemoryLayout<Int>.size),
count: origDestData.count - MemoryLayout<Int>.size)
#if INTERNAL_CHECKS_ENABLED
// If checks are enabled, use a validating walker that ensures that the
// size pre-walk and instantiation walk are in sync.
let sizeWalker = GetKeyPathClassAndInstanceSizeFromPattern(
patternArgs: arguments)
let instantiateWalker = InstantiateKeyPathBuffer(
destData: destData,
patternArgs: arguments,
root: rootType)
var walker = ValidatingInstantiateKeyPathBuffer(sizeVisitor: sizeWalker,
instantiateVisitor: instantiateWalker)
#else
var walker = InstantiateKeyPathBuffer(
destData: destData,
patternArgs: arguments,
root: rootType)
#endif
_walkKeyPathPattern(pattern, walker: &walker)
#if INTERNAL_CHECKS_ENABLED
let isTrivial = walker.instantiateVisitor.isTrivial
let endOfReferencePrefixComponent =
walker.instantiateVisitor.endOfReferencePrefixComponent
#else
let isTrivial = walker.isTrivial
let endOfReferencePrefixComponent = walker.endOfReferencePrefixComponent
#endif
// Write out the header.
let destHeader = KeyPathBuffer.Header(
size: origDestData.count - MemoryLayout<Int>.size,
trivial: isTrivial,
hasReferencePrefix: endOfReferencePrefixComponent != nil)
destHeaderPtr.storeBytes(of: destHeader, as: KeyPathBuffer.Header.self)
// Mark the reference prefix if there is one.
if let endOfReferencePrefixComponent = endOfReferencePrefixComponent {
var componentHeader = endOfReferencePrefixComponent
.load(as: RawKeyPathComponent.Header.self)
componentHeader.endOfReferencePrefix = true
endOfReferencePrefixComponent.storeBytes(of: componentHeader,
as: RawKeyPathComponent.Header.self)
}
var isPureStruct = true
var offset: UInt32? = nil
for value in walker.isPureStruct {
isPureStruct = isPureStruct && value
}
if isPureStruct {
offset = walker.structOffset
}
return offset
}
#if SWIFT_ENABLE_REFLECTION
@_silgen_name("swift_keyPath_dladdr")
fileprivate func keypath_dladdr(_: UnsafeRawPointer) -> UnsafePointer<CChar>?
@_silgen_name("swift_keyPathSourceString")
fileprivate func demangle(
name: UnsafePointer<CChar>
) -> UnsafeMutablePointer<CChar>?
fileprivate func dynamicLibraryAddress<Base, Leaf>(
of pointer: ComputedAccessorsPtr,
_: Base.Type,
_ leaf: Leaf.Type
) -> String {
let getter: ComputedAccessorsPtr.Getter<Base, Leaf> = pointer.getter()
let pointer = unsafeBitCast(getter, to: UnsafeRawPointer.self)
if let cString = keypath_dladdr(UnsafeRawPointer(pointer)) {
if let demangled = demangle(name: cString)
.map({ pointer in
defer {
pointer.deallocate()
}
return String(cString: pointer)
}) {
return demangled
}
}
return "<computed \(pointer) (\(leaf))>"
}
#endif
@available(SwiftStdlib 5.8, *)
extension AnyKeyPath: CustomDebugStringConvertible {
#if SWIFT_ENABLE_REFLECTION
@available(SwiftStdlib 5.8, *)
public var debugDescription: String {
var description = "\\\(String(describing: Self.rootType))"
return withBuffer {
var buffer = $0
if buffer.data.isEmpty {
_internalInvariantFailure("key path has no components")
}
var valueType: Any.Type = Self.rootType
while true {
let (rawComponent, optNextType) = buffer.next()
let hasEnded = optNextType == nil
let nextType = optNextType ?? Self.valueType
switch rawComponent.value {
case .optionalForce, .optionalWrap, .optionalChain:
break
default:
description.append(".")
}
switch rawComponent.value {
case .class(let offset),
.struct(let offset):
let count = _getRecursiveChildCount(valueType)
let index = (0..<count)
.first(where: { i in
_getChildOffset(
valueType,
index: i
) == offset
})
if let index = index {
var field = _FieldReflectionMetadata()
_ = _getChildMetadata(
valueType,
index: index,
fieldMetadata: &field
)
defer {
field.freeFunc?(field.name)
}
description.append(String(cString: field.name))
} else {
description.append("<offset \(offset) (\(nextType))>")
}
case .get(_, let accessors, _),
.nonmutatingGetSet(_, let accessors, _),
.mutatingGetSet(_, let accessors, _):
func project<Base>(base: Base.Type) -> String {
func project2<Leaf>(leaf: Leaf.Type) -> String {
dynamicLibraryAddress(
of: accessors,
base,
leaf
)
}
return _openExistential(nextType, do: project2)
}
description.append(
_openExistential(valueType, do: project)
)
case .optionalChain, .optionalWrap:
description.append("?")
case .optionalForce:
description.append("!")
}
if hasEnded {
break
}
valueType = nextType
}
return description
}
}
#else
@available(SwiftStdlib 5.8, *)
public var debugDescription: String {
"(value cannot be printed without reflection)"
}
#endif
}
|
apache-2.0
|
1f2de6bea9217f748a94fdd50da6bb81
| 36.135128 | 94 | 0.658816 | 4.963808 | false | false | false | false |
zero2launch/z2l-ios-social-network
|
InstagramClone/UserApi.swift
|
1
|
3181
|
//
// UserApi.swift
// InstagramClone
//
// Created by The Zero2Launch Team on 1/8/17.
// Copyright © 2017 The Zero2Launch Team. All rights reserved.
//
import Foundation
import FirebaseDatabase
import FirebaseAuth
class UserApi {
var REF_USERS = FIRDatabase.database().reference().child("users")
func observeUserByUsername(username: String, completion: @escaping (User) -> Void) {
REF_USERS.queryOrdered(byChild: "username_lowercase").queryEqual(toValue: username).observeSingleEvent(of: .childAdded, with: {
snapshot in
print(snapshot)
if let dict = snapshot.value as? [String: Any] {
let user = User.transformUser(dict: dict, key: snapshot.key)
completion(user)
}
})
}
// DataService.dataService.USER_REF.queryOrdered(byChild: "username").queryEqual(toValue: "\(mention.lowercased())").observe(.childAdded, with: { snapshot in
func observeUser(withId uid: String, completion: @escaping (User) -> Void) {
REF_USERS.child(uid).observeSingleEvent(of: .value, with: {
snapshot in
if let dict = snapshot.value as? [String: Any] {
let user = User.transformUser(dict: dict, key: snapshot.key)
completion(user)
}
})
}
func observeCurrentUser(completion: @escaping (User) -> Void) {
guard let currentUser = FIRAuth.auth()?.currentUser else {
return
}
REF_USERS.child(currentUser.uid).observeSingleEvent(of: .value, with: {
snapshot in
if let dict = snapshot.value as? [String: Any] {
let user = User.transformUser(dict: dict, key: snapshot.key)
completion(user)
}
})
}
func observeUsers(completion: @escaping (User) -> Void) {
REF_USERS.observe(.childAdded, with: {
snapshot in
if let dict = snapshot.value as? [String: Any] {
let user = User.transformUser(dict: dict, key: snapshot.key)
completion(user)
}
})
}
func queryUsers(withText text: String, completion: @escaping (User) -> Void) {
REF_USERS.queryOrdered(byChild: "username_lowercase").queryStarting(atValue: text).queryEnding(atValue: text+"\u{f8ff}").queryLimited(toFirst: 10).observeSingleEvent(of: .value, with: {
snapshot in
snapshot.children.forEach({ (s) in
let child = s as! FIRDataSnapshot
if let dict = child.value as? [String: Any] {
let user = User.transformUser(dict: dict, key: child.key)
completion(user)
}
})
})
}
var CURRENT_USER: FIRUser? {
if let currentUser = FIRAuth.auth()?.currentUser {
return currentUser
}
return nil
}
var REF_CURRENT_USER: FIRDatabaseReference? {
guard let currentUser = FIRAuth.auth()?.currentUser else {
return nil
}
return REF_USERS.child(currentUser.uid)
}
}
|
mit
|
d6e86a0a0dfa229e3ed2968390db8d89
| 35.136364 | 193 | 0.574214 | 4.416667 | false | false | false | false |
steelwheels/Coconut
|
CoconutData/Source/File/CNResourceInstaller.swift
|
1
|
2301
|
/*
* @file CNResourceInstaller.swift
* @brief Define CNResourceInstaller class
* @par Copyright
* Copyright (C) 2021 Steel Wheels Project
*/
import Foundation
public class CNResourceInstaller
{
private var mConsole: CNConsole
public init(console cons: CNConsole){
mConsole = cons
}
public func install(destinationDirectory dstdir: URL, sourceDirectoryNames srcdirs: Array<String>) -> Bool {
var result: Bool = true
let fmgr = FileManager.default
for srcdir in srcdirs {
let dstsubdir = dstdir.appendingPathComponent(srcdir)
if fmgr.fileExists(atURL: dstsubdir) {
mConsole.print(string: "Remove directory: \(dstsubdir.path)\n")
if let err = remove(directory: dstsubdir) {
mConsole.error(string: "[Error] \(err.toString())")
result = false
continue
}
}
if let srcsubdir = Bundle.main.url(forResource: srcdir, withExtension: nil){
mConsole.print(string: "Copy directory: \(srcsubdir) --> \(dstsubdir)\n")
if let err = copy(destinationDirectory: dstsubdir, sourceDirectory: srcsubdir){
mConsole.error(string: "[Error] \(err.toString())")
result = false
}
} else {
mConsole.error(string: "[Error] No source directory: \(srcdir)")
result = false
}
}
return result
}
private func makeTargetDir(directory targdir: URL) -> NSError? {
do {
let fmgr = FileManager.default
switch fmgr.checkFileType(pathString: targdir.path) {
case .Directory:
break // Nothing have to do
case .File:
return NSError.fileError(message: "The file is already exist: \(targdir.path)")
case .NotExist:
/* Make the directory */
mConsole.print(string: "Make directory: \(targdir.path)\n")
try fmgr.createDirectory(at: targdir,
withIntermediateDirectories: false,
attributes: nil)
}
return nil
} catch {
return error as NSError
}
}
private func remove(directory dir: URL) -> NSError? {
let fmgr = FileManager.default
do {
try fmgr.removeItem(at: dir)
return nil
} catch {
return error as NSError
}
}
private func copy(destinationDirectory dstdir: URL, sourceDirectory srcdir: URL) -> NSError? {
let fmgr = FileManager.default
do {
try fmgr.copyItem(at: srcdir, to: dstdir)
return nil
} catch {
return error as NSError
}
}
}
|
lgpl-2.1
|
33215adb790723cdee5110db0672783b
| 25.448276 | 109 | 0.682312 | 3.42921 | false | false | false | false |
edx/edx-app-ios
|
Source/UIDeviceExtension.swift
|
1
|
8233
|
//
// https://github.com/schickling/Device.swift
// UIDeviceExtension.swift
// Device
//
// Created by Johannes Schickling on 7/20/15.
//
//
// MARK: Imports
import Foundation
import UIKit
/// Enum representing the different types of iOS devices available
public enum DeviceType: String, CaseIterable {
case iPhone2G
case iPhone3G
case iPhone3GS
case iPhone4
case iPhone4S
case iPhone5
case iPhone5C
case iPhone5S
case iPhone6
case iPhone6Plus
case iPhone6S
case iPhone6SPlus
case iPhoneSE
case iPhone7
case iPhone7Plus
case iPhone8
case iPhone8Plus
case iPhoneX
case iPhoneXS
case iPhoneXSMax
case iPhoneXR
case iPhone11
case iPhone11Pro
case iPhone11ProMax
case iPhoneSEGen2
case iPhone12Mini
case iPhone12
case iPhone12Pro
case iPhone12ProMax
case iPodTouch1G
case iPodTouch2G
case iPodTouch3G
case iPodTouch4G
case iPodTouch5G
case iPodTouch6G
case iPodTouch7G
case iPad
case iPad2
case iPad3
case iPad4
case iPad5
case iPad6
case iPadMini
case iPadMiniRetina
case iPadMini3
case iPadMini4
case iPadAir
case iPadAir2
case iPadPro9Inch
case iPadPro10p5Inch
case iPadPro11Inch
case iPadPro12Inch
case simulator
case notAvailable
public static var current: DeviceType {
return DeviceType.init(identifier: deviceIdentifier)
}
static var deviceIdentifier: String {
var systemInfo = utsname()
uname(&systemInfo)
let machine = systemInfo.machine
let mirror = Mirror(reflecting: machine)
var identifier = ""
for child in mirror.children {
if let value = child.value as? Int8, value != 0 {
identifier.append(String(UnicodeScalar(UInt8(value))))
}
}
return identifier
}
public var displayName: String {
switch self {
case .iPhone2G: return "iPhone 2G"
case .iPhone3G: return "iPhone 3G"
case .iPhone3GS: return "iPhone 3GS"
case .iPhone4: return "iPhone 4"
case .iPhone4S: return "iPhone 4S"
case .iPhone5: return "iPhone 5"
case .iPhone5C: return "iPhone 5C"
case .iPhone5S: return "iPhone 5S"
case .iPhone6Plus: return "iPhone 6 Plus"
case .iPhone6: return "iPhone 6"
case .iPhone6S: return "iPhone 6S"
case .iPhone6SPlus: return "iPhone 6S Plus"
case .iPhoneSE: return "iPhone SE"
case .iPhone7: return "iPhone 7"
case .iPhone7Plus: return "iPhone 7 Plus"
case .iPhone8: return "iPhone 8"
case .iPhone8Plus: return "iPhone 8 Plus"
case .iPhoneX: return "iPhone X"
case .iPhoneXS: return "iPhone XS"
case .iPhoneXSMax: return "iPhone XS Max"
case .iPhoneXR: return "iPhone XR"
case .iPhone11: return "iPhone 11"
case .iPhone11Pro: return "iPhone 11 Pro"
case .iPhone11ProMax: return "iPhone 11 Pro Max"
case .iPhoneSEGen2: return "iPhone SE (2nd Gen)"
case .iPhone12Mini: return "iPhone 12 Mini"
case .iPhone12: return "iPhone 12"
case .iPhone12Pro: return "iPhone 12 Pro"
case .iPhone12ProMax: return "iPhone 12 Pro Max"
case .iPodTouch1G: return "iPod Touch 1G"
case .iPodTouch2G: return "iPod Touch 2G"
case .iPodTouch3G: return "iPod Touch 3G"
case .iPodTouch4G: return "iPod Touch 4G"
case .iPodTouch5G: return "iPod Touch 5G"
case .iPodTouch6G: return "iPod Touch 6G"
case .iPodTouch7G: return "iPod Touch 7G"
case .iPad: return "iPad"
case .iPad2: return "iPad 2"
case .iPad3: return "iPad 3"
case .iPad4: return "iPad 4"
case .iPad5: return "iPad 5"
case .iPad6: return "iPad 6"
case .iPadMini: return "iPad Mini"
case .iPadMiniRetina: return "iPad Mini Retina"
case .iPadMini3: return "iPad Mini 3"
case .iPadMini4: return "iPad Mini 4"
case .iPadAir: return "iPad Air"
case .iPadAir2: return "iPad Air 2"
case .iPadPro9Inch: return "iPad Pro 9 Inch"
case .iPadPro10p5Inch: return "iPad Pro 10.5 Inch"
case .iPadPro11Inch: return "iPad Pro 11 Inch"
case .iPadPro12Inch: return "iPad Pro 12 Inch"
case .simulator: return "Simulator"
case .notAvailable: return "Not Available"
}
}
private var identifiers: [String] {
switch self {
case .notAvailable: return []
case .simulator: return ["i386", "x86_64"]
case .iPhone2G: return ["iPhone1,1"]
case .iPhone3G: return ["iPhone1,2"]
case .iPhone3GS: return ["iPhone2,1"]
case .iPhone4: return ["iPhone3,1", "iPhone3,2", "iPhone3,3"]
case .iPhone4S: return ["iPhone4,1"]
case .iPhone5: return ["iPhone5,1", "iPhone5,2"]
case .iPhone5C: return ["iPhone5,3", "iPhone5,4"]
case .iPhone5S: return ["iPhone6,1", "iPhone6,2"]
case .iPhone6: return ["iPhone7,2"]
case .iPhone6Plus: return ["iPhone7,1"]
case .iPhone6S: return ["iPhone8,1"]
case .iPhone6SPlus: return ["iPhone8,2"]
case .iPhoneSE: return ["iPhone8,4"]
case .iPhone7: return ["iPhone9,1", "iPhone9,3"]
case .iPhone7Plus: return ["iPhone9,2", "iPhone9,4"]
case .iPhone8: return ["iPhone10,1", "iPhone10,4"]
case .iPhone8Plus: return ["iPhone10,2", "iPhone10,5"]
case .iPhoneX: return ["iPhone10,3", "iPhone10,6"]
case .iPhoneXS: return ["iPhone11,2"]
case .iPhoneXSMax: return ["iPhone11,4", "iPhone11,6"]
case .iPhoneXR: return ["iPhone11,8"]
case .iPhone11: return ["iPhone12,1"]
case .iPhone11Pro: return ["iPhone12,3"]
case .iPhone11ProMax: return ["iPhone12,5"]
case .iPhoneSEGen2: return ["iPhone12,8"]
case .iPhone12Mini: return ["iPhone13,1"]
case .iPhone12: return ["iPhone13,2"]
case .iPhone12Pro: return ["iPhone13,3"]
case .iPhone12ProMax: return ["iPhone13,4"]
case .iPodTouch1G: return ["iPod1,1"]
case .iPodTouch2G: return ["iPod2,1"]
case .iPodTouch3G: return ["iPod3,1"]
case .iPodTouch4G: return ["iPod4,1"]
case .iPodTouch5G: return ["iPod5,1"]
case .iPodTouch6G: return ["iPod7,1"]
case .iPodTouch7G: return ["iPod9,1"]
case .iPad: return ["iPad1,1", "iPad1,2"]
case .iPad2: return ["iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4"]
case .iPad3: return ["iPad3,1", "iPad3,2", "iPad3,3"]
case .iPad4: return ["iPad3,4", "iPad3,5", "iPad3,6"]
case .iPad5: return ["iPad6,11", "iPad6,12"]
case .iPad6: return ["iPad7,5", "iPad7,6"]
case .iPadMini: return ["iPad2,5", "iPad2,6", "iPad2,7"]
case .iPadMiniRetina: return ["iPad4,4", "iPad4,5", "iPad4,6"]
case .iPadMini3: return ["iPad4,7", "iPad4,8", "iPad4,9"]
case .iPadMini4: return ["iPad5,1", "iPad5,2"]
case .iPadAir: return ["iPad4,1", "iPad4,2", "iPad4,3"]
case .iPadAir2: return ["iPad5,3", "iPad5,4"]
case .iPadPro9Inch: return ["iPad6,3", "iPad6,4"]
case .iPadPro10p5Inch: return ["iPad7,3", "iPad7,4"]
case .iPadPro11Inch: return ["iPad8,1", "iPad8,2", "iPad8,3", "iPad8,4"]
case .iPadPro12Inch: return ["iPad6,7", "iPad6,8", "iPad7,1", "iPad7,2", "iPad8,5", "iPad8,6", "iPad8,7", "iPad8,8"]
}
}
private init(identifier: String) {
for device in DeviceType.allCases {
for deviceId in device.identifiers {
guard identifier == deviceId else { continue }
self = device
return
}
}
self = .notAvailable
}
}
public extension UIDevice {
static var deviceModel: String {
return DeviceType.current == .notAvailable ? DeviceType.deviceIdentifier : DeviceType.current.displayName
}
}
|
apache-2.0
|
b2a4d4713cfc3fc1a62617e026da460c
| 32.064257 | 124 | 0.597109 | 3.673806 | false | false | false | false |
ishaq/ContactsImporter
|
ContactsImporter/Libs/GooglePlusContactsImporter.swift
|
1
|
3595
|
//
// GooglePlusContactsImporter.swift
// ContactsImporter
//
// Created by Muhammad Ishaq on 10/10/2014.
// Copyright (c) 2014 Kahaf. All rights reserved.
//
import UIKit
// imports friends from visible circles
// docs here: https://developers.google.com/+/mobile/ios/
class GooglePlusContactsImporter : NSObject, GPPSignInDelegate {
private var contacts = Array<Contact>()
private var callback: ((contacts: Array<Contact>, error: NSError!) -> Void)! = nil
// FIXME: paste your google client id
// follow the instructions here: https://developers.google.com/+/mobile/ios/getting-started
private let GoogleClientId = "623330778218-lj9ql2mn31ajffaf28sp6egbopu9ln6r.apps.googleusercontent.com";
func importContacts(callback: ((contacts: Array<Contact>, error: NSError!) -> Void)) {
self.callback = callback
self.signInGooglePlus()
}
func signInGooglePlus() {
let signIn = GPPSignIn.sharedInstance()
signIn.shouldFetchGooglePlusUser = true
signIn.shouldFetchGoogleUserEmail = true
signIn.clientID = self.GoogleClientId
signIn.scopes = [kGTLAuthScopePlusLogin]
signIn.delegate = self
let result = signIn.trySilentAuthentication()
if result == false {
signIn.authenticate()
}
}
func finishedWithAuth(auth: GTMOAuth2Authentication!, error: NSError!) {
println("Received error \(error) and auth object \(auth)")
println("User's Email \(auth.userEmail)")
kickOffContactsRequest()
}
func kickOffContactsRequest() {
let plusService = GTLServicePlus()
plusService.retryEnabled = true
plusService.authorizer = GPPSignIn.sharedInstance().authentication
self.contacts = Array<Contact>()
let query = GTLQueryPlus.queryForPeopleListWithUserId("me", collection: kGTLPlusCollectionVisible) as GTLQueryPlus
plusService.executeQuery(query, completionHandler: self.googlePlusContactsCallback);
}
func googlePlusContactsCallback(ticket: GTLServiceTicket!, returnObject: AnyObject?, error: NSError!) {
if (error != nil) {
// show error alert
self.callback(contacts: self.contacts, error:error)
return
}
let peopleFeed = returnObject as GTLPlusPeopleFeed
let peopleList = peopleFeed.items()
println("peopleFeed.totalItems: \(peopleFeed.totalItems) peopleFeed.items().count: \(peopleFeed.items().count) peopleFeed.nextPageToken: \(peopleFeed.nextPageToken)")
for personObject in peopleList {
let person = personObject as GTLPlusPerson
let c = Contact(name: person.displayName)
c.googlePlusId = person.identifier
c.imageURL = person.image.url
self.contacts.append(c)
}
if(peopleFeed.nextPageToken != nil) {
let plusService = GTLServicePlus()
plusService.retryEnabled = true
plusService.authorizer = GPPSignIn.sharedInstance().authentication
let query = GTLQueryPlus.queryForPeopleListWithUserId("me", collection: kGTLPlusCollectionVisible) as GTLQueryPlus
query.pageToken = peopleFeed.nextPageToken
plusService.executeQuery(query, completionHandler: googlePlusContactsCallback)
}
else {
self.callback(contacts:self.contacts, error:nil)
}
}
}
|
cc0-1.0
|
95202660dbd87580b3e1f2bb4f7ab3e6
| 35.683673 | 174 | 0.645897 | 4.699346 | false | false | false | false |
pkl728/ZombieInjection
|
Pods/Bond/Sources/Bond/Collections/Observable2DArray.swift
|
1
|
23723
|
//
// The MIT License (MIT)
//
// Copyright (c) 2016 Srdan Rasic (@srdanrasic)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import ReactiveKit
import Differ
public enum Observable2DArrayChange {
case reset
case insertItems([IndexPath])
case deleteItems([IndexPath])
case updateItems([IndexPath])
case moveItem(IndexPath, IndexPath)
case insertSections(IndexSet)
case deleteSections(IndexSet)
case updateSections(IndexSet)
case moveSection(Int, Int)
case beginBatchEditing
case endBatchEditing
}
public protocol Observable2DArrayEventProtocol {
associatedtype SectionMetadata
associatedtype Item
var change: Observable2DArrayChange { get }
var source: Observable2DArray<SectionMetadata, Item> { get }
}
public struct Observable2DArrayEvent<SectionMetadata, Item>: Observable2DArrayEventProtocol {
public let change: Observable2DArrayChange
public let source: Observable2DArray<SectionMetadata, Item>
public init(change: Observable2DArrayChange, source: Observable2DArray<SectionMetadata, Item>) {
self.change = change
self.source = source
}
public init(change: Observable2DArrayChange, source: [Observable2DArraySection<SectionMetadata, Item>]) {
self.change = change
self.source = Observable2DArray(source)
}
}
public struct Observable2DArrayPatchEvent<SectionMetadata, Item>: Observable2DArrayEventProtocol {
public let change: Observable2DArrayChange
public let source: Observable2DArray<SectionMetadata, Item>
public init(change: Observable2DArrayChange, source: Observable2DArray<SectionMetadata, Item>) {
self.change = change
self.source = source
}
public init(change: Observable2DArrayChange, source: [Observable2DArraySection<SectionMetadata, Item>]) {
self.change = change
self.source = Observable2DArray(source)
}
}
/// Represents a section in 2D array.
/// Section contains its metadata (e.g. header string) and items.
public struct Observable2DArraySection<Metadata, Item>: Collection {
public var metadata: Metadata
public var items: [Item]
public init(metadata: Metadata, items: [Item] = []) {
self.metadata = metadata
self.items = items
}
public var startIndex: Int {
return items.startIndex
}
public var endIndex: Int {
return items.endIndex
}
public var count: Int {
return items.count
}
public var isEmpty: Bool {
return items.isEmpty
}
public func index(after i: Int) -> Int {
return items.index(after: i)
}
public subscript(index: Int) -> Item {
get {
return items[index]
}
}
}
public class Observable2DArray<SectionMetadata, Item>: SignalProtocol {
public fileprivate(set) var sections: [Observable2DArraySection<SectionMetadata, Item>]
fileprivate let subject = PublishSubject<Observable2DArrayEvent<SectionMetadata, Item>, NoError>()
fileprivate let lock = NSRecursiveLock(name: "com.reactivekit.bond.observable2darray")
public init(_ sections: [Observable2DArraySection<SectionMetadata, Item>] = []) {
self.sections = sections
}
public var numberOfSections: Int {
return sections.count
}
public func numberOfItems(inSection section: Int) -> Int {
guard section < numberOfSections else { return 0 }
return sections[section].items.count
}
public var startIndex: IndexPath {
guard sections.count > 0 else { return IndexPath(item: 0, section: 0) }
var section = 0
while section < sections.count && sections[section].count == 0 {
section += 1
}
return IndexPath(item: 0, section: section)
}
public var endIndex: IndexPath {
return IndexPath(item: 0, section: numberOfSections)
}
public func index(after i: IndexPath) -> IndexPath {
if i.section < sections.count {
let section = sections[i.section]
if i.item + 1 < section.items.count {
return IndexPath(item: i.item + 1, section: i.section)
} else {
var section = i.section + 1
while section < sections.count {
if sections[section].items.count > 0 {
return IndexPath(item: 0, section: section)
} else {
section += 1
}
}
return endIndex
}
} else {
return endIndex
}
}
public var isEmpty: Bool {
return sections.reduce(true) { $0 && $1.items.isEmpty }
}
public var count: Int {
return sections.reduce(0) { $0 + $1.items.count }
}
public subscript(index: IndexPath) -> Item {
get {
return sections[index.section].items[index.item]
}
}
public subscript(index: Int) -> Observable2DArraySection<SectionMetadata, Item> {
get {
return sections[index]
}
}
public func observe(with observer: @escaping (Event<Observable2DArrayEvent<SectionMetadata, Item>, NoError>) -> Void) -> Disposable {
observer(.next(Observable2DArrayEvent(change: .reset, source: self)))
return subject.observe(with: observer)
}
}
extension Observable2DArray: Deallocatable {
public var deallocated: Signal<Void, NoError> {
return subject.disposeBag.deallocated
}
}
public class MutableObservable2DArray<SectionMetadata, Item>: Observable2DArray<SectionMetadata, Item> {
/// Append new section at the end of the 2D array.
public func appendSection(_ section: Observable2DArraySection<SectionMetadata, Item>) {
lock.lock(); defer { lock.unlock() }
sections.append(section)
let sectionIndex = sections.count - 1
let indices = 0..<section.items.count
let indexPaths = indices.map { IndexPath(item: $0, section: sectionIndex) }
if indices.count > 0 {
subject.next(Observable2DArrayEvent(change: .beginBatchEditing, source: self))
subject.next(Observable2DArrayEvent(change: .insertSections([sectionIndex]), source: self))
subject.next(Observable2DArrayEvent(change: .insertItems(indexPaths), source: self))
subject.next(Observable2DArrayEvent(change: .endBatchEditing, source: self))
} else {
subject.next(Observable2DArrayEvent(change: .insertSections([sectionIndex]), source: self))
}
}
/// Append `item` to the section `section` of the array.
public func appendItem(_ item: Item, toSection section: Int) {
lock.lock(); defer { lock.unlock() }
sections[section].items.append(item)
let indexPath = IndexPath(item: sections[section].items.count - 1, section: section)
subject.next(Observable2DArrayEvent(change: .insertItems([indexPath]), source: self))
}
/// Insert section at `index` with `items`.
public func insert(section: Observable2DArraySection<SectionMetadata, Item>, at index: Int) {
lock.lock(); defer { lock.unlock() }
sections.insert(section, at: index)
let indices = 0..<section.items.count
let indexPaths = indices.map { IndexPath(item: $0, section: index) }
if indices.count > 0 {
subject.next(Observable2DArrayEvent(change: .beginBatchEditing, source: self))
subject.next(Observable2DArrayEvent(change: .insertSections([index]), source: self))
subject.next(Observable2DArrayEvent(change: .insertItems(indexPaths), source: self))
subject.next(Observable2DArrayEvent(change: .endBatchEditing, source: self))
} else {
subject.next(Observable2DArrayEvent(change: .insertSections([index]), source: self))
}
}
/// Insert `item` at `indexPath`.
public func insert(item: Item, at indexPath: IndexPath) {
lock.lock(); defer { lock.unlock() }
sections[indexPath.section].items.insert(item, at: indexPath.item)
subject.next(Observable2DArrayEvent(change: .insertItems([indexPath]), source: self))
}
/// Insert `items` at index path `indexPath`.
public func insert(contentsOf items: [Item], at indexPath: IndexPath) {
lock.lock(); defer { lock.unlock() }
sections[indexPath.section].items.insert(contentsOf: items, at: indexPath.item)
let indices = indexPath.item..<indexPath.item+items.count
let indexPaths = indices.map { IndexPath(item: $0, section: indexPath.section) }
subject.next(Observable2DArrayEvent(change: .insertItems(indexPaths), source: self))
}
/// Move the section at index `fromIndex` to index `toIndex`.
public func moveSection(from fromIndex: Int, to toIndex: Int) {
lock.lock(); defer { lock.unlock() }
let section = sections.remove(at: fromIndex)
sections.insert(section, at: toIndex)
subject.next(Observable2DArrayEvent(change: .moveSection(fromIndex, toIndex), source: self))
}
/// Move the item at `fromIndexPath` to `toIndexPath`.
public func moveItem(from fromIndexPath: IndexPath, to toIndexPath: IndexPath) {
lock.lock(); defer { lock.unlock() }
let item = sections[fromIndexPath.section].items.remove(at: fromIndexPath.item)
sections[toIndexPath.section].items.insert(item, at: toIndexPath.item)
subject.next(Observable2DArrayEvent(change: .moveItem(fromIndexPath, toIndexPath), source: self))
}
/// Remove and return the section at `index`.
@discardableResult
public func removeSection(at index: Int) -> Observable2DArraySection<SectionMetadata, Item> {
lock.lock(); defer { lock.unlock() }
let element = sections.remove(at: index)
subject.next(Observable2DArrayEvent(change: .deleteSections([index]), source: self))
return element
}
/// Remove and return the item at `indexPath`.
@discardableResult
public func removeItem(at indexPath: IndexPath) -> Item {
lock.lock(); defer { lock.unlock() }
let element = sections[indexPath.section].items.remove(at: indexPath.item)
subject.next(Observable2DArrayEvent(change: .deleteItems([indexPath]), source: self))
return element
}
/// Remove all items from the array. Keep empty sections.
public func removeAllItems() {
lock.lock(); defer { lock.unlock() }
let indexPaths = sections.enumerated().reduce([]) { (indexPaths, section) -> [IndexPath] in
indexPaths + section.element.items.indices.map { IndexPath(item: $0, section: section.offset) }
}
for index in sections.indices {
sections[index].items.removeAll()
}
subject.next(Observable2DArrayEvent(change: .deleteItems(indexPaths), source: self))
}
/// Remove all items and sections from the array.
public func removeAllItemsAndSections() {
lock.lock(); defer { lock.unlock() }
let indices = sections.indices
sections.removeAll()
subject.next(Observable2DArrayEvent(change: .deleteSections(IndexSet(integersIn: indices)), source: self))
}
public override subscript(index: IndexPath) -> Item {
get {
return sections[index.section].items[index.item]
}
set {
lock.lock(); defer { lock.unlock() }
sections[index.section].items[index.item] = newValue
subject.next(Observable2DArrayEvent(change: .updateItems([index]), source: self))
}
}
/// Change the underlying value withouth notifying the observers.
public func silentUpdate(_ update: (inout [Observable2DArraySection<SectionMetadata, Item>]) -> Void) {
lock.lock(); defer { lock.unlock() }
update(§ions)
}
}
extension MutableObservable2DArray: BindableProtocol {
public func bind(signal: Signal<Observable2DArrayEvent<SectionMetadata, Item>, NoError>) -> Disposable {
return signal
.take(until: deallocated)
.observeNext { [weak self] event in
guard let s = self else { return }
s.sections = event.source.sections
s.subject.next(Observable2DArrayEvent(change: event.change, source: s))
}
}
}
// MARK: DataSourceProtocol conformation
extension Observable2DArrayChange {
public var asDataSourceEventKind: DataSourceEventKind {
switch self {
case .reset:
return .reload
case .insertItems(let indexPaths):
return .insertItems(indexPaths)
case .deleteItems(let indexPaths):
return .deleteItems(indexPaths)
case .updateItems(let indexPaths):
return .reloadItems(indexPaths)
case .moveItem(let from, let to):
return .moveItem(from, to)
case .insertSections(let indices):
return .insertSections(indices)
case .deleteSections(let indices):
return .deleteSections(indices)
case .updateSections(let indices):
return .reloadSections(indices)
case .moveSection(let from, let to):
return .moveSection(from, to)
case .beginBatchEditing:
return .beginUpdates
case .endBatchEditing:
return .endUpdates
}
}
}
extension Observable2DArrayEvent: DataSourceEventProtocol {
public typealias BatchKind = BatchKindDiff
public var kind: DataSourceEventKind {
return change.asDataSourceEventKind
}
public var dataSource: Observable2DArray<SectionMetadata, Item> {
return source
}
}
extension Observable2DArrayPatchEvent: DataSourceEventProtocol {
public typealias BatchKind = BatchKindPatch
public var kind: DataSourceEventKind {
return change.asDataSourceEventKind
}
public var dataSource: Observable2DArray<SectionMetadata, Item> {
return source
}
}
extension Observable2DArray: QueryableDataSourceProtocol {
public func item(at index: IndexPath) -> Item {
return self[index]
}
}
extension MutableObservable2DArray {
/// Replace section at given index with given section and notify observers to reload section completely
public func replaceSection(at index: Int, with section: Observable2DArraySection<SectionMetadata, Item>) {
lock.lock(); defer { lock.unlock() }
sections[index] = section
subject.next(Observable2DArrayEvent(change: .updateSections([index]), source: self))
}
/// Replace the entier 2d array with a new one forcing a reload
public func replace(with array: Observable2DArray<SectionMetadata, Item>) {
lock.lock(); defer { lock.unlock() }
sections = array.sections
subject.next(Observable2DArrayEvent(change: .reset, source: self))
}
}
extension MutableObservable2DArray where Item: Equatable {
/// Replace section at given index with given section performing diff if performDiff is true
/// on all items in section and notifying observers about delets and inserts
public func replaceSection(at index: Int, with section: Observable2DArraySection<SectionMetadata, Item>, performDiff: Bool) {
if performDiff {
lock.lock()
let diff = sections[index].items.extendedDiff(section.items)
let patch = diff.patch(from: sections[index].items, to: section.items)
subject.next(Observable2DArrayEvent(change: .beginBatchEditing, source: self))
sections[index].metadata = section.metadata
sections[index].items = section.items
for step in patch {
switch step {
case .insertion(let patchIndex, _):
let indexPath = IndexPath(item: patchIndex, section: index)
subject.next(Observable2DArrayEvent(change: .insertItems([indexPath]), source: self))
case .deletion(let patchIndex):
let indexPath = IndexPath(item: patchIndex, section: index)
subject.next(Observable2DArrayEvent(change: .deleteItems([indexPath]), source: self))
case .move(let from, let to):
let fromIndexPath = IndexPath(item: from, section: index)
let toIndexPath = IndexPath(item: to, section: index)
subject.next(Observable2DArrayEvent(change: .moveItem(fromIndexPath, toIndexPath), source: self))
}
}
subject.next(Observable2DArrayEvent(change: .endBatchEditing, source: self))
lock.unlock()
} else {
replaceSection(at: index, with: section)
}
}
/// Replace all items in section at given index with given items performing diff between
/// existing and new items if performDiff is true, otherwise reload section with new items
public func replaceSection(at index: Int, with items: [Item], performDiff: Bool) {
replaceSection(at: index, with: Observable2DArraySection<SectionMetadata, Item>(metadata: sections[index].metadata, items: items), performDiff: performDiff)
}
}
extension MutableObservable2DArray where Item: Equatable, SectionMetadata: Equatable {
/// Perform batched updates on the array.
public func batchUpdate(_ update: (MutableObservable2DArray<SectionMetadata, Item>) -> Void) {
let copy = MutableObservable2DArray(sections)
update(copy)
replace(with: copy, performDiff: true)
}
/// Replace the entire 2DArray performing nested diff (if preformDiff is true) on all
/// sections and section's items resulting in a series of events (deleteSection,
/// deleteItems, insertSections, insertItems, moveSection, moveItem) that migrate the old
/// 2DArray to the new 2DArray
/// Note that both Item and SectionMetadata should be Equatable
public func replace(with array: Observable2DArray<SectionMetadata, Item>, performDiff: Bool) {
if performDiff {
lock.lock()
// perform nested diff
let diff = sections.nestedExtendedDiff(to: array.sections, isEqualSection: {(oldSection, newSection) in
return oldSection.metadata == newSection.metadata
})
let update = NestedBatchUpdate(diff: diff)
subject.next(Observable2DArrayEvent(change: .beginBatchEditing, source: self))
sections = array.sections
// item deletion
subject.next(Observable2DArrayEvent(change: .deleteItems(update.itemDeletions), source: self))
// item insertions
subject.next(Observable2DArrayEvent(change: .insertItems(update.itemInsertions), source: self))
// item moves
update.itemMoves.forEach {
subject.next(Observable2DArrayEvent(change: .moveItem($0.from, $0.to) , source: self))
}
// section deletion
subject.next(Observable2DArrayEvent(change: .deleteSections(update.sectionDeletions), source: self))
// section insertions
subject.next(Observable2DArrayEvent(change: .insertSections(update.sectionInsertions), source: self))
// section moves
update.sectionMoves.forEach {
subject.next(Observable2DArrayEvent(change: .moveSection($0.from, $0.to), source: self))
}
subject.next(Observable2DArrayEvent(change: .endBatchEditing, source: self))
lock.unlock()
} else {
replace(with: array)
}
}
}
fileprivate struct NestedBatchUpdate {
let itemDeletions: [IndexPath]
let itemInsertions: [IndexPath]
let itemMoves: [(from: IndexPath, to: IndexPath)]
let sectionDeletions: IndexSet
let sectionInsertions: IndexSet
let sectionMoves: [(from: Int, to: Int)]
init(diff: NestedExtendedDiff) {
var itemDeletions: [IndexPath] = []
var itemInsertions: [IndexPath] = []
var itemMoves: [(IndexPath, IndexPath)] = []
var sectionDeletions: IndexSet = []
var sectionInsertions: IndexSet = []
var sectionMoves: [(from: Int, to: Int)] = []
diff.forEach { element in
switch element {
case let .deleteElement(at, section):
itemDeletions.append(IndexPath(item: at, section: section))
case let .insertElement(at, section):
itemInsertions.append(IndexPath(item: at, section: section))
case let .moveElement(from, to):
itemMoves.append((IndexPath(item: from.item, section: from.section), IndexPath(item: to.item, section: to.section)))
case let .deleteSection(at):
sectionDeletions.insert(at)
case let .insertSection(at):
sectionInsertions.insert(at)
case let .moveSection(move):
sectionMoves.append(move)
}
}
self.itemInsertions = itemInsertions
self.itemDeletions = itemDeletions
self.itemMoves = itemMoves
self.sectionMoves = sectionMoves
self.sectionInsertions = sectionInsertions
self.sectionDeletions = sectionDeletions
}
}
public extension SignalProtocol where Element: Observable2DArrayEventProtocol {
/// Converts diff events into patch events by transforming batch updates into resets (i.e. disabling batch updates).
public func toPatchesByResettingBatch() -> Signal<Observable2DArrayPatchEvent<Element.SectionMetadata, Element.Item>, Error> {
var isBatching = false
return Signal { observer in
return self.observe { event in
switch event {
case .next(let observableArrayEvent):
let source = observableArrayEvent.source
switch observableArrayEvent.change {
case .beginBatchEditing:
isBatching = true
case .endBatchEditing:
isBatching = false
observer.next(.init(change: .reset, source: source))
default:
if !isBatching {
observer.next(.init(change: observableArrayEvent.change, source: source))
}
}
case .failed(let error):
observer.failed(error)
case .completed:
observer.completed()
}
}
}
}
}
|
mit
|
616d75a4b19fd12d10f9d2937196a897
| 37.201288 | 164 | 0.648906 | 4.691121 | false | false | false | false |
azadibogolubov/InterestDestroyer
|
iOS Version/Interest Destroyer/Charts/Classes/Highlight/BarChartHighlighter.swift
|
22
|
6980
|
//
// ChartBarHighlighter.swift
// Charts
//
// Created by Daniel Cohen Gindi on 26/7/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
internal class BarChartHighlighter: ChartHighlighter
{
internal init(chart: BarChartView)
{
super.init(chart: chart)
}
internal override func getHighlight(x x: Double, y: Double) -> ChartHighlight?
{
let h = super.getHighlight(x: x, y: y)
if h === nil
{
return h
}
else
{
if let set = _chart?.data?.getDataSetByIndex(h!.dataSetIndex) as? BarChartDataSet
{
if set.isStacked
{
// create an array of the touch-point
var pt = CGPoint()
pt.y = CGFloat(y)
// take any transformer to determine the x-axis value
_chart?.getTransformer(set.axisDependency).pixelToValue(&pt)
return getStackedHighlight(old: h, set: set, xIndex: h!.xIndex, dataSetIndex: h!.dataSetIndex, yValue: Double(pt.y))
}
}
return h
}
}
internal override func getXIndex(x: Double) -> Int
{
if let barChartData = _chart?.data as? BarChartData
{
if !barChartData.isGrouped
{
return super.getXIndex(x)
}
else
{
let baseNoSpace = getBase(x)
let setCount = barChartData.dataSetCount
var xIndex = Int(baseNoSpace) / setCount
let valCount = barChartData.xValCount
if xIndex < 0
{
xIndex = 0
}
else if xIndex >= valCount
{
xIndex = valCount - 1
}
return xIndex
}
}
else
{
return 0
}
}
internal override func getDataSetIndex(xIndex xIndex: Int, x: Double, y: Double) -> Int
{
if let barChartData = _chart?.data as? BarChartData
{
if !barChartData.isGrouped
{
return 0
}
else
{
let baseNoSpace = getBase(x)
let setCount = barChartData.dataSetCount
var dataSetIndex = Int(baseNoSpace) % setCount
if dataSetIndex < 0
{
dataSetIndex = 0
}
else if dataSetIndex >= setCount
{
dataSetIndex = setCount - 1
}
return dataSetIndex
}
}
else
{
return 0
}
}
/// This method creates the Highlight object that also indicates which value of a stacked BarEntry has been selected.
/// - parameter old: the old highlight object before looking for stacked values
/// - parameter set:
/// - parameter xIndex:
/// - parameter dataSetIndex:
/// - parameter yValue:
/// - returns:
internal func getStackedHighlight(old old: ChartHighlight?, set: BarChartDataSet, xIndex: Int, dataSetIndex: Int, yValue: Double) -> ChartHighlight?
{
let entry = set.entryForXIndex(xIndex) as? BarChartDataEntry
if entry?.values === nil
{
return old
}
if let ranges = getRanges(entry: entry!)
{
let stackIndex = getClosestStackIndex(ranges: ranges, value: yValue)
let h = ChartHighlight(xIndex: xIndex, dataSetIndex: dataSetIndex, stackIndex: stackIndex, range: ranges[stackIndex])
return h
}
return nil
}
/// Returns the index of the closest value inside the values array / ranges (stacked barchart) to the value given as a parameter.
/// - parameter entry:
/// - parameter value:
/// - returns:
internal func getClosestStackIndex(ranges ranges: [ChartRange]?, value: Double) -> Int
{
if ranges == nil
{
return 0
}
var stackIndex = 0
for range in ranges!
{
if range.contains(value)
{
return stackIndex
}
else
{
stackIndex++
}
}
let length = ranges!.count - 1
return (value > ranges![length].to) ? length : 0
}
/// Returns the base x-value to the corresponding x-touch value in pixels.
/// - parameter x:
/// - returns:
internal func getBase(x: Double) -> Double
{
if let barChartData = _chart?.data as? BarChartData
{
// create an array of the touch-point
var pt = CGPoint()
pt.x = CGFloat(x)
// take any transformer to determine the x-axis value
_chart?.getTransformer(ChartYAxis.AxisDependency.Left).pixelToValue(&pt)
let xVal = Double(pt.x)
let setCount = barChartData.dataSetCount ?? 0
// calculate how often the group-space appears
let steps = Int(xVal / (Double(setCount) + Double(barChartData.groupSpace)))
let groupSpaceSum = Double(barChartData.groupSpace) * Double(steps)
let baseNoSpace = xVal - groupSpaceSum
return baseNoSpace
}
else
{
return 0.0
}
}
/// Splits up the stack-values of the given bar-entry into Range objects.
/// - parameter entry:
/// - returns:
internal func getRanges(entry entry: BarChartDataEntry) -> [ChartRange]?
{
let values = entry.values
if (values == nil)
{
return nil
}
var negRemain = -entry.negativeSum
var posRemain: Double = 0.0
var ranges = [ChartRange]()
ranges.reserveCapacity(values!.count)
for (var i = 0, count = values!.count; i < count; i++)
{
let value = values![i]
if value < 0
{
ranges.append(ChartRange(from: negRemain, to: negRemain + abs(value)))
negRemain += abs(value)
}
else
{
ranges.append(ChartRange(from: posRemain, to: posRemain+value))
posRemain += value
}
}
return ranges
}
}
|
apache-2.0
|
3108fd6559174b09d0dc04c2cbec079b
| 27.606557 | 152 | 0.489255 | 5.291888 | false | false | false | false |
leleyinhangjia/leleyinhangjia-DEMO
|
zly-ofo/zly-ofo/封装方法/UIviewHelper.swift
|
1
|
1655
|
//
// UIviewHelper.swift
// zly-ofo
//
// Created by 郑乐银 on 2017/6/4.
// Copyright © 2017年 郑乐银. All rights reserved.
//
extension UIView {
@IBInspectable var boderwidth: CGFloat {
get {
return self.layer.borderWidth
}
set {
self.layer.borderWidth = newValue
}
}
@IBInspectable var borderColor: UIColor {
get {
return UIColor(cgColor: self.layer.borderColor!)
}
set {
self.layer.borderColor = newValue.cgColor
}
}
@IBInspectable var cornerRadius: CGFloat {
get {
return self.layer.cornerRadius
}
set {
self.layer.cornerRadius = newValue
self.layer.masksToBounds = newValue > 0
}
}
}
@IBDesignable class zlyPreviewLabel:UILabel {
}
import AVFoundation
func turnTorch() {
guard let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) else {
return
}
if device.hasTorch && device.isTorchAvailable {
try? device.lockForConfiguration()
if device.torchMode == .off {
device.torchMode = .on
}else {
device.torchMode = .off
}
device.unlockForConfiguration()
}
}
func voiceBtnStatus(voiceBtn: UIButton) {
let defauts = UserDefaults.standard
if defauts.bool(forKey: "isVoiceOn") {
voiceBtn.setImage(#imageLiteral(resourceName: "voiceopen"), for: .normal)
}else {
voiceBtn.setImage(#imageLiteral(resourceName: "voiceclose"), for: .normal)
}
}
|
mit
|
0c9e9b5140afa6313b3a7544df1b63cb
| 20.025641 | 92 | 0.576829 | 4.493151 | false | false | false | false |
benlangmuir/swift
|
test/SymbolGraph/Symbols/Names.swift
|
11
|
1648
|
// RUN: %empty-directory(%t)
// RUN: %target-build-swift %s -module-name Names -emit-module -emit-module-path %t/
// RUN: %target-swift-symbolgraph-extract -module-name Names -I %t -pretty-print -output-dir %t
// RUN: %FileCheck %s --input-file %t/Names.symbols.json
// RUN: %FileCheck %s --input-file %t/Names.symbols.json --check-prefix=FUNC
// RUN: %FileCheck %s --input-file %t/Names.symbols.json --check-prefix=INNERTYPE
// RUN: %FileCheck %s --input-file %t/Names.symbols.json --check-prefix=INNERTYPEALIAS
// RUN: %FileCheck %s --input-file %t/Names.symbols.json --check-prefix=INNERENUM
// RUN: %FileCheck %s --input-file %t/Names.symbols.json --check-prefix=INNERCASE
public struct MyStruct {
public struct InnerStruct {}
public typealias InnerTypeAlias = InnerStruct
public func foo() {}
public enum InnerEnum {
case InnerCase
}
}
// CHECK-LABEL: "precise": "s:5Names8MyStructV"
// CHECK: names
// CHECK-NEXT: "title": "MyStruct"
// FUNC-LABEL: "precise": "s:5Names8MyStructV3fooyyF",
// FUNC: names
// FUNC-NEXT: "title": "foo()"
// INNERTYPE-LABEL: "precise": "s:5Names8MyStructV05InnerC0V"
// INNERTYPE: names
// INNERTYPE-NEXT: "title": "MyStruct.InnerStruct"
// INNERTYPEALIAS-LABEL: "precise": "s:5Names8MyStructV14InnerTypeAliasa"
// INNERTYPEALIAS: names
// INNERTYPEALIAS-NEXT: "title": "MyStruct.InnerTypeAlias"
// INNERENUM-LABEL: "precise": "s:5Names8MyStructV9InnerEnumO",
// INNERENUM: names
// INNERENUM-NEXT: "title": "MyStruct.InnerEnum"
// INNERCASE-LABEL: "precise": "s:5Names8MyStructV9InnerEnumO0D4CaseyA2EmF",
// INNERCASE: names
// INNERCASE-NEXT: "title": "MyStruct.InnerEnum.InnerCase",
|
apache-2.0
|
c13175b9ac27755415effed3fbc9be99
| 35.622222 | 95 | 0.717233 | 3.057514 | false | false | false | false |
agalue/TicTacToe
|
TicTacToe/Matrix.swift
|
1
|
1290
|
//
// Matrix.swift
// TicTacToe
//
// Created by Alejandro Galue on 11/8/15.
// Copyright © 2015 Street Dog Studio. All rights reserved.
//
public struct Matrix {
let rows: Int, columns: Int
var grid: [Int]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
grid = Array(count: rows * columns, repeatedValue: 0)
}
func indexIsValidForRow(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
func indexIsValid(idx : Int) -> Bool {
return idx >= 0 && idx <= rows * columns
}
subscript(row: Int, column: Int) -> Int {
get {
assert(indexIsValidForRow(row, column: column), "Index out of range")
return grid[(row * columns) + column]
}
set {
assert(indexIsValidForRow(row, column: column), "Index out of range")
grid[(row * columns) + column] = newValue
}
}
subscript(index : Int) -> Int {
get {
assert(indexIsValid(index), "Index out of range")
return grid[index]
}
set {
assert(indexIsValid(index), "Index out of range")
grid[index] = newValue
}
}
}
|
gpl-3.0
|
b18cf156822d0f451571ee1c1210498f
| 25.326531 | 81 | 0.535299 | 4.13141 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.