repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
cooliean/CLLKit | XLForm/Examples/Swift/SwiftExample/PredicateExamples/PredicateFormViewController.swift | 14 | 5028 | //
// PredicateFormViewController.swift
// XLForm ( https://github.com/xmartlabs/XLForm )
//
// Copyright (c) 2014-2015 Xmartlabs ( http://xmartlabs.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.
class PredicateFormViewController : XLFormViewController {
private struct Tags {
static let Text = "text"
static let Integer = "integer"
static let Switch = "switch"
static let Date = "date"
static let Account = "account"
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
initializeForm()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initializeForm()
}
func initializeForm() {
let form : XLFormDescriptor
var section : XLFormSectionDescriptor
var row : XLFormRowDescriptor
form = XLFormDescriptor(title: "Predicates example")
section = XLFormSectionDescriptor()
section.title = "Independent rows"
form.addFormSection(section)
row = XLFormRowDescriptor(tag: Tags.Text, rowType: XLFormRowDescriptorTypeAccount, title:"Text")
row.cellConfigAtConfigure["textField.placeholder"] = "Type disable"
section.addFormRow(row)
row = XLFormRowDescriptor(tag: Tags.Integer, rowType: XLFormRowDescriptorTypeInteger, title:"Integer")
row.hidden = NSPredicate(format: "$\(Tags.Switch).value==0")
section.addFormRow(row)
row = XLFormRowDescriptor(tag: Tags.Switch, rowType: XLFormRowDescriptorTypeBooleanSwitch, title:"Boolean")
row.value = true
section.addFormRow(row)
form.addFormSection(section)
section = XLFormSectionDescriptor()
section.title = "Dependent section"
section.footerTitle = "Type disable in the textfield, a number between 18 and 60 in the integer field or use the switch to disable the last row. By doing all three the last section will hide.\nThe integer field hides when the boolean switch is set to 0."
form.addFormSection(section)
// Predicate Disabling
row = XLFormRowDescriptor(tag: Tags.Date, rowType: XLFormRowDescriptorTypeDateInline, title:"Disabled")
row.value = NSDate()
section.addFormRow(row)
row.disabled = NSPredicate(format: "$\(Tags.Text).value contains[c] 'disable' OR ($\(Tags.Integer).value between {18, 60}) OR ($\(Tags.Switch).value == 0)")
section.hidden = NSPredicate(format: "($\(Tags.Text).value contains[c] 'disable') AND ($\(Tags.Integer).value between {18, 60}) AND ($\(Tags.Switch).value == 0)")
section = XLFormSectionDescriptor()
section.title = "More predicates..."
section.footerTitle = "This row hides when the row of the previous section is disabled and the textfield in the first section contains \"out\"\n\nPredicateFormViewController.swift"
form.addFormSection(section)
row = XLFormRowDescriptor(tag: "thirds", rowType:XLFormRowDescriptorTypeAccount, title:"Account")
section.addFormRow(row)
row.hidden = NSPredicate(format: "$\(Tags.Date).isDisabled == 1 AND $\(Tags.Text).value contains[c] 'Out'")
row.onChangeBlock = { [weak self] oldValue, newValue, _ in
let noValue = "No Value"
let message = "Old value: \(oldValue ?? noValue), New value: \(newValue ?? noValue)"
let alertView = UIAlertController(title: "Account Field changed", message: message, preferredStyle: .ActionSheet)
alertView.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
self?.navigationController?.presentViewController(alertView, animated: true, completion: nil)
}
self.form = form
}
}
| mit |
jmgc/swift | test/Driver/Dependencies/driver-show-incremental-mutual-fine.swift | 1 | 1665 | /// main <==> other
// RUN: %empty-directory(%t)
// RUN: cp -r %S/Inputs/mutual-with-swiftdeps-fine/* %t
// RUN: touch -t 201401240005 %t/*
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v -driver-show-incremental 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s
// CHECK-FIRST-DAG: Handled main.swift
// CHECK-FIRST-DAG: Handled other.swift
// CHECK-FIRST-DAG: Disabling incremental build: could not read build record
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v -driver-show-incremental 2>&1 | %FileCheck -check-prefix=CHECK-SECOND %s
// CHECK-SECOND-NOT: Queuing
// RUN: touch -t 201401240006 %t/other.swift
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v -driver-show-incremental 2>&1 | %FileCheck -check-prefix=CHECK-THIRD %s
// CHECK-THIRD: Queuing (initial): {compile: other.o <= other.swift}
// CHECK-THIRD-DAG: Queuing because of the initial set: {compile: main.o <= main.swift}
// CHECK-THIRD-DAG: interface of top-level name 'a' in other.swift -> interface of source file main.swiftdeps
| apache-2.0 |
auth0-tutorials/mvvm_viper | VIPER Contacts Starter/VIPER Contacts Starter/AddContact/Presenter/AddContactPresenter.swift | 1 | 954 | //
// Created by AUTHOR
// Copyright (c) YEAR AUTHOR. All rights reserved.
//
class AddContactPresenter: AddContactPresenterProtocol, AddContactInteractorOutputProtocol {
weak var view: AddContactViewProtocol?
var interactor: AddContactInteractorInputProtocol?
var wireFrame: AddContactWireFrameProtocol?
var delegate: AddModuleDelegate?
func cancelAddContactAction() {
if let view = view {
wireFrame?.dismissAddContactInterface(from: view) { [weak delegate] in
delegate?.didCancelAddContact()
}
}
}
func addNewContact(firstName: String, lastName: String) {
let contact = interactor?.saveNewContact(firstName: firstName, lastName: lastName)
if let view = view, let contact = contact {
wireFrame?.dismissAddContactInterface(from: view) { [weak delegate] in
delegate?.didAddContact(contact)
}
}
}
}
| mit |
boqian2000/swift-algorithm-club | Trie/Trie/Trie/AppDelegate.swift | 2 | 504 | //
// AppDelegate.swift
// Trie
//
// Created by Rick Zaccone on 2016-12-12.
// Copyright © 2016 Rick Zaccone. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
| mit |
quadro5/swift3_L | Swift_api.playground/Pages/Pass Reference Value.xcplaygroundpage/Contents.swift | 1 | 1261 | //: [Previous](@previous)
import Foundation
var str = "Hello, playground"
//: [Next](@next)
func test() {
var num = 1
func passRef(_ input: inout Int) {
print("input: \(input)")
print("num: \(num)")
input = 2
print("input: \(input)")
print("num: \(num)")
}
print("before num: \(num)")
passRef(&num)
print("after num: \(num)")
}
test()
print("\ntestArray")
func testArray() {
var num = [1, 2, 3]
func passRef(_ input: inout [Int]) {
print("input: \(input)")
print("num: \(num)")
input = [1,2]
print("input: \(input)")
print("num: \(num)")
}
print("before num: \(num)")
passRef(&num)
print("after num: \(num)")
}
testArray()
print("\ntestArray2")
class TestArray {
var num = [1, 2, 3]
func testArray() {
print("before num: \(num)")
passRef(&num)
print("after num: \(num)")
}
func passRef(_ input: inout [Int]) {
print("input: \(input)")
print("num: \(self.num)")
input = [1,2]
print("input: \(input)")
print("num: \(self.num)")
}
}
let testArrayClass = TestArray()
testArrayClass.testArray()
| unlicense |
yangyueguang/MyCocoaPods | Extension/Collection+Extension.swift | 1 | 6247 | //
// Collection+Extension.swift
// MyCocoaPods
//
// Created by Chao Xue 薛超 on 2018/12/12.
// Copyright © 2018 Super. All rights reserved.
//
import Foundation
public extension Array{
/// 返回对象数组对应的json数组 前提element一定是AnyObject类型
func jsonArray() -> [[String: Any]] {
var jsonObjects: [[String: Any]] = []
for element in self {
let model: AnyObject = element as AnyObject
let jsonDict = model.dictionaryRepresentation()
jsonObjects.append(jsonDict)
}
return jsonObjects
}
/// 安全的取值
public func item(at index: Int) -> Element? {
guard startIndex..<endIndex ~= index else { return nil }
return self[index]
}
/// 交换
public mutating func swap(from index: Int, to: Int) {
guard index != to,
startIndex..<endIndex ~= index,
startIndex..<endIndex ~= to else { return }
swapAt(index, to)
}
/// 找到的元素的地址列表
public func indexs(where condition: (Element) throws -> Bool) rethrows -> [Int] {
var indicies: [Int] = []
for (index, value) in lazy.enumerated() {
if try condition(value) { indicies.append(index) }
}
return indicies
}
/// 是否全是某种条件的对象
public func isAll(Where condition: (Element) throws -> Bool) rethrows -> Bool {
return try !contains { try !condition($0) }
}
/// 是否全不是某种条件对象
public func isNone(Where condition: (Element) throws -> Bool) rethrows -> Bool {
return try !contains { try condition($0) }
}
/// 对满足条件的每个对象采取行动
public func forEach(where condition: (Element) throws -> Bool, body: (Element) throws -> Void) rethrows {
for element in self where try condition(element) {
try body(element)
}
}
/// 数组筛选
public func filtered<T>(_ isIncluded: (Element) throws -> Bool, map transform: (Element) throws -> T) rethrows -> [T] {
#if swift(>=4.1)
return try compactMap({
if try isIncluded($0) {
return try transform($0)
}
return nil
})
#else
return try flatMap({
if try isIncluded($0) {
return try transform($0)
}
return nil
})
#endif
}
/// 分组
public func group(by size: Int) -> [[Element]] {
guard size > 0, !isEmpty else { return [] }
var value: Int = 0
var slices: [[Element]] = []
while value < count {
slices.append(Array(self[Swift.max(value, startIndex)..<Swift.min(value + size, endIndex)]))
value += size
}
return slices
}
/// 分为满足和不满足条件的两组
public func divided(by condition: (Element) throws -> Bool) rethrows -> (matching: [Element], nonMatching: [Element]) {
var matching = [Element]()
var nonMatching = [Element]()
for element in self {
if try condition(element) {
matching.append(element)
} else {
nonMatching.append(element)
}
}
return (matching, nonMatching)
}
/// 排序
public func sorted<T: Comparable>(by path: KeyPath<Element, T?>, ascending: Bool = true) -> [Element] {
return sorted(by: { (lhs, rhs) -> Bool in
guard let lhsValue = lhs[keyPath: path], let rhsValue = rhs[keyPath: path] else { return false }
if ascending {
return lhsValue < rhsValue
}
return lhsValue > rhsValue
})
}
}
public extension Array where Element: Equatable {
/// 是否包含
public func contains(_ elements: [Element]) -> Bool {
guard !elements.isEmpty else { return true }
var found = true
for element in elements {
if !contains(element) {
found = false
}
}
return found
}
/// 删除
public mutating func removeAll(_ items: [Element]) {
guard !items.isEmpty else { return }
self = filter { !items.contains($0) }
}
/// 去重
public mutating func removeDuplicates() {
self = reduce(into: [Element]()) {
if !$0.contains($1) {
$0.append($1)
}
}
}
func index(_ e: Element) -> Int? {
for (index, value) in lazy.enumerated() where value == e {
return index
}
return nil
}
}
public extension Dictionary{
func jsonString(prettify: Bool = false) -> String {
guard JSONSerialization.isValidJSONObject(self) else {
return ""
}
let options = (prettify == true) ? JSONSerialization.WritingOptions.prettyPrinted : JSONSerialization.WritingOptions()
guard let jsonData = try? JSONSerialization.data(withJSONObject: self, options: options) else { return "" }
return String(data: jsonData, encoding: .utf8) ?? ""
}
/// let result = dict + dict2
public static func + (lhs: [Key: Value], rhs: [Key: Value]) -> [Key: Value] {
var result = lhs
rhs.forEach { result[$0] = $1 }
return result
}
/// dict += dict2
public static func += (lhs: inout [Key: Value], rhs: [Key: Value]) {
rhs.forEach { lhs[$0] = $1}
}
/// let result = dict-["key1", "key2"]
public static func - (lhs: [Key: Value], keys: [Key]) -> [Key: Value] {
var result = lhs
result.removeAll(keys: keys)
return result
}
/// dict-=["key1", "key2"]
public static func -= (lhs: inout [Key: Value], keys: [Key]) {
lhs.removeAll(keys: keys)
}
public mutating func removeAll(keys: [Key]) {
keys.forEach({ removeValue(forKey: $0)})
}
public func count(where condition: @escaping ((key: Key, value: Value)) throws -> Bool) rethrows -> Int {
var count: Int = 0
try self.forEach {
if try condition($0) {
count += 1
}
}
return count
}
}
| mit |
SummerHF/SinaPractice | sina/Pods/LTMorphingLabel/LTMorphingLabel/LTMorphingLabel+Anvil.swift | 5 | 11271 | //
// LTMorphingLabel+Anvil.swift
// https://github.com/lexrus/LTMorphingLabel
//
// The MIT License (MIT)
// Copyright (c) 2016 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 {
func AnvilLoad() {
startClosures["Anvil\(LTMorphingPhases.Start)"] = {
self.emitterView.removeAllEmitters()
guard self.newRects.count > 0 else { return }
let centerRect = self.newRects[Int(self.newRects.count / 2)]
self.emitterView.createEmitter(
"leftSmoke",
particleName: "Smoke",
duration: 0.6
) { (layer, cell) in
layer.emitterSize = CGSize(width: 1, height: 1)
layer.emitterPosition = CGPoint(
x: centerRect.origin.x,
y: centerRect.origin.y + centerRect.size.height / 1.3)
layer.renderMode = kCAEmitterLayerSurface
cell.emissionLongitude = CGFloat(M_PI / 2.0)
cell.scale = self.font.pointSize / 90.0
cell.scaleSpeed = self.font.pointSize / 130
cell.birthRate = 60
cell.velocity = CGFloat(80 + Int(arc4random_uniform(60)))
cell.velocityRange = 100
cell.yAcceleration = -40
cell.xAcceleration = 70
cell.emissionLongitude = CGFloat(-M_PI_2)
cell.emissionRange = CGFloat(M_PI_4) / 5.0
cell.lifetime = self.morphingDuration * 2.0
cell.spin = 10
cell.alphaSpeed = -0.5 / self.morphingDuration
}
self.emitterView.createEmitter(
"rightSmoke",
particleName: "Smoke",
duration: 0.6
) { (layer, cell) in
layer.emitterSize = CGSize(width: 1, height: 1)
layer.emitterPosition = CGPoint(
x: centerRect.origin.x,
y: centerRect.origin.y + centerRect.size.height / 1.3)
layer.renderMode = kCAEmitterLayerSurface
cell.emissionLongitude = CGFloat(M_PI / 2.0)
cell.scale = self.font.pointSize / 90.0
cell.scaleSpeed = self.font.pointSize / 130
cell.birthRate = 60
cell.velocity = CGFloat(80 + Int(arc4random_uniform(60)))
cell.velocityRange = 100
cell.yAcceleration = -40
cell.xAcceleration = -70
cell.emissionLongitude = CGFloat(M_PI_2)
cell.emissionRange = CGFloat(-M_PI_4) / 5.0
cell.lifetime = self.morphingDuration * 2.0
cell.spin = -10
cell.alphaSpeed = -0.5 / self.morphingDuration
}
self.emitterView.createEmitter(
"leftFragments",
particleName: "Fragment",
duration: 0.6
) { (layer, cell) in
layer.emitterSize = CGSize(
width: self.font.pointSize,
height: 1
)
layer.emitterPosition = CGPoint(
x: centerRect.origin.x,
y: centerRect.origin.y + centerRect.size.height / 1.3
)
cell.scale = self.font.pointSize / 90.0
cell.scaleSpeed = self.font.pointSize / 40.0
cell.color = self.textColor.CGColor
cell.birthRate = 60
cell.velocity = 350
cell.yAcceleration = 0
cell.xAcceleration = CGFloat(10 * Int(arc4random_uniform(10)))
cell.emissionLongitude = CGFloat(-M_PI_2)
cell.emissionRange = CGFloat(M_PI_4) / 5.0
cell.alphaSpeed = -2
cell.lifetime = self.morphingDuration
}
self.emitterView.createEmitter(
"rightFragments",
particleName: "Fragment",
duration: 0.6
) { (layer, cell) in
layer.emitterSize = CGSize(
width: self.font.pointSize,
height: 1
)
layer.emitterPosition = CGPoint(
x: centerRect.origin.x,
y: centerRect.origin.y + centerRect.size.height / 1.3)
cell.scale = self.font.pointSize / 90.0
cell.scaleSpeed = self.font.pointSize / 40.0
cell.color = self.textColor.CGColor
cell.birthRate = 60
cell.velocity = 350
cell.yAcceleration = 0
cell.xAcceleration = CGFloat(-10 * Int(arc4random_uniform(10)))
cell.emissionLongitude = CGFloat(M_PI_2)
cell.emissionRange = CGFloat(-M_PI_4) / 5.0
cell.alphaSpeed = -2
cell.lifetime = self.morphingDuration
}
self.emitterView.createEmitter(
"fragments",
particleName: "Fragment",
duration: 0.6
) { (layer, cell) in
layer.emitterSize = CGSize(
width: self.font.pointSize,
height: 1
)
layer.emitterPosition = CGPoint(
x: centerRect.origin.x,
y: centerRect.origin.y + centerRect.size.height / 1.3)
cell.scale = self.font.pointSize / 90.0
cell.scaleSpeed = self.font.pointSize / 40.0
cell.color = self.textColor.CGColor
cell.birthRate = 60
cell.velocity = 250
cell.velocityRange = CGFloat(Int(arc4random_uniform(20)) + 30)
cell.yAcceleration = 500
cell.emissionLongitude = 0
cell.emissionRange = CGFloat(M_PI_2)
cell.alphaSpeed = -1
cell.lifetime = self.morphingDuration
}
}
progressClosures["Anvil\(LTMorphingPhases.Progress)"] = {
(index: Int, progress: Float, isNewChar: Bool) in
if !isNewChar {
return min(1.0, max(0.0, progress))
}
let j = Float(sin(Float(index))) * 1.7
return min(1.0, max(0.0001, progress + self.morphingCharacterDelay * j))
}
effectClosures["Anvil\(LTMorphingPhases.Disappear)"] = {
char, index, progress in
return LTCharacterLimbo(
char: char,
rect: self.previousRects[index],
alpha: CGFloat(1.0 - progress),
size: self.font.pointSize,
drawingProgress: 0.0)
}
effectClosures["Anvil\(LTMorphingPhases.Appear)"] = {
char, index, progress in
var rect = self.newRects[index]
if progress < 1.0 {
let easingValue = LTEasing.easeOutBounce(progress, 0.0, 1.0)
rect.origin.y = CGFloat(Float(rect.origin.y) * easingValue)
}
if progress > self.morphingDuration * 0.5 {
let end = self.morphingDuration * 0.55
self.emitterView.createEmitter(
"fragments",
particleName: "Fragment",
duration: 0.6
) {_ in}.update {
(layer, cell) in
if progress > end {
layer.birthRate = 0
}
}.play()
self.emitterView.createEmitter(
"leftFragments",
particleName: "Fragment",
duration: 0.6
) {_ in}.update {
(layer, cell) in
if progress > end {
layer.birthRate = 0
}
}.play()
self.emitterView.createEmitter(
"rightFragments",
particleName: "Fragment",
duration: 0.6
) {_ in}.update {
(layer, cell) in
if progress > end {
layer.birthRate = 0
}
}.play()
}
if progress > self.morphingDuration * 0.63 {
let end = self.morphingDuration * 0.7
self.emitterView.createEmitter(
"leftSmoke",
particleName: "Smoke",
duration: 0.6
) {_ in}.update {
(layer, cell) in
if progress > end {
layer.birthRate = 0
}
}.play()
self.emitterView.createEmitter(
"rightSmoke",
particleName: "Smoke",
duration: 0.6
) {_ in}.update {
(layer, cell) in
if progress > end {
layer.birthRate = 0
}
}.play()
}
return LTCharacterLimbo(
char: char,
rect: rect,
alpha: CGFloat(self.morphingProgress),
size: self.font.pointSize,
drawingProgress: CGFloat(progress)
)
}
}
}
| mit |
nathawes/swift | test/stdlib/KeyPath.swift | 8 | 32224 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -import-objc-header %S/Inputs/tail_allocated_c_array.h -swift-version 5 -g %s -o %t/a.out
// RUN: %target-codesign %t/a.out
// RUN: %target-run %t/a.out
// REQUIRES: executable_test
import StdlibUnittest
var keyPath = TestSuite("key paths")
final class C<T> {
var x: Int
var y: LifetimeTracked?
var z: T
let immutable: String
private(set) var secretlyMutable: String
var computed: T {
get {
return z
}
set {
z = newValue
}
}
init(x: Int, y: LifetimeTracked?, z: T) {
self.x = x
self.y = y
self.z = z
self.immutable = "\(x) \(y) \(z)"
self.secretlyMutable = immutable
}
}
struct Point: Equatable {
var x: Double
var y: Double
var trackLifetime = LifetimeTracked(123)
let hypotenuse: Double
private(set) var secretlyMutableHypotenuse: Double
init(x: Double, y: Double) {
self.x = x
self.y = y
hypotenuse = x*x + y*y
secretlyMutableHypotenuse = x*x + y*y
}
static func ==(a: Point, b: Point) -> Bool {
return a.x == b.x && a.y == b.y
}
}
struct S<T: Equatable>: Equatable {
var x: Int
var y: LifetimeTracked?
var z: T
var p: Point
var c: C<T>
static func ==(a: S, b: S) -> Bool {
return a.x == b.x
&& a.y === b.y
&& a.z == b.z
&& a.p == b.p
&& a.c === b.c
}
}
final class ComputedA {
var readOnly: ComputedB { fatalError() }
var nonmutating: ComputedB {
get { fatalError() }
set { fatalError() }
}
var reabstracted: () -> () = {}
}
struct ComputedB {
var readOnly: ComputedA { fatalError() }
var mutating: ComputedA {
get { fatalError() }
set { fatalError() }
}
var nonmutating: ComputedA {
get { fatalError() }
nonmutating set { fatalError() }
}
var reabstracted: () -> () = {}
}
typealias Tuple<T: Equatable, U> = (S<T>, C<U>)
keyPath.test("key path in-place instantiation") {
for _ in 1...2 {
let s_x = (\S<Int>.x as AnyKeyPath) as! WritableKeyPath<S<Int>, Int>
let s_y = (\S<Int>.y as AnyKeyPath) as! WritableKeyPath<S<Int>, LifetimeTracked?>
let s_z = (\S<Int>.z as AnyKeyPath) as! WritableKeyPath<S<Int>, Int>
let s_p = (\S<Int>.p as AnyKeyPath) as! WritableKeyPath<S<Int>, Point>
let s_p_x = (\S<Int>.p.x as AnyKeyPath) as! WritableKeyPath<S<Int>, Double>
let s_p_y = (\S<Int>.p.y as AnyKeyPath) as! WritableKeyPath<S<Int>, Double>
let s_c = (\S<Int>.c as AnyKeyPath) as! WritableKeyPath<S<Int>, C<Int>>
let s_c_x = (\S<Int>.c.x as AnyKeyPath) as! ReferenceWritableKeyPath<S<Int>, Int>
let t_0s = (\Tuple<Int, Int>.0 as AnyKeyPath) as! WritableKeyPath<Tuple<Int, Int>, S<Int>>
let t_1c = (\Tuple<Int, Int>.1 as AnyKeyPath) as! WritableKeyPath<Tuple<Int, Int>, C<Int>>
let t_0s_x = (\Tuple<Int, Int>.0.x as AnyKeyPath) as! WritableKeyPath<Tuple<Int, Int>, Int>
let t_0s_p_hypotenuse = (\Tuple<Int, Int>.0.p.hypotenuse as AnyKeyPath) as! KeyPath<Tuple<Int, Int>, Double>
let t_1c_x = (\Tuple<Int, Int>.1.x as AnyKeyPath) as! ReferenceWritableKeyPath<Tuple<Int, Int>, Int>
let t_1c_immutable = (\Tuple<Int, Int>.1.immutable as AnyKeyPath) as! KeyPath<Tuple<Int, Int>, String>
let c_x = (\C<Int>.x as AnyKeyPath) as! ReferenceWritableKeyPath<C<Int>, Int>
let s_c_x_2 = s_c.appending(path: c_x)
expectEqual(s_c_x, s_c_x_2)
expectEqual(s_c_x_2, s_c_x)
expectEqual(s_c_x.hashValue, s_c_x_2.hashValue)
let t_1c_x_2 = t_1c.appending(path: c_x)
expectEqual(t_1c_x, t_1c_x_2)
expectEqual(t_1c_x_2, t_1c_x)
expectEqual(t_1c_x.hashValue, t_1c_x_2.hashValue)
let point_x = (\Point.x as AnyKeyPath) as! WritableKeyPath<Point, Double>
let point_y = (\Point.y as AnyKeyPath) as! WritableKeyPath<Point, Double>
let s_p_x_2 = s_p.appending(path: point_x)
let s_p_y_2 = s_p.appending(path: point_y)
expectEqual(s_p_x, s_p_x_2)
expectEqual(s_p_x_2, s_p_x)
expectEqual(s_p_x_2.hashValue, s_p_x.hashValue)
expectEqual(s_p_y, s_p_y_2)
expectEqual(s_p_y_2, s_p_y)
expectEqual(s_p_y_2.hashValue, s_p_y.hashValue)
let ca_readOnly = (\ComputedA.readOnly as AnyKeyPath) as! KeyPath<ComputedA, ComputedB>
let ca_nonmutating = (\ComputedA.nonmutating as AnyKeyPath) as! ReferenceWritableKeyPath<ComputedA, ComputedB>
let ca_reabstracted = (\ComputedA.reabstracted as AnyKeyPath) as! ReferenceWritableKeyPath<ComputedA, () -> ()>
let cb_readOnly = (\ComputedB.readOnly as AnyKeyPath) as! KeyPath<ComputedB, ComputedA>
let cb_mutating = (\ComputedB.mutating as AnyKeyPath) as! WritableKeyPath<ComputedB, ComputedA>
let cb_nonmutating = (\ComputedB.nonmutating as AnyKeyPath) as! ReferenceWritableKeyPath<ComputedB, ComputedA>
let cb_reabstracted = (\ComputedB.reabstracted as AnyKeyPath) as! WritableKeyPath<ComputedB, () -> ()>
let ca_readOnly_mutating = (\ComputedA.readOnly.mutating as AnyKeyPath) as! KeyPath<ComputedA, ComputedA>
let cb_mutating_readOnly = (\ComputedB.mutating.readOnly as AnyKeyPath) as! KeyPath<ComputedB, ComputedB>
let ca_readOnly_nonmutating = (\ComputedA.readOnly.nonmutating as AnyKeyPath) as! ReferenceWritableKeyPath<ComputedA, ComputedA>
let cb_readOnly_reabstracted = (\ComputedB.readOnly.reabstracted as AnyKeyPath) as! ReferenceWritableKeyPath<ComputedB, () -> ()>
let ca_readOnly_mutating2 = ca_readOnly.appending(path: cb_mutating)
expectEqual(ca_readOnly_mutating, ca_readOnly_mutating2)
expectEqual(ca_readOnly_mutating2, ca_readOnly_mutating)
expectEqual(ca_readOnly_mutating.hashValue, ca_readOnly_mutating2.hashValue)
let cb_mutating_readOnly2 = cb_mutating.appending(path: ca_readOnly)
expectEqual(cb_mutating_readOnly, cb_mutating_readOnly2)
expectEqual(cb_mutating_readOnly2, cb_mutating_readOnly)
expectEqual(cb_mutating_readOnly.hashValue, cb_mutating_readOnly2.hashValue)
let ca_readOnly_nonmutating2 = ca_readOnly.appending(path: cb_nonmutating)
expectEqual(ca_readOnly_nonmutating, ca_readOnly_nonmutating2)
expectEqual(ca_readOnly_nonmutating2, ca_readOnly_nonmutating)
expectEqual(ca_readOnly_nonmutating.hashValue,
ca_readOnly_nonmutating2.hashValue)
let cb_readOnly_reabstracted2 = cb_readOnly.appending(path: ca_reabstracted)
expectEqual(cb_readOnly_reabstracted,
cb_readOnly_reabstracted2)
expectEqual(cb_readOnly_reabstracted2,
cb_readOnly_reabstracted)
expectEqual(cb_readOnly_reabstracted2.hashValue,
cb_readOnly_reabstracted.hashValue)
}
}
keyPath.test("key path generic instantiation") {
func testWithGenericParam<T: Equatable>(_: T.Type) -> ReferenceWritableKeyPath<S<T>, Int> {
for i in 1...2 {
let s_x = (\S<T>.x as AnyKeyPath) as! WritableKeyPath<S<T>, Int>
let s_y = (\S<T>.y as AnyKeyPath) as! WritableKeyPath<S<T>, LifetimeTracked?>
let s_z = (\S<T>.z as AnyKeyPath) as! WritableKeyPath<S<T>, T>
let s_p = (\S<T>.p as AnyKeyPath) as! WritableKeyPath<S<T>, Point>
let s_p_x = (\S<T>.p.x as AnyKeyPath) as! WritableKeyPath<S<T>, Double>
let s_p_y = (\S<T>.p.y as AnyKeyPath) as! WritableKeyPath<S<T>, Double>
let s_c = (\S<T>.c as AnyKeyPath) as! WritableKeyPath<S<T>, C<T>>
let s_c_x = (\S<T>.c.x as AnyKeyPath) as! ReferenceWritableKeyPath<S<T>, Int>
let t_0s = (\Tuple<T, T>.0 as AnyKeyPath) as! WritableKeyPath<Tuple<T, T>, S<T>>
let t_1c = (\Tuple<T, T>.1 as AnyKeyPath) as! WritableKeyPath<Tuple<T, T>, C<T>>
let t_0s_x = (\Tuple<T, T>.0.x as AnyKeyPath) as! WritableKeyPath<Tuple<T, T>, Int>
let t_0s_p_hypotenuse = (\Tuple<T, T>.0.p.hypotenuse as AnyKeyPath) as! KeyPath<Tuple<T, T>, Double>
let t_1c_x = (\Tuple<T, T>.1.x as AnyKeyPath) as! ReferenceWritableKeyPath<Tuple<T, T>, Int>
let t_1c_immutable = (\Tuple<T, T>.1.immutable as AnyKeyPath) as! KeyPath<Tuple<T, T>, String>
let c_x = (\C<T>.x as AnyKeyPath) as! ReferenceWritableKeyPath<C<T>, Int>
let s_c_x_2 = s_c.appending(path: c_x)
expectEqual(s_c_x, s_c_x_2)
expectEqual(s_c_x_2, s_c_x)
expectEqual(s_c_x.hashValue, s_c_x_2.hashValue)
let t_1c_x_2 = t_1c.appending(path: c_x)
expectEqual(t_1c_x, t_1c_x_2)
expectEqual(t_1c_x_2, t_1c_x)
expectEqual(t_1c_x.hashValue, t_1c_x_2.hashValue)
let point_x = (\Point.x as AnyKeyPath) as! WritableKeyPath<Point, Double>
let point_y = (\Point.y as AnyKeyPath) as! WritableKeyPath<Point, Double>
let s_p_x_2 = s_p.appending(path: point_x)
let s_p_y_2 = s_p.appending(path: point_y)
expectEqual(s_p_x, s_p_x_2)
expectEqual(s_p_x_2, s_p_x)
expectEqual(s_p_x_2.hashValue, s_p_x.hashValue)
expectEqual(s_p_y, s_p_y_2)
expectEqual(s_p_y_2, s_p_y)
expectEqual(s_p_y_2.hashValue, s_p_y.hashValue)
if i == 2 { return s_c_x }
}
fatalError()
}
let s_c_x_int = testWithGenericParam(Int.self)
let s_c_x_int2 = \S<Int>.c.x
expectEqual(s_c_x_int, s_c_x_int2)
let s_c_x_string = testWithGenericParam(String.self)
let s_c_x_string2 = \S<String>.c.x
expectEqual(s_c_x_string, s_c_x_string2)
let s_c_x_lt = testWithGenericParam(LifetimeTracked.self)
let s_c_x_lt2 = \S<LifetimeTracked>.c.x
expectEqual(s_c_x_lt, s_c_x_lt2)
}
protocol P {}
struct TestComputed: P {
static var numNonmutatingSets = 0
static var numMutatingSets = 0
static func resetCounts() {
numNonmutatingSets = 0
numMutatingSets = 0
}
var canary = LifetimeTracked(0)
var readonly: LifetimeTracked {
return LifetimeTracked(1)
}
var nonmutating: LifetimeTracked {
get {
return LifetimeTracked(2)
}
nonmutating set { TestComputed.numNonmutatingSets += 1 }
}
var mutating: LifetimeTracked {
get {
return LifetimeTracked(3)
}
set {
canary = newValue
}
}
}
extension P {
var readonlyProtoExt: Self { return self }
var mutatingProtoExt: Self {
get { return self }
set { self = newValue }
}
}
keyPath.test("computed properties") {
var test = TestComputed()
do {
let tc_readonly = \TestComputed.readonly
expectTrue(test[keyPath: tc_readonly] !== test[keyPath: tc_readonly])
expectEqual(test[keyPath: tc_readonly].value,
test[keyPath: tc_readonly].value)
}
do {
let tc_nonmutating = \TestComputed.nonmutating
expectTrue(test[keyPath: tc_nonmutating] !== test[keyPath: tc_nonmutating])
expectEqual(test[keyPath: tc_nonmutating].value,
test[keyPath: tc_nonmutating].value)
TestComputed.resetCounts()
test[keyPath: tc_nonmutating] = LifetimeTracked(4)
expectEqual(TestComputed.numNonmutatingSets, 1)
}
do {
let tc_mutating = \TestComputed.mutating
expectTrue(test[keyPath: tc_mutating] !== test[keyPath: tc_mutating])
expectEqual(test[keyPath: tc_mutating].value,
test[keyPath: tc_mutating].value)
let newObject = LifetimeTracked(5)
test[keyPath: tc_mutating] = newObject
expectTrue(test.canary === newObject)
}
do {
let tc_readonlyProtoExt = \TestComputed.readonlyProtoExt
expectTrue(test.canary === test[keyPath: tc_readonlyProtoExt].canary)
}
do {
let tc_mutatingProtoExt = \TestComputed.mutatingProtoExt
expectTrue(test.canary === test[keyPath: tc_mutatingProtoExt].canary)
let oldTest = test
test[keyPath: tc_mutatingProtoExt] = TestComputed()
expectTrue(oldTest.canary !== test.canary)
expectTrue(test.canary === test[keyPath: tc_mutatingProtoExt].canary)
}
}
class AB {
}
class ABC: AB, ABCProtocol {
var a = LifetimeTracked(1)
var b = LifetimeTracked(2)
var c = LifetimeTracked(3)
}
protocol ABCProtocol {
var a: LifetimeTracked { get }
var b: LifetimeTracked { get set }
var c: LifetimeTracked { get nonmutating set }
}
keyPath.test("dynamically-typed application") {
let cPaths = [\ABC.a, \ABC.b, \ABC.c]
let subject = ABC()
do {
let fields = cPaths.map { subject[keyPath: $0] }
expectTrue(fields[0] as! AnyObject === subject.a)
expectTrue(fields[1] as! AnyObject === subject.b)
expectTrue(fields[2] as! AnyObject === subject.c)
}
let erasedSubject: AB = subject
let erasedPaths: [AnyKeyPath] = cPaths
let wrongSubject = AB()
do {
let fields = erasedPaths.map { erasedSubject[keyPath: $0] }
expectTrue(fields[0]! as! AnyObject === subject.a)
expectTrue(fields[1]! as! AnyObject === subject.b)
expectTrue(fields[2]! as! AnyObject === subject.c)
let wrongFields = erasedPaths.map { wrongSubject[keyPath: $0] }
expectTrue(wrongFields[0] == nil)
expectTrue(wrongFields[1] == nil)
expectTrue(wrongFields[2] == nil)
}
var protoErasedSubject: ABCProtocol = subject
let protoErasedPathA = \ABCProtocol.a
let protoErasedPathB = \ABCProtocol.b
let protoErasedPathC = \ABCProtocol.c
do {
expectTrue(protoErasedSubject.a ===
protoErasedSubject[keyPath: protoErasedPathA])
let newB = LifetimeTracked(4)
expectTrue(protoErasedSubject.b ===
protoErasedSubject[keyPath: protoErasedPathB])
protoErasedSubject[keyPath: protoErasedPathB] = newB
expectTrue(protoErasedSubject.b ===
protoErasedSubject[keyPath: protoErasedPathB])
expectTrue(protoErasedSubject.b === newB)
let newC = LifetimeTracked(5)
expectTrue(protoErasedSubject.c ===
protoErasedSubject[keyPath: protoErasedPathC])
protoErasedSubject[keyPath: protoErasedPathC] = newC
expectTrue(protoErasedSubject.c ===
protoErasedSubject[keyPath: protoErasedPathC])
expectTrue(protoErasedSubject.c === newC)
}
}
struct TestOptional {
var origin: Point?
var questionableCanary: LifetimeTracked? = LifetimeTracked(123)
init(origin: Point?) {
self.origin = origin
}
}
keyPath.test("optional force-unwrapping") {
let origin_x = \TestOptional.origin!.x
let canary = \TestOptional.questionableCanary!
var value = TestOptional(origin: Point(x: 3, y: 4))
expectEqual(value[keyPath: origin_x], 3)
expectEqual(value.origin!.x, 3)
value[keyPath: origin_x] = 5
expectEqual(value[keyPath: origin_x], 5)
expectEqual(value.origin!.x, 5)
expectTrue(value[keyPath: canary] === value.questionableCanary)
let newCanary = LifetimeTracked(456)
value[keyPath: canary] = newCanary
expectTrue(value[keyPath: canary] === newCanary)
expectTrue(value.questionableCanary === newCanary)
}
keyPath.test("optional force-unwrapping trap") {
let origin_x = \TestOptional.origin!.x
var value = TestOptional(origin: nil)
expectCrashLater()
_ = value[keyPath: origin_x]
}
struct TestOptional2 {
var optional: TestOptional?
}
keyPath.test("optional chaining") {
let origin_x = \TestOptional.origin?.x
let canary = \TestOptional.questionableCanary?.value
let withPoint = TestOptional(origin: Point(x: 3, y: 4))
expectEqual(withPoint[keyPath: origin_x]!, 3)
expectEqual(withPoint[keyPath: canary]!, 123)
let withoutPoint = TestOptional(origin: nil)
expectNil(withoutPoint[keyPath: origin_x])
let optional2: TestOptional2? = TestOptional2(optional: withPoint)
let optional2_optional = \TestOptional2?.?.optional
expectEqual(optional2[keyPath: optional2_optional]!.origin!.x, 3)
expectEqual(optional2[keyPath: optional2_optional]!.origin!.y, 4)
}
func makeKeyPathInGenericContext<T>(of: T.Type)
-> ReferenceWritableKeyPath<C<T>, T> {
return \C<T>.computed
}
keyPath.test("computed generic key paths") {
let path = makeKeyPathInGenericContext(of: LifetimeTracked.self)
let z = LifetimeTracked(456)
let c = C(x: 42, y: LifetimeTracked(123), z: z)
expectTrue(c[keyPath: path] === z)
let z2 = LifetimeTracked(789)
c[keyPath: path] = z2
expectTrue(c[keyPath: path] === z2)
expectTrue(c.z === z2)
let path2 = makeKeyPathInGenericContext(of: LifetimeTracked.self)
expectEqual(path, path2)
expectEqual(path.hashValue, path2.hashValue)
let pathNonGeneric = \C<LifetimeTracked>.computed
expectEqual(path, pathNonGeneric)
expectEqual(path.hashValue, pathNonGeneric.hashValue)
let valuePath = path.appending(path: \LifetimeTracked.value)
expectEqual(c[keyPath: valuePath], 789)
let valuePathNonGeneric = pathNonGeneric.appending(path: \LifetimeTracked.value)
expectEqual(valuePath, valuePathNonGeneric)
expectEqual(valuePath.hashValue, valuePathNonGeneric.hashValue)
}
var numberOfMutatingWritebacks = 0
var numberOfNonmutatingWritebacks = 0
struct NoisyWriteback {
var canary = LifetimeTracked(246)
var mutating: LifetimeTracked {
get { return canary }
set { numberOfMutatingWritebacks += 1 }
}
var nonmutating: LifetimeTracked {
get { return canary }
nonmutating set { numberOfNonmutatingWritebacks += 1 }
}
}
keyPath.test("read-only accesses don't trigger writebacks") {
var x = NoisyWriteback()
x = NoisyWriteback() // suppress "never mutated" warnings
let wkp = \NoisyWriteback.mutating
let rkp = \NoisyWriteback.nonmutating
numberOfMutatingWritebacks = 0
numberOfNonmutatingWritebacks = 0
_ = x[keyPath: wkp]
_ = x[keyPath: rkp]
expectEqual(x[keyPath: wkp].value, 246)
expectEqual(x[keyPath: rkp].value, 246)
expectEqual(numberOfMutatingWritebacks, 0)
expectEqual(numberOfNonmutatingWritebacks, 0)
let y = x
_ = y[keyPath: wkp]
_ = y[keyPath: rkp]
expectEqual(y[keyPath: wkp].value, 246)
expectEqual(y[keyPath: rkp].value, 246)
expectEqual(numberOfMutatingWritebacks, 0)
expectEqual(numberOfNonmutatingWritebacks, 0)
}
var nestedWritebackLog = 0
struct NoisyNestingWriteback {
var value: Int
var nested: NoisyNestingWriteback {
get {
return NoisyNestingWriteback(value: value + 1)
}
set {
nestedWritebackLog = nestedWritebackLog << 8 | newValue.value
value = newValue.value - 1
}
}
}
keyPath.test("writebacks nest properly") {
var test = NoisyNestingWriteback(value: 0)
nestedWritebackLog = 0
test.nested.nested.nested.value = 0x38
expectEqual(nestedWritebackLog, 0x383736)
nestedWritebackLog = 0
let kp = \NoisyNestingWriteback.nested.nested.nested
test[keyPath: kp].value = 0x38
expectEqual(nestedWritebackLog, 0x383736)
}
struct IUOWrapper {
var wrapped: IUOWrapped!
}
struct IUOWrapped {
var value: Int
}
keyPath.test("IUO and key paths") {
var subject = IUOWrapper(wrapped: IUOWrapped(value: 1989))
let kp1 = \IUOWrapper.wrapped.value
expectEqual(subject[keyPath: kp1], 1989)
subject[keyPath: kp1] = 1738
expectEqual(subject[keyPath: kp1], 1738)
expectEqual(subject.wrapped.value, 1738)
let kp2 = \IUOWrapper.wrapped!.value
expectEqual(kp1, kp2)
expectEqual(kp1.hashValue, kp2.hashValue)
}
struct SubscriptResult<T: Hashable, U: Hashable> {
var canary = LifetimeTracked(3333)
var left: T
var right: U
init(left: T, right: U) {
self.left = left
self.right = right
}
subscript(left: T) -> Bool {
return self.left == left
}
subscript(right: U) -> Bool {
return self.right == right
}
}
struct Subscripts<T: Hashable> {
var canary = LifetimeTracked(4444)
subscript<U: Hashable>(x: T, y: U) -> SubscriptResult<T, U> {
return SubscriptResult(left: x, right: y)
}
subscript(x: Int, y: Int) -> Int {
return x + y
}
}
struct KeyA: Hashable {
var canary = LifetimeTracked(1111)
var value: String
init(value: String) { self.value = value }
static func ==(a: KeyA, b: KeyA) -> Bool { return a.value == b.value }
func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
}
struct KeyB: Hashable {
var canary = LifetimeTracked(2222)
var value: Int
init(value: Int) { self.value = value }
static func ==(a: KeyB, b: KeyB) -> Bool { return a.value == b.value }
func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
}
func fullGenericContext<T: Hashable, U: Hashable>(x: T, y: U) -> KeyPath<Subscripts<T>, SubscriptResult<T, U>> {
return \Subscripts<T>.[x, y]
}
func halfGenericContext<U: Hashable>(x: KeyA, y: U) -> KeyPath<Subscripts<KeyA>, SubscriptResult<KeyA, U>> {
return \Subscripts<KeyA>.[x, y]
}
func nonGenericContext(x: KeyA, y: KeyB) -> KeyPath<Subscripts<KeyA>, SubscriptResult<KeyA, KeyB>> {
return \Subscripts<KeyA>.[x, y]
}
keyPath.test("subscripts") {
let a = fullGenericContext(x: KeyA(value: "hey"), y: KeyB(value: 1738))
let b = halfGenericContext(x: KeyA(value: "hey"), y: KeyB(value: 1738))
let c = nonGenericContext(x: KeyA(value: "hey"), y: KeyB(value: 1738))
expectEqual(a, b)
expectEqual(a, c)
expectEqual(b, a)
expectEqual(b, c)
expectEqual(c, a)
expectEqual(c, b)
expectEqual(a.hashValue, b.hashValue)
expectEqual(a.hashValue, c.hashValue)
expectEqual(b.hashValue, a.hashValue)
expectEqual(b.hashValue, c.hashValue)
expectEqual(c.hashValue, a.hashValue)
expectEqual(c.hashValue, b.hashValue)
let base = Subscripts<KeyA>()
let kp2 = \SubscriptResult<KeyA, KeyB>.[KeyA(value: "hey")]
for kp in [a, b, c] {
let projected = base[keyPath: kp]
expectEqual(projected.left.value, "hey")
expectEqual(projected.right.value, 1738)
expectEqual(projected[keyPath: kp2], true)
let kp12 =
\Subscripts<KeyA>.[KeyA(value: "hey"), KeyB(value: 1738)][KeyA(value: "hey")]
let kp12a = kp.appending(path: kp2)
expectEqual(kp12, kp12a)
expectEqual(kp12a, kp12)
expectEqual(kp12.hashValue, kp12a.hashValue)
}
let ints = \Subscripts<KeyA>.[17, 38]
let ints2 = \Subscripts<KeyA>.[17, 38]
let ints3 = \Subscripts<KeyA>.[38, 17]
expectEqual(base[keyPath: ints], 17 + 38)
expectEqual(ints, ints2)
expectEqual(ints2, ints)
expectNotEqual(ints, ints3)
expectNotEqual(ints2, ints3)
expectNotEqual(ints3, ints)
expectNotEqual(ints3, ints2)
expectEqual(ints.hashValue, ints2.hashValue)
let ints_be = ints.appending(path: \Int.bigEndian)
expectEqual(base[keyPath: ints_be], (17 + 38).bigEndian)
}
struct NonOffsetableProperties {
// observers
var x: Int { didSet {} }
// reabstracted
var y: () -> ()
// computed
var z: Int { return 0 }
}
struct TupleProperties {
// unlabeled
var a: (Int, String)
// labeled
let b: (x: String, y: Int)
// reference writable
let c: (m: C<Int>, n: C<String>)
}
func getIdentityKeyPathOfType<T>(_: T.Type) -> KeyPath<T, T> {
return \.self
}
keyPath.test("offsets") {
let SLayout = MemoryLayout<S<Int>>.self
expectNotNil(SLayout.offset(of: \S<Int>.x))
expectNotNil(SLayout.offset(of: \S<Int>.y))
expectNotNil(SLayout.offset(of: \S<Int>.z))
expectNotNil(SLayout.offset(of: \S<Int>.p))
expectNotNil(SLayout.offset(of: \S<Int>.p.x))
expectNotNil(SLayout.offset(of: \S<Int>.p.y))
expectNotNil(SLayout.offset(of: \S<Int>.c))
expectNil(SLayout.offset(of: \S<Int>.c.x))
let NOPLayout = MemoryLayout<NonOffsetableProperties>.self
expectNil(NOPLayout.offset(of: \NonOffsetableProperties.x))
expectNil(NOPLayout.offset(of: \NonOffsetableProperties.y))
expectNil(NOPLayout.offset(of: \NonOffsetableProperties.z))
expectEqual(SLayout.offset(of: \.self), 0)
expectEqual(SLayout.offset(of: getIdentityKeyPathOfType(S<Int>.self)), 0)
let TPLayout = MemoryLayout<TupleProperties>.self
expectEqual(TPLayout.offset(of: \TupleProperties.self), 0)
expectEqual(TPLayout.offset(of: \TupleProperties.a), 0)
expectEqual(TPLayout.offset(of: \TupleProperties.a.0), 0)
expectEqual(TPLayout.offset(of: \TupleProperties.a.1), MemoryLayout<Int>.size)
expectEqual(TPLayout.offset(of: \TupleProperties.b), MemoryLayout<(Int, String)>.size)
expectEqual(TPLayout.offset(of: \TupleProperties.b.x), MemoryLayout<(Int, String)>.size)
expectEqual(TPLayout.offset(of: \TupleProperties.b.y), MemoryLayout<(Int, String, String)>.size)
expectEqual(TPLayout.offset(of: \TupleProperties.c), MemoryLayout<(Int, String, String, Int)>.size)
expectEqual(TPLayout.offset(of: \TupleProperties.c.m), MemoryLayout<(Int, String, String, Int)>.size)
expectEqual(TPLayout.offset(of: \TupleProperties.c.n), MemoryLayout<(Int, String, String, Int, C<Int>)>.size)
let TLayout = MemoryLayout<Tuple<Int, Int>>.self
expectEqual(TLayout.offset(of: \Tuple<Int, Int>.self), 0)
expectEqual(TLayout.offset(of: \Tuple<Int, Int>.0), 0)
expectEqual(TLayout.offset(of: \Tuple<Int, Int>.0.x), 0)
expectEqual(TLayout.offset(of: \Tuple<Int, Int>.1), SLayout.size)
}
keyPath.test("identity key path") {
var x = LifetimeTracked(1738)
let id = \LifetimeTracked.self
expectTrue(x === x[keyPath: id])
let newX = LifetimeTracked(679)
x[keyPath: id] = newX
expectTrue(x === newX)
let id2 = getIdentityKeyPathOfType(LifetimeTracked.self)
expectEqual(id, id2)
expectEqual(id.hashValue, id2.hashValue)
expectNotNil(id2 as? WritableKeyPath)
let id3 = id.appending(path: id2)
expectEqual(id, id3)
expectEqual(id.hashValue, id3.hashValue)
expectNotNil(id3 as? WritableKeyPath)
let valueKey = \LifetimeTracked.value
let valueKey2 = id.appending(path: valueKey)
let valueKey3 = (valueKey as KeyPath).appending(path: \Int.self)
expectEqual(valueKey, valueKey2)
expectEqual(valueKey.hashValue, valueKey2.hashValue)
expectEqual(valueKey, valueKey3)
expectEqual(valueKey.hashValue, valueKey3.hashValue)
expectEqual(x[keyPath: valueKey2], 679)
expectEqual(x[keyPath: valueKey3], 679)
}
keyPath.test("tuple key path") {
let t0 = \TupleProperties.a.0
expectNotNil(t0 as? KeyPath<TupleProperties, Int>)
expectNotNil(t0 as? WritableKeyPath<TupleProperties, Int>)
expectNil(t0 as? ReferenceWritableKeyPath<TupleProperties, Int>)
let t1 = \TupleProperties.a.1
expectNotNil(t1 as? KeyPath<TupleProperties, String>)
expectNotNil(t1 as? WritableKeyPath<TupleProperties, String>)
expectNil(t1 as? ReferenceWritableKeyPath<TupleProperties, String>)
let t2 = \TupleProperties.b.x
expectNotNil(t2 as? KeyPath<TupleProperties, String>)
expectNil(t2 as? WritableKeyPath<TupleProperties, String>)
expectNil(t2 as? ReferenceWritableKeyPath<TupleProperties, String>)
let t3 = \TupleProperties.b.y
expectNotNil(t3 as? KeyPath<TupleProperties, Int>)
expectNil(t3 as? WritableKeyPath<TupleProperties, Int>)
expectNil(t3 as? ReferenceWritableKeyPath<TupleProperties, Int>)
let t4 = \TupleProperties.c.m
expectNotNil(t4 as? KeyPath<TupleProperties, C<Int>>)
expectNil(t4 as? WritableKeyPath<TupleProperties, C<Int>>)
expectNil(t4 as? ReferenceWritableKeyPath<TupleProperties, C<Int>>)
let t5 = \TupleProperties.c.n.z
expectNotNil(t5 as? KeyPath<TupleProperties, String>)
expectNotNil(t5 as? WritableKeyPath<TupleProperties, String>)
expectNotNil(t5 as? ReferenceWritableKeyPath<TupleProperties, String>)
}
keyPath.test("tuple key path execution") {
typealias T0 = (Int, String)
typealias T1 = (x: Int, y: String)
let kp_t0_0 = \T0.0
let kp_t0_1 = \T0.1
let kp_t1_x = \T1.x
let kp_t1_y = \T1.y
let kp_t1_0 = \T1.0
let kp_t1_1 = \T1.1
var tuple0 = (1, "Hello")
let tuple1 = (x: 2, y: "World")
let tuple2 = (a: 3, b: "String")
// in some cases, tuple key paths are interchangeable
expectEqual(tuple0[keyPath: kp_t0_0], 1)
expectEqual(tuple0[keyPath: kp_t1_x], 1)
expectEqual(tuple0[keyPath: kp_t1_0], 1)
expectEqual(tuple0[keyPath: kp_t0_1], "Hello")
expectEqual(tuple0[keyPath: kp_t1_y], "Hello")
expectEqual(tuple0[keyPath: kp_t1_1], "Hello")
expectEqual(tuple1[keyPath: kp_t0_0], 2)
expectEqual(tuple1[keyPath: kp_t1_x], 2)
expectEqual(tuple1[keyPath: kp_t1_0], 2)
expectEqual(tuple1[keyPath: kp_t0_1], "World")
expectEqual(tuple1[keyPath: kp_t1_y], "World")
expectEqual(tuple1[keyPath: kp_t1_1], "World")
expectEqual(tuple2[keyPath: kp_t0_0], 3)
//expectEqual(tuple2[keyPath: kp_t1_x], 3)
//expectEqual(tuple2[keyPath: kp_t1_0], 3)
expectEqual(tuple2[keyPath: kp_t0_1], "String")
//expectEqual(tuple2[keyPath: kp_t1_y], "String")
//expectEqual(tuple2[keyPath: kp_t1_1], "String")
tuple0[keyPath: kp_t0_1] = "Another String"
expectEqual(tuple0[keyPath: kp_t0_1], "Another String")
}
keyPath.test("tuple key path execution (generic)") {
struct Container<T, U> {
let x: (T, U)
var y: (a: T, b: U)
}
func generic<A: Equatable, B: Equatable>(a: A, b: B) {
typealias T = (A, B)
let kp_t_0 = \T.0
let kp_t_1 = \T.1
let kp_c_x = \Container<A, B>.x
let kp_c_x_0 = kp_c_x.appending(path: kp_t_0)
let kp_c_x_1 = kp_c_x.appending(path: kp_t_1)
let kp_c_y_a = \Container<A, B>.y.a
let kp_c_y_b = \Container<A, B>.y.b
let tuple = (a, b)
let container = Container(x: (a, b), y: (a, b))
expectEqual(tuple[keyPath: kp_t_0], tuple.0)
expectEqual(tuple[keyPath: kp_t_1], tuple.1)
expectEqual(container[keyPath: kp_c_x_0], container.x.0)
expectEqual(container[keyPath: kp_c_x_1], container.x.1)
expectEqual(container[keyPath: kp_c_y_a], container.y.0)
expectEqual(container[keyPath: kp_c_y_b], container.y.1)
}
generic(a: 13, b: "Hello Tuples")
generic(a: "Tuples Hello", b: 31)
}
keyPath.test("let-ness") {
expectNil(\C<Int>.immutable as? ReferenceWritableKeyPath)
expectNotNil(\C<Int>.secretlyMutable as? ReferenceWritableKeyPath)
expectNil(\Point.hypotenuse as? WritableKeyPath)
expectNotNil(\Point.secretlyMutableHypotenuse as? WritableKeyPath)
}
keyPath.test("key path literal closures") {
// Property access
let fnX: (C<String>) -> Int = \C<String>.x
let fnY: (C<String>) -> LifetimeTracked? = \C<String>.y
let fnZ: (C<String>) -> String = \C<String>.z
let fnImmutable: (C<String>) -> String = \C<String>.immutable
let fnSecretlyMutable: (C<String>) -> String = \C<String>.secretlyMutable
let fnComputed: (C<String>) -> String = \C<String>.computed
let lifetime = LifetimeTracked(249)
let base = C(x: 1, y: lifetime, z: "SE-0249")
expectEqual(1, fnX(base))
expectEqual(lifetime, fnY(base))
expectEqual("SE-0249", fnZ(base))
expectEqual("1 Optional(249) SE-0249", fnImmutable(base))
expectEqual("1 Optional(249) SE-0249", fnSecretlyMutable(base))
expectEqual("SE-0249", fnComputed(base))
// Subscripts
var callsToComputeIndex = 0
func computeIndexWithSideEffect(_ i: Int) -> Int {
callsToComputeIndex += 1
return -i
}
let fnSubscriptResultA: (Subscripts<String>) -> SubscriptResult<String, Int>
= \Subscripts<String>.["A", computeIndexWithSideEffect(13)]
let fnSubscriptResultB: (Subscripts<String>) -> SubscriptResult<String, Int>
= \Subscripts<String>.["B", computeIndexWithSideEffect(42)]
let subscripts = Subscripts<String>()
expectEqual("A", fnSubscriptResultA(subscripts).left)
expectEqual(-13, fnSubscriptResultA(subscripts).right)
expectEqual("B", fnSubscriptResultB(subscripts).left)
expectEqual(-42, fnSubscriptResultB(subscripts).right)
// Did we compute the indices once per closure construction, or once per
// closure application?
expectEqual(2, callsToComputeIndex)
// rdar://problem/59445486
let variadicFn: (String...) -> Int = \.count
expectEqual(3, variadicFn("a", "b", "c"))
}
// SR-6096
protocol Protocol6096 {}
struct Value6096<ValueType> {}
extension Protocol6096 {
var asString: String? {
return self as? String
}
}
extension Value6096 where ValueType: Protocol6096 {
func doSomething() {
_ = \ValueType.asString?.endIndex
}
}
extension Int: Protocol6096 {}
keyPath.test("optional chaining component that needs generic instantiation") {
Value6096<Int>().doSomething()
}
// Nested generics.
protocol HasAssoc {
associatedtype A
}
struct Outer<T, U> {
struct Middle<V, W, X> {
}
}
extension Outer.Middle where V: HasAssoc, U == V.A, W == X {
struct Inner<Y: Hashable> {
func foo() -> AnyKeyPath {
return \[Y?: [U]].values
}
}
}
extension Double: HasAssoc {
typealias A = Float
}
keyPath.test("nested generics") {
let nested = Outer<Int, Float>.Middle<Double, String, String>.Inner<UInt>()
let nestedKeyPath = nested.foo()
typealias DictType = [UInt? : [Float]]
expectTrue(nestedKeyPath is KeyPath<DictType, DictType.Values>)
}
keyPath.test("tail allocated c array") {
let offset = MemoryLayout<foo>.offset(of: \foo.tailallocatedarray)!
expectEqual(4, offset)
}
runAllTests()
| apache-2.0 |
sschiau/swift | test/Sema/enum_raw_representable.swift | 2 | 6816 | // RUN: %target-typecheck-verify-swift
enum Foo : Int {
case a, b, c
}
var raw1: Int = Foo.a.rawValue
var raw2: Foo.RawValue = raw1
var cooked1: Foo? = Foo(rawValue: 0)
var cooked2: Foo? = Foo(rawValue: 22)
enum Bar : Double {
case a, b, c
}
func localEnum() -> Int {
enum LocalEnum : Int {
case a, b, c
}
return LocalEnum.a.rawValue
}
enum MembersReferenceRawType : Int {
case a, b, c
init?(rawValue: Int) {
self = MembersReferenceRawType(rawValue: rawValue)!
}
func successor() -> MembersReferenceRawType {
return MembersReferenceRawType(rawValue: rawValue + 1)!
}
}
func serialize<T : RawRepresentable>(_ values: [T]) -> [T.RawValue] {
return values.map { $0.rawValue }
}
func deserialize<T : RawRepresentable>(_ serialized: [T.RawValue]) -> [T] {
return serialized.map { T(rawValue: $0)! }
}
var ints: [Int] = serialize([Foo.a, .b, .c])
var doubles: [Double] = serialize([Bar.a, .b, .c])
var foos: [Foo] = deserialize([1, 2, 3])
var bars: [Bar] = deserialize([1.2, 3.4, 5.6])
// Infer RawValue from witnesses.
enum Color : Int {
case red
case blue
init?(rawValue: Double) {
return nil
}
var rawValue: Double {
return 1.0
}
}
var colorRaw: Color.RawValue = 7.5
// Mismatched case types
enum BadPlain : UInt { // expected-error {{'BadPlain' declares raw type 'UInt', but does not conform to RawRepresentable and conformance could not be synthesized}} expected-note {{do you want to add protocol stubs?}}
case a = "hello" // expected-error {{cannot convert value of type 'String' to raw type 'UInt'}}
}
// Recursive diagnostics issue in tryRawRepresentableFixIts()
class Outer {
// The setup is that we have to trigger the conformance check
// while diagnosing the conversion here. For the purposes of
// the test I'm putting everything inside a class in the right
// order, but the problem can trigger with a multi-file
// scenario too.
let a: Int = E.a // expected-error {{cannot convert value of type 'Outer.E' to specified type 'Int'}}
enum E : Array<Int> { // expected-error {{raw type 'Array<Int>' is not expressible by a string, integer, or floating-point literal}}
case a
}
}
// rdar://problem/32431736 - Conversion fix-it from String to String raw value enum can't look through optionals
func rdar32431736() {
enum E : String {
case A = "A"
case B = "B"
}
let items1: [String] = ["A", "a"]
let items2: [String]? = ["A"]
let myE1: E = items1.first
// expected-error@-1 {{cannot convert value of type 'String?' to specified type 'E'}}
// expected-note@-2 {{construct 'E' from unwrapped 'String' value}} {{17-17=E(rawValue: }} {{29-29=!)}}
let myE2: E = items2?.first
// expected-error@-1 {{cannot convert value of type 'String?' to specified type 'E'}}
// expected-note@-2 {{construct 'E' from unwrapped 'String' value}} {{17-17=E(rawValue: (}} {{30-30=)!)}}
}
// rdar://problem/32431165 - improve diagnostic for raw representable argument mismatch
enum E_32431165 : String {
case foo = "foo"
case bar = "bar" // expected-note {{'bar' declared here}}
}
func rdar32431165_1(_: E_32431165) {}
func rdar32431165_1(_: Int) {}
func rdar32431165_1(_: Int, _: E_32431165) {}
rdar32431165_1(E_32431165.baz)
// expected-error@-1 {{type 'E_32431165' has no member 'baz'; did you mean 'bar'?}}
rdar32431165_1(.baz)
// expected-error@-1 {{reference to member 'baz' cannot be resolved without a contextual type}}
rdar32431165_1("")
// expected-error@-1 {{cannot convert value of type 'String' to expected argument type 'E_32431165'}} {{16-16=E_32431165(rawValue: }} {{18-18=)}}
rdar32431165_1(42, "")
// expected-error@-1 {{cannot convert value of type 'String' to expected argument type 'E_32431165'}} {{20-20=E_32431165(rawValue: }} {{22-22=)}}
func rdar32431165_2(_: String) {}
func rdar32431165_2(_: Int) {}
func rdar32431165_2(_: Int, _: String) {}
rdar32431165_2(E_32431165.bar)
// expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String'}} {{16-16=}} {{30-30=.rawValue}}
rdar32431165_2(42, E_32431165.bar)
// expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String'}} {{20-20=}} {{34-34=.rawValue}}
E_32431165.bar == "bar"
// expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String}} {{1-1=}} {{15-15=.rawValue}}
"bar" == E_32431165.bar
// expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String}} {{10-10=}} {{24-24=.rawValue}}
func rdar32432253(_ condition: Bool = false) {
let choice: E_32431165 = condition ? .foo : .bar
let _ = choice == "bar"
// expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String'}} {{11-11=}} {{17-17=.rawValue}}
}
func sr8150_helper1(_: Int) {}
func sr8150_helper1(_: Double) {}
func sr8150_helper2(_: Double) {}
func sr8150_helper2(_: Int) {}
func sr8150_helper3(_: Foo) {}
func sr8150_helper3(_: Bar) {}
func sr8150_helper4(_: Bar) {}
func sr8150_helper4(_: Foo) {}
func sr8150(bar: Bar) {
sr8150_helper1(bar)
// expected-error@-1 {{cannot convert value of type 'Bar' to expected argument type 'Double'}} {{18-18=}} {{21-21=.rawValue}}
sr8150_helper2(bar)
// expected-error@-1 {{cannot convert value of type 'Bar' to expected argument type 'Double'}} {{18-18=}} {{21-21=.rawValue}}
sr8150_helper3(0.0)
// expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Bar'}} {{18-18=Bar(rawValue: }} {{21-21=)}}
sr8150_helper4(0.0)
// expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Bar'}} {{18-18=Bar(rawValue: }} {{21-21=)}}
}
class SR8150Box {
var bar: Bar
init(bar: Bar) { self.bar = bar }
}
// Bonus problem with mutable values being passed.
func sr8150_mutable(obj: SR8150Box) {
sr8150_helper1(obj.bar)
// expected-error@-1 {{cannot convert value of type 'Bar' to expected argument type 'Double'}} {{18-18=}} {{25-25=.rawValue}}
var bar = obj.bar
sr8150_helper1(bar)
// expected-error@-1 {{cannot convert value of type 'Bar' to expected argument type 'Double'}} {{18-18=}} {{21-21=.rawValue}}
}
struct NotEquatable { }
enum ArrayOfNewEquatable : Array<NotEquatable> { }
// expected-error@-1{{raw type 'Array<NotEquatable>' is not expressible by a string, integer, or floating-point literal}}
// expected-error@-2{{'ArrayOfNewEquatable' declares raw type 'Array<NotEquatable>', but does not conform to RawRepresentable and conformance could not be synthesized}}
// expected-error@-3{{RawRepresentable conformance cannot be synthesized because raw type 'Array<NotEquatable>' is not Equatable}}
// expected-note@-4{{do you want to add protocol stubs?}}
// expected-error@-5 {{an enum with no cases cannot declare a raw type}}
| apache-2.0 |
GrandCentralBoard/GrandCentralBoard | Pods/Operations/Sources/Features/Shared/Reachability.swift | 2 | 10679 | //
// Reachability.swift
// Operations
//
// Created by Daniel Thorpe on 24/07/2015.
// Copyright (c) 2015 Daniel Thorpe. All rights reserved.
//
import Foundation
import SystemConfiguration
// swiftlint:disable variable_name
public struct Reachability {
/// Errors which can be thrown or returned.
public enum Error: ErrorType {
case FailedToCreateDefaultRouteReachability
case FailedToSetNotifierCallback
case FailedToSetDispatchQueue
}
/// The kind of `Reachability` connectivity
public enum Connectivity {
case AnyConnectionKind, ViaWWAN, ViaWiFi
}
/// The `NetworkStatus`
public enum NetworkStatus {
case NotReachable
case Reachable(Connectivity)
}
/// The ObserverBlockType
public typealias ObserverBlockType = NetworkStatus -> Void
struct Observer {
let connectivity: Connectivity
let whenConnectedBlock: () -> Void
}
}
protocol NetworkReachabilityDelegate: class {
func reachabilityDidChange(flags: SCNetworkReachabilityFlags)
}
protocol NetworkReachabilityType {
weak var delegate: NetworkReachabilityDelegate? { get set }
func startNotifierOnQueue(queue: dispatch_queue_t) throws
func stopNotifier()
func reachabilityFlagsForHostname(host: String) -> SCNetworkReachabilityFlags?
}
protocol ReachabilityManagerType {
init(_ network: NetworkReachabilityType)
}
protocol SystemReachabilityType: ReachabilityManagerType {
func whenConnected(conn: Reachability.Connectivity, block: () -> Void)
}
protocol HostReachabilityType: ReachabilityManagerType {
func reachabilityForURL(url: NSURL, completion: Reachability.ObserverBlockType)
}
final class ReachabilityManager {
typealias Status = Reachability.NetworkStatus
static let sharedInstance = ReachabilityManager(DeviceReachability())
let queue = Queue.Utility.serial("me.danthorpe.Operations.Reachability")
var network: NetworkReachabilityType
var _observers = Protector(Array<Reachability.Observer>())
var observers: [Reachability.Observer] {
return _observers.read { $0 }
}
var numberOfObservers: Int {
return observers.count
}
required init(_ net: NetworkReachabilityType) {
network = net
network.delegate = self
}
}
extension ReachabilityManager: NetworkReachabilityDelegate {
func reachabilityDidChange(flags: SCNetworkReachabilityFlags) {
let status = Status(flags: flags)
let observersToCheck = _observers.read { $0 }
_observers.write { (inout mutableObservers: Array<Reachability.Observer>) in
mutableObservers = observersToCheck.filter { observer in
let shouldRemove = status.isConnected(observer.connectivity)
if shouldRemove {
dispatch_async(Queue.Main.queue, observer.whenConnectedBlock)
}
return !shouldRemove
}
}
if numberOfObservers == 0 {
network.stopNotifier()
}
}
}
extension ReachabilityManager: SystemReachabilityType {
// swiftlint:disable force_try
func whenConnected(conn: Reachability.Connectivity, block: () -> Void) {
_observers.write({ (inout mutableObservers: [Reachability.Observer]) in
mutableObservers.append(Reachability.Observer(connectivity: conn, whenConnectedBlock: block))
}, completion: { try! self.network.startNotifierOnQueue(self.queue) })
}
// swiftlint:enable force_try
}
extension ReachabilityManager: HostReachabilityType {
func reachabilityForURL(url: NSURL, completion: Reachability.ObserverBlockType) {
dispatch_async(queue) { [reachabilityFlagsForHostname = network.reachabilityFlagsForHostname] in
if let host = url.host, flags = reachabilityFlagsForHostname(host) {
completion(Status(flags: flags))
}
else {
completion(.NotReachable)
}
}
}
}
class DeviceReachability: NetworkReachabilityType {
typealias Error = Reachability.Error
var __defaultRouteReachability: SCNetworkReachability? = .None
var threadSafeProtector = Protector(false)
weak var delegate: NetworkReachabilityDelegate?
var notifierIsRunning: Bool {
get { return threadSafeProtector.read { $0 } }
set {
threadSafeProtector.write { (inout isRunning: Bool) in
isRunning = newValue
}
}
}
init() { }
func defaultRouteReachability() throws -> SCNetworkReachability {
if let reachability = __defaultRouteReachability { return reachability }
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let reachability = withUnsafePointer(&zeroAddress, {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}) else { throw Error.FailedToCreateDefaultRouteReachability }
__defaultRouteReachability = reachability
return reachability
}
func reachabilityForHost(host: String) -> SCNetworkReachability? {
return SCNetworkReachabilityCreateWithName(nil, (host as NSString).UTF8String)
}
func getFlagsForReachability(reachability: SCNetworkReachability) -> SCNetworkReachabilityFlags {
var flags = SCNetworkReachabilityFlags()
guard withUnsafeMutablePointer(&flags, {
SCNetworkReachabilityGetFlags(reachability, UnsafeMutablePointer($0))
}) else { return SCNetworkReachabilityFlags() }
return flags
}
func reachabilityDidChange(flags: SCNetworkReachabilityFlags) {
delegate?.reachabilityDidChange(flags)
}
func check(reachability: SCNetworkReachability, queue: dispatch_queue_t) {
dispatch_async(queue) { [weak self] in
if let delegate = self?.delegate, flags = self?.getFlagsForReachability(reachability) {
delegate.reachabilityDidChange(flags)
}
}
}
func startNotifierOnQueue(queue: dispatch_queue_t) throws {
assert(delegate != nil, "Reachability Delegate not set.")
let reachability = try defaultRouteReachability()
if !notifierIsRunning {
notifierIsRunning = true
var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
context.info = UnsafeMutablePointer(Unmanaged.passUnretained(self).toOpaque())
guard SCNetworkReachabilitySetCallback(reachability, __device_reachability_callback, &context) else {
stopNotifier()
throw Error.FailedToSetNotifierCallback
}
guard SCNetworkReachabilitySetDispatchQueue(reachability, queue) else {
stopNotifier()
throw Error.FailedToSetDispatchQueue
}
}
check(reachability, queue: queue)
}
func stopNotifier() {
if let reachability = try? defaultRouteReachability() {
SCNetworkReachabilityUnscheduleFromRunLoop(reachability, CFRunLoopGetCurrent(), kCFRunLoopCommonModes)
SCNetworkReachabilitySetCallback(reachability, nil, nil)
}
notifierIsRunning = false
}
func reachabilityFlagsForHostname(host: String) -> SCNetworkReachabilityFlags? {
guard let reachability = reachabilityForHost(host) else { return .None }
return getFlagsForReachability(reachability)
}
}
private func __device_reachability_callback(reachability: SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutablePointer<Void>) {
let handler = Unmanaged<DeviceReachability>.fromOpaque(COpaquePointer(info)).takeUnretainedValue()
dispatch_async(Queue.Default.queue) {
handler.delegate?.reachabilityDidChange(flags)
}
}
extension Reachability.NetworkStatus: Equatable { }
public func == (lhs: Reachability.NetworkStatus, rhs: Reachability.NetworkStatus) -> Bool {
switch (lhs, rhs) {
case (.NotReachable, .NotReachable):
return true
case let (.Reachable(aConnectivity), .Reachable(bConnectivity)):
return aConnectivity == bConnectivity
default:
return false
}
}
extension Reachability.NetworkStatus {
public init(flags: SCNetworkReachabilityFlags) {
if flags.isReachableViaWiFi {
self = .Reachable(.ViaWiFi)
}
else if flags.isReachableViaWWAN {
#if os(iOS)
self = .Reachable(.ViaWWAN)
#else
self = .Reachable(.AnyConnectionKind)
#endif
}
else {
self = .NotReachable
}
}
func isConnected(target: Reachability.Connectivity) -> Bool {
switch (self, target) {
case (.NotReachable, _):
return false
case (.Reachable(.ViaWWAN), .ViaWiFi):
return false
case (.Reachable(_), _):
return true
}
}
}
// MARK: - Conformance
extension SCNetworkReachabilityFlags {
var isReachable: Bool {
return contains(.Reachable)
}
var isConnectionRequired: Bool {
return contains(.ConnectionRequired)
}
var isInterventionRequired: Bool {
return contains(.InterventionRequired)
}
var isConnectionOnTraffic: Bool {
return contains(.ConnectionOnTraffic)
}
var isConnectionOnDemand: Bool {
return contains(.ConnectionOnDemand)
}
var isTransientConnection: Bool {
return contains(.TransientConnection)
}
var isLocalAddress: Bool {
return contains(.IsLocalAddress)
}
var isDirect: Bool {
return contains(.IsDirect)
}
var isConnectionOnTrafficOrDemand: Bool {
return isConnectionOnTraffic || isConnectionOnDemand
}
var isConnectionRequiredOrTransient: Bool {
return isConnectionRequired || isTransientConnection
}
var isConnected: Bool {
return isReachable && !isConnectionRequired
}
var isOnWWAN: Bool {
#if os(iOS)
return contains(.IsWWAN)
#else
return false
#endif
}
var isReachableViaWWAN: Bool {
#if os(iOS)
return isConnected && isOnWWAN
#else
return isReachable
#endif
}
var isReachableViaWiFi: Bool {
#if os(iOS)
return isConnected && !isOnWWAN
#else
return isConnected
#endif
}
}
// swiftlint:enable variable_name
| gpl-3.0 |
sggtgb/Sea-Cow | seaCow/ReadingList.swift | 1 | 1925 | //
// ReadingList.swift
// seaCow
//
// Created by Scott Gavin on 5/7/15.
// Copyright (c) 2015 Scott G Gavin. All rights reserved.
//
import UIKit
import Foundation
class ReadingList: NSObject , NSCoding {
var articles: [ArticleData]! = []
override init() {
println("Initalizing Reading List")
}
func addArticle(article: ArticleData) {
println("Adding article")
articles.append(article)
}
func removeArticle(index: Int) {
println("Removing article")
articles.removeAtIndex(index)
}
func getArticles() -> [ArticleData] {
println("Returning list")
return articles!
}
// MARK: NSCoding
func encodeWithCoder(coder: NSCoder) {
println("trying to encode articles, value: ")
println(articles)
coder.encodeObject(articles, forKey: "article")
}
required init(coder aDecoder: NSCoder) {
var temp: AnyObject? = aDecoder.decodeObjectForKey("article")
println("trying to load reading list in init...")
if (temp != nil) {
println("reading list loaded")
//test = (temp as! ReadingList).test
articles = temp as! [ArticleData]
} else {
println("failed")
}
}
func save() {
println("trying to save")
let data = NSKeyedArchiver.archivedDataWithRootObject(self)
println("data created, trying to write")
NSUserDefaults.standardUserDefaults().setObject(data, forKey: "readingList")
println("success")
}
func load() -> Bool {
if let data = NSUserDefaults.standardUserDefaults().objectForKey("readingList") as? NSData {
let temp = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! ReadingList
articles = temp.articles
return true
}
return false
}
}
| mpl-2.0 |
huonw/swift | validation-test/compiler_crashers_fixed/00875-getselftypeforcontainer.swift | 65 | 874 | // 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
// RUN: not %target-swift-frontend %s -typecheck
protocol c {
class A {
if true {
func f: NSObject {
enum A {
}
if c = c(v: NSObject {
}
f = b: e == T) {
func compose<T: C {
}
typealias e = c() -> V {
func a(f: A: A {
}
var d where T>) -> {
let d<T : P {
}
let c: P {
}
protocol c = e, V>: Array) {
}
self] {
print() -> {
}
protocol P {
}
}
var b = {
protocol P {
}
}
enum S<T) {
return g<T>: A() {
}
deinit {
}
}
}
}
}
}
extension NSSet {
}
}
}
var e: e!.e == c: String = compose(false)
protocol P {
}
typealias e : e == ni
| apache-2.0 |
EgzonArifi/Daliy-Gifs | Daily Gifs/Constants.swift | 1 | 310 | //
// Constants.swift
// Daily Gifs
//
// Created by EgzonArifi on 3/5/17.
// Copyright © 2017 Overjump. All rights reserved.
//
import Foundation
let HOME_URL = "https://api.giphy.com/v1/gifs/trending?api_key=dc6zaTOxFJmzC"
let SEARCH_URL = "https://api.giphy.com/v1/gifs/search?api_key=dc6zaTOxFJmzC"
| mit |
vector-im/riot-ios | Riot/Modules/KeyBackup/Recover/Passphrase/KeyBackupRecoverFromPassphraseViewController.swift | 2 | 9609 | /*
Copyright 2019 New Vector Ltd
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
final class KeyBackupRecoverFromPassphraseViewController: UIViewController {
// MARK: - Properties
// MARK: Outlets
@IBOutlet private weak var scrollView: UIScrollView!
@IBOutlet private weak var shieldImageView: UIImageView!
@IBOutlet private weak var informationLabel: UILabel!
@IBOutlet private weak var passphraseTitleLabel: UILabel!
@IBOutlet private weak var passphraseTextField: UITextField!
@IBOutlet private weak var passphraseTextFieldBackgroundView: UIView!
@IBOutlet private weak var passphraseVisibilityButton: UIButton!
@IBOutlet private weak var unknownPassphraseButton: UIButton!
@IBOutlet private weak var recoverButtonBackgroundView: UIView!
@IBOutlet private weak var recoverButton: UIButton!
// MARK: Private
private var viewModel: KeyBackupRecoverFromPassphraseViewModelType!
private var keyboardAvoider: KeyboardAvoider?
private var theme: Theme!
private var errorPresenter: MXKErrorPresentation!
private var activityPresenter: ActivityIndicatorPresenter!
// MARK: Public
// MARK: - Setup
class func instantiate(with viewModel: KeyBackupRecoverFromPassphraseViewModelType) -> KeyBackupRecoverFromPassphraseViewController {
let viewController = StoryboardScene.KeyBackupRecoverFromPassphraseViewController.initialScene.instantiate()
viewController.viewModel = viewModel
viewController.theme = ThemeService.shared().theme
return viewController
}
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = VectorL10n.keyBackupRecoverTitle
self.vc_removeBackTitle()
self.setupViews()
self.keyboardAvoider = KeyboardAvoider(scrollViewContainerView: self.view, scrollView: self.scrollView)
self.activityPresenter = ActivityIndicatorPresenter()
self.errorPresenter = MXKErrorAlertPresentation()
self.registerThemeServiceDidChangeThemeNotification()
self.update(theme: self.theme)
self.viewModel.viewDelegate = self
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return self.theme.statusBarStyle
}
// MARK: - Private
private func setupViews() {
let cancelBarButtonItem = MXKBarButtonItem(title: VectorL10n.cancel, style: .plain) { [weak self] in
self?.viewModel.process(viewAction: .cancel)
}
self.navigationItem.rightBarButtonItem = cancelBarButtonItem
self.scrollView.keyboardDismissMode = .interactive
let shieldImage = Asset.Images.keyBackupLogo.image.withRenderingMode(.alwaysTemplate)
self.shieldImageView.image = shieldImage
let visibilityImage = Asset.Images.revealPasswordButton.image.withRenderingMode(.alwaysTemplate)
self.passphraseVisibilityButton.setImage(visibilityImage, for: .normal)
self.informationLabel.text = VectorL10n.keyBackupRecoverFromPassphraseInfo
self.passphraseTitleLabel.text = VectorL10n.keyBackupRecoverFromPassphrasePassphraseTitle
self.passphraseTextField.addTarget(self, action: #selector(passphraseTextFieldDidChange(_:)), for: .editingChanged)
self.unknownPassphraseButton.vc_enableMultiLinesTitle()
self.recoverButton.vc_enableMultiLinesTitle()
self.recoverButton.setTitle(VectorL10n.keyBackupRecoverFromPassphraseRecoverAction, for: .normal)
self.updateRecoverButton()
}
private func update(theme: Theme) {
self.theme = theme
self.view.backgroundColor = theme.headerBackgroundColor
if let navigationBar = self.navigationController?.navigationBar {
theme.applyStyle(onNavigationBar: navigationBar)
}
self.informationLabel.textColor = theme.textPrimaryColor
self.shieldImageView.tintColor = theme.textPrimaryColor
self.passphraseTextFieldBackgroundView.backgroundColor = theme.backgroundColor
self.passphraseTitleLabel.textColor = theme.textPrimaryColor
theme.applyStyle(onTextField: self.passphraseTextField)
self.passphraseTextField.attributedPlaceholder = NSAttributedString(string: VectorL10n.keyBackupRecoverFromPassphrasePassphrasePlaceholder,
attributes: [.foregroundColor: theme.placeholderTextColor])
self.theme.applyStyle(onButton: self.passphraseVisibilityButton)
self.recoverButtonBackgroundView.backgroundColor = theme.backgroundColor
theme.applyStyle(onButton: self.recoverButton)
let unknownRecoveryKeyAttributedString = NSMutableAttributedString(string: VectorL10n.keyBackupRecoverFromPassphraseLostPassphraseActionPart1, attributes: [.foregroundColor: self.theme.textPrimaryColor])
let unknownRecoveryKeyAttributedStringPart2 = NSAttributedString(string: VectorL10n.keyBackupRecoverFromPassphraseLostPassphraseActionPart2, attributes: [.foregroundColor: self.theme.tintColor])
let unknownRecoveryKeyAttributedStringPart3 = NSAttributedString(string: VectorL10n.keyBackupRecoverFromPassphraseLostPassphraseActionPart3, attributes: [.foregroundColor: self.theme.textPrimaryColor])
unknownRecoveryKeyAttributedString.append(unknownRecoveryKeyAttributedStringPart2)
unknownRecoveryKeyAttributedString.append(unknownRecoveryKeyAttributedStringPart3)
self.unknownPassphraseButton.setAttributedTitle(unknownRecoveryKeyAttributedString, for: .normal)
}
private func registerThemeServiceDidChangeThemeNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeServiceDidChangeTheme, object: nil)
}
@objc private func themeDidChange() {
self.update(theme: ThemeService.shared().theme)
}
private func updateRecoverButton() {
self.recoverButton.isEnabled = self.viewModel.isFormValid
}
private func render(viewState: KeyBackupRecoverFromPassphraseViewState) {
switch viewState {
case .loading:
self.renderLoading()
case .loaded:
self.renderLoaded()
case .error(let error):
self.render(error: error)
}
}
private func renderLoading() {
self.view.endEditing(true)
self.activityPresenter.presentActivityIndicator(on: self.view, animated: true)
}
private func renderLoaded() {
self.activityPresenter.removeCurrentActivityIndicator(animated: true)
}
private func render(error: Error) {
self.activityPresenter.removeCurrentActivityIndicator(animated: true)
if (error as NSError).domain == MXKeyBackupErrorDomain
&& (error as NSError).code == Int(MXKeyBackupErrorInvalidRecoveryKeyCode.rawValue) {
self.errorPresenter.presentError(from: self,
title: VectorL10n.keyBackupRecoverInvalidPassphraseTitle,
message: VectorL10n.keyBackupRecoverInvalidPassphrase,
animated: true,
handler: nil)
} else {
self.errorPresenter.presentError(from: self, forError: error, animated: true, handler: nil)
}
}
// MARK: - Actions
@IBAction private func passphraseVisibilityButtonAction(_ sender: Any) {
self.passphraseTextField.isSecureTextEntry = !self.passphraseTextField.isSecureTextEntry
}
@objc private func passphraseTextFieldDidChange(_ textField: UITextField) {
self.viewModel.passphrase = textField.text
self.updateRecoverButton()
}
@IBAction private func recoverButtonAction(_ sender: Any) {
self.viewModel.process(viewAction: .recover)
}
@IBAction private func unknownPassphraseButtonAction(_ sender: Any) {
self.viewModel.process(viewAction: .unknownPassphrase)
}
}
// MARK: - UITextFieldDelegate
extension KeyBackupRecoverFromPassphraseViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
// MARK: - KeyBackupRecoverFromPassphraseViewModelViewDelegate
extension KeyBackupRecoverFromPassphraseViewController: KeyBackupRecoverFromPassphraseViewModelViewDelegate {
func keyBackupRecoverFromPassphraseViewModel(_ viewModel: KeyBackupRecoverFromPassphraseViewModelType, didUpdateViewState viewSate: KeyBackupRecoverFromPassphraseViewState) {
self.render(viewState: viewSate)
}
}
| apache-2.0 |
MaximeLM/superlachaise-ios | SuperLachaise/UI/Gallery/GalleryViewController.swift | 1 | 174 | //
// GalleryViewController.swift
// SuperLachaise
//
// Created by Maxime Le Moine on 10/06/2017.
//
//
import UIKit
class GalleryViewController: UIViewController {
}
| mit |
eofster/Telephone | ReceiptValidation/DeviceGUID.swift | 1 | 1901 | //
// DeviceGUID.swift
// Telephone
//
// Copyright © 2008-2016 Alexey Kuznetsov
// Copyright © 2016-2021 64 Characters
//
// Telephone is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Telephone is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import Foundation
import IOKit
struct DeviceGUID {
let dataValue: Data
init() {
dataValue = makeGUID()
}
}
private func makeGUID() -> Data {
let iterator = makeIterator()
guard iterator != 0 else { return Data() }
var mac = Data()
var service = IOIteratorNext(iterator)
while service != 0 {
var parent: io_object_t = 0
let status = IORegistryEntryGetParentEntry(service, kIOServicePlane, &parent)
if status == KERN_SUCCESS {
mac = (IORegistryEntryCreateCFProperty(parent, "IOMACAddress" as CFString, kCFAllocatorDefault, 0).takeRetainedValue() as! CFData) as Data
IOObjectRelease(parent)
}
IOObjectRelease(service)
service = IOIteratorNext(iterator)
}
IOObjectRelease(iterator)
return mac
}
private func makeIterator() -> io_iterator_t {
var port: mach_port_t = 0
var status = IOMasterPort(mach_port_t(MACH_PORT_NULL), &port)
guard status == KERN_SUCCESS else { return 0 }
guard let match = IOBSDNameMatching(port, 0, "en0") else { return 0 }
var iterator: io_iterator_t = 0
status = IOServiceGetMatchingServices(port, match, &iterator)
guard status == KERN_SUCCESS else { return 0 }
return iterator
}
| gpl-3.0 |
simonnarang/Fandom | Desktop/Fandom-IOS-master/Fandomm/ShareToFandomTableViewController.swift | 1 | 8471 | //
// ShareToFandomTableViewController.swift
// Fandomm
//
// Created by Simon Narang on 1/9/16.
// Copyright © 2016 Simon Narang. All rights reserved.
//
import UIKit
class ShareToFandomTableViewController: UITableViewController {
@IBOutlet weak var labell: UILabel!
var counter = Int()
let redisClient:RedisClient = RedisClient(host:"localhost", port:6379, loggingBlock:{(redisClient:AnyObject, message:String, severity:RedisLogSeverity) in
var debugString:String = message
debugString = debugString.stringByReplacingOccurrencesOfString("\r", withString: "\\r")
debugString = debugString.stringByReplacingOccurrencesOfString("\n", withString: "\\n")
print("Log (\(severity.rawValue)): \(debugString)")
})
var usernameThreeTextOne = String()
var shareImage: UIImage? = nil
var shareLinky: String? = nil
var fandomsArray: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
let linkShareActionSheetMenu = UIAlertController(title: nil, message: "which fandoms do you want to share this with?", preferredStyle: .ActionSheet)
let backAction = UIAlertAction(title: "back", style: .Cancel, handler: {
(alert: UIAlertAction!) -> Void in
print("Cancelled Link Share")
})
linkShareActionSheetMenu.addAction(backAction)
presentViewController(linkShareActionSheetMenu, animated: true) { () -> Void in
self.redisClient.lRange("\(self.usernameThreeTextOne)fandoms", start: 0, stop: 999999, completionHandler: { (array, error) -> Void in
if error != nil {
} else{
for fandom in array {
print(fandom)
self.counter += 1
let bla = UIAlertAction(title: fandom as? String, style: .Default, handler: {
(alert: UIAlertAction!) -> Void in
print("bla")
if self.shareLinky != nil && self.shareImage == nil {
self.redisClient.lPush(fandom as! String, values: [self.shareLinky! as String], completionHandler: { (int, error) -> Void in
if error != nil {
}else{
self.performSegueWithIdentifier("doneSharing", sender: nil)
}
})
}else if self.shareLinky == nil && self.shareImage != nil {
}
})
linkShareActionSheetMenu.addAction(bla)
}
}
})
self.counter = 0
}
counter = 0
let networkErrorAlertOne = UIAlertController(title: "Network troubles...", message: "Sorry about that... Perhaps check the app store to see if you need to update fandom... If not I'm already working on a fix so try again soon", preferredStyle: .Alert)
let networkErrorAlertOneOkButton = UIAlertAction(title: "☹️okay☹️", style: .Default) { (action) in
}
networkErrorAlertOne.addAction(networkErrorAlertOneOkButton)
let noFandomsErrorAlertOne = UIAlertController(title: "Youre not in any Fandoms!", message: "id recomend searching gor what your interested in and joining it!", preferredStyle: .Alert)
let noFandomsErrorAlertOneOkButton = UIAlertAction(title: "okay", style: .Default) { (action) in
}
let noFandomsErrorAlertOneOkButton2 = UIAlertAction(title: "search", style: .Default) { (action) in
self.performSegueWithIdentifier("segueSeven", sender: nil)
}
noFandomsErrorAlertOne.addAction(noFandomsErrorAlertOneOkButton)
noFandomsErrorAlertOne.addAction(noFandomsErrorAlertOneOkButton2)
/* redisClient.lRange("\(self.usernameThreeTextOne)fandoms", start: 0, stop: 99999999) { (array, error) -> Void in
if error != nil {
print(error)
self.presentViewController(networkErrorAlertOne, animated: true) {}
}else if array == nil {
print("you have no friends because you have no fandoms")
self.presentViewController(noFandomsErrorAlertOne, animated: true) {}
}else if error == nil{
print("jubs")
print("\(self.usernameThreeTextOne)'s fandoms is/are \(array)")
for fandom in array {
print(fandom)
self.counter += 1
self.fandomsArray.append(fandom as! String)
print("counter = \(self.counter)")
print("hi")
}
print("array of fandoms is \(self.fandomsArray)")
}else{
}
}*/
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return counter
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
/*let cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("cell")
//let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
let(fandomconstant) = fandomsArray[indexPath.row]
cell!.textLabel?.text = fandomconstant
print(fandomconstant)
if cell == nil {
print("wow")
print("bad")
}else{
print("life")
}
return cell!*/
let cell = UITableViewCell()
let label = UILabel(frame: CGRect(x:0, y:0, width:200, height:50))
label.text = "Hello Man"
cell.addSubview(label)
return cell
}
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return false
}
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| unlicense |
rayho/CodePathTwitter | CodePathTwitter/DetailController.swift | 1 | 7136 | //
// DetailController.swift
// CodePathTwitter
//
// Created by Ray Ho on 9/29/14.
// Copyright (c) 2014 Prime Rib Software. All rights reserved.
//
import UIKit
class DetailController: UIViewController, TweetActionButtonsDelegate {
var tweet: Tweet!
var avatarView: UIImageView!
var tweetTextView: UILabel!
var realNameView: UILabel!
var screenNameView: UILabel!
var timeView: UILabel!
var numRetweetView: UILabel!
var numRetweetLabel: UILabel!
var numFavoriteView: UILabel!
var numFavoriteLabel: UILabel!
var tweetActions: TweetActionButtons!
// Convenience method to launch this view controller
class func launch(fromNavController: UINavigationController, tweet: Tweet) {
var toViewController: DetailController = DetailController()
toViewController.tweet = tweet
var toNavController: UINavigationController = UINavigationController(rootViewController: toViewController)
fromNavController.pushViewController(toViewController, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Tweet"
// Initialize views
self.view.backgroundColor = UIColor.whiteColor()
avatarView = UIImageView()
avatarView.setTranslatesAutoresizingMaskIntoConstraints(false)
realNameView = UILabel()
realNameView.setTranslatesAutoresizingMaskIntoConstraints(false)
realNameView.numberOfLines = 1
screenNameView = UILabel()
screenNameView.setTranslatesAutoresizingMaskIntoConstraints(false)
screenNameView.numberOfLines = 1
timeView = UILabel()
timeView.setTranslatesAutoresizingMaskIntoConstraints(false)
timeView.numberOfLines = 1
tweetTextView = UILabel()
tweetTextView.setTranslatesAutoresizingMaskIntoConstraints(false)
tweetTextView.numberOfLines = 0
numRetweetView = UILabel()
numRetweetView.setTranslatesAutoresizingMaskIntoConstraints(false)
numRetweetView.numberOfLines = 1
numRetweetLabel = UILabel()
numRetweetLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
numRetweetLabel.numberOfLines = 1
numFavoriteView = UILabel()
numFavoriteView.setTranslatesAutoresizingMaskIntoConstraints(false)
numFavoriteView.numberOfLines = 1
numFavoriteLabel = UILabel()
numFavoriteLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
numFavoriteLabel.numberOfLines = 1
tweetActions = NSBundle.mainBundle().loadNibNamed("TweetActionButtons", owner: self, options: nil)[0] as TweetActionButtons
tweetActions.setTranslatesAutoresizingMaskIntoConstraints(false)
tweetActions.delegate = self
let viewDictionary: Dictionary = ["tweetTextView": tweetTextView, "avatarView": avatarView, "realNameView": realNameView, "screenNameView": screenNameView, "timeView": timeView, "numRetweetView": numRetweetView, "numRetweetLabel": numRetweetLabel, "numFavoriteView": numFavoriteView, "numFavoriteLabel": numFavoriteLabel, "tweetActions": tweetActions]
self.view.addSubview(avatarView)
self.view.addSubview(realNameView)
self.view.addSubview(screenNameView)
self.view.addSubview(timeView)
self.view.addSubview(tweetTextView)
self.view.addSubview(numRetweetView)
self.view.addSubview(numRetweetLabel)
self.view.addSubview(numFavoriteView)
self.view.addSubview(numFavoriteLabel)
self.view.addSubview(tweetActions)
self.view.layoutIfNeeded()
self.view.addConstraint(NSLayoutConstraint(item: avatarView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.topLayoutGuide, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 8))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-8-[avatarView(48)]-[realNameView]-(>=8)-|", options: NSLayoutFormatOptions.AlignAllTop, metrics: nil, views: viewDictionary))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[tweetTextView]-8-|", options: NSLayoutFormatOptions.allZeros, metrics: nil, views: viewDictionary))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[numRetweetView]-4-[numRetweetLabel]-[numFavoriteView]-4-[numFavoriteLabel]-(>=8)-|", options: NSLayoutFormatOptions.AlignAllBaseline, metrics: nil, views: viewDictionary))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[avatarView(48)]-[tweetTextView]-[timeView]-[numRetweetView]-[tweetActions]", options: NSLayoutFormatOptions.AlignAllLeft, metrics: nil, views: viewDictionary))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[realNameView]-0-[screenNameView]-(>=8)-|", options: NSLayoutFormatOptions.AlignAllLeft, metrics: nil, views: viewDictionary))
}
func clicked(sender: AnyObject) {
NSLog("clicked")
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
updateUI()
}
func updateUI() {
avatarView.image = nil
let avatarUrl: NSString? = tweet.user.avatarUrl
if (avatarUrl != nil) {
avatarView.setImageWithURL(NSURL.URLWithString(avatarUrl!))
}
// Names, tweet text
let realName: NSString? = tweet.user.realName
realNameView.text = realName != nil ? realName! : ""
screenNameView.text = "@\(tweet.user.screenName)"
tweetTextView.text = tweet.text
// Time
var dateFormatter: NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "M/d/yy, h:mm a"
timeView.text = dateFormatter.stringFromDate(tweet.timestamp)
// Retweets and favorites
numRetweetView.text = "\(tweet.numRetweets)"
numRetweetLabel.text = (tweet.numRetweets == 0 || tweet.numRetweets > 1) ? "RETWEETS" : "RETWEET"
numFavoriteView.text = "\(tweet.numFavorites)"
numFavoriteLabel.text = (tweet.numFavorites == 0 || tweet.numFavorites > 1) ? "FAVORITES" : "FAVORITE"
// Action buttons
tweetActions.updateUI(tweet)
}
func tweetActionReply(sender: TweetActionButtons) {
NSLog("Launching reply controller ...")
ComposeController.launch(self, inReplyToTweet: tweet)
}
func tweetActionRetweet(sender: TweetActionButtons) {
if (tweet.didRetweet) {
NSLog("Already retweeted. Ignoring request.")
} else {
NSLog("Retweeting ...")
tweet.didRetweet = true
TWTR.postRetweet(tweet.id)
}
tweetActions.updateUI(tweet)
}
func tweetActionFavorite(sender: TweetActionButtons) {
if (tweet.didFavorite) {
NSLog("Favoriting ...")
tweet.didFavorite = false
TWTR.removeFavorite(tweet.id)
} else {
NSLog("Un-favoriting ...")
tweet.didFavorite = true
TWTR.postFavorite(tweet.id)
}
tweetActions.updateUI(tweet)
}
}
| mit |
mattiasjahnke/arduino-projects | matrix-painter/iOS/PixelDrawer/Carthage/Checkouts/flow/Flow/Delegate.swift | 1 | 1951 | //
// Delegate.swift
// Flow
//
// Created by Måns Bernhardt on 2017-01-16.
// Copyright © 2017 iZettle. All rights reserved.
//
import Foundation
/// Helper to manage the life time of a delegate `(Arg) -> Ret`.
public final class Delegate<Arg, Ret> {
private var callbackAndDisposable: (callback: (Arg) -> Ret, disposable: Disposable)? = nil
private let onSet: (@escaping (Arg) -> Ret) -> Disposable
/// Creates a new instance.
/// - Parameter onSet: When `set()` is called with a new callback, `onSet` will be called with the same callback
/// and the `Disposable` returned from `onSet` will be hold on to and not disposed until the callback is unset.
public init(onSet: @escaping (@escaping (Arg) -> Ret) -> Disposable = { _ in NilDisposer() }) {
self.onSet = onSet
}
/// Sets the callback to be called when calling `call()` on `self`.
/// - Returns: A disposable that will unset the callback once being disposed.
/// - Note: If a callback was already set, it will be unset before the new callback is set.
public func set(_ callback: @escaping (Arg) -> Ret) -> Disposable {
callbackAndDisposable?.disposable.dispose()
let bag = DisposeBag()
bag += onSet(callback)
bag += { self.callbackAndDisposable = nil }
callbackAndDisposable = (callback, bag)
return bag
}
/// Is a callback currently set?
public var isSet: Bool {
return callbackAndDisposable != nil
}
/// Call any currently set callback with `arg` and return the result, or return nil if no callback is set.
public func call(_ arg: Arg) -> Ret? {
return callbackAndDisposable?.callback(arg)
}
}
extension Delegate where Arg == () {
/// Call any currently set callback and return the result, or return nil if no callback is set.
public func call() -> Ret? {
return call(())
}
}
| mit |
cactis/SwiftEasyKit | Source/Classes/Scrollable2ViewController.swift | 1 | 2443 | //
// Scrollable2ViewController.swift
import UIKit
open class Scrollable2ViewController: DefaultViewController {
public var contentView = UIScrollView()
override open func viewDidLoad() {
super.viewDidLoad()
}
override open func layoutUI() {
super.layoutUI()
contentView = view.addScrollView()
view.layout([contentView])
}
override open func bindUI() {
super.bindUI()
// registerKeyboardNotifications()
}
override open func updateViewConstraints() {
super.updateViewConstraints()
contentView.fillSuperview()
}
//
// override func viewWillDisappear(animated: Bool) {
// super.viewWillDisappear(animated)
// unregisterKeyboardNotifications()
// }
//
override open func keyboardDidShow(_ notification: NSNotification) {
super.keyboardDidShow(notification)
// let userInfo: NSDictionary = notification.userInfo!
// let
// keyboardSize = userInfo.objectForKey(UIKeyboardFrameBeginUserInfoKey)!.CGRectValue.size
let contentInsets = UIEdgeInsetsMake(0, 0, keyboardSize.height, 0)
contentView.contentInset = contentInsets
contentView.scrollIndicatorInsets = contentInsets
}
override open func keyboardWillHide(_ notification: NSNotification) {
super.keyboardWillHide(notification)
contentView.contentInset = .zero
contentView.scrollIndicatorInsets = .zero
}
func textViewDidBeginEditing(textView: UITextView) {
makeTargetVisible(textView.superview!)
}
private func makeTargetVisible(_ target: UIView) {
// var viewRect = view.frame
// viewRect.size.height -= keyboardSize.height
// let y = target.frame.origin.y
var y: CGFloat = 0
if target.bottomEdge() > 200 { y = target.bottomEdge() - 100 }
let scrollPoint = CGPoint(x: 0, y: y)
contentView.setContentOffset(scrollPoint, animated: true)
}
func textFieldDidBeginEditing(textField: UITextField) {
makeTargetVisible(textField.superview!)
}
//
//
// func registerKeyboardNotifications() {
// NSNotificationCenter.default().addObserver(self, selector: "keyboardDidShow:", name: UIKeyboardDidShowNotification, object: nil)
// NSNotificationCenter.default().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
// }
//
// func unregisterKeyboardNotifications() {
// NSNotificationCenter.default().removeObserver(self)
// }
}
| mit |
chatappcodepath/ChatAppSwift | LZChat/SignInViewController.swift | 1 | 3116 | //
//
// License
// Copyright (c) 2017 chatappcodepath
// Released under an MIT license: http://opensource.org/licenses/MIT
//
import UIKit
import Firebase
@objc(SignInViewController)
class SignInViewController: UIViewController, GIDSignInUIDelegate {
@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var googleSigninButton: GIDSignInButton!
override func viewDidAppear(_ animated: Bool) {
if let user = FIRAuth.auth()?.currentUser {
self.signedIn(user)
}
}
override func viewDidLoad() {
GIDSignIn.sharedInstance().uiDelegate = self
}
@IBAction func didTapSignIn(_ sender: AnyObject) {
// Sign In with credentials.
guard let email = emailField.text, let password = passwordField.text else { return }
FIRAuth.auth()?.signIn(withEmail: email, password: password) { (user, error) in
if let error = error {
print(error.localizedDescription)
return
}
self.signedIn(user!)
}
}
@IBAction func didTapSignUp(_ sender: AnyObject) {
guard let email = emailField.text, let password = passwordField.text else { return }
FIRAuth.auth()?.createUser(withEmail: email, password: password) { (user, error) in
if let error = error {
print(error.localizedDescription)
return
}
self.setDisplayName(user!)
}
}
func setDisplayName(_ user: FIRUser?) {
guard let user = user else {
return;
}
let changeRequest = user.profileChangeRequest()
changeRequest.displayName = user.email!.components(separatedBy: "@")[0]
changeRequest.commitChanges(){ (error) in
if let error = error {
print(error.localizedDescription)
return
}
self.signedIn(FIRAuth.auth()?.currentUser)
}
}
@IBAction func didRequestPasswordReset(_ sender: AnyObject) {
let prompt = UIAlertController.init(title: nil, message: "Email:", preferredStyle: .alert)
let okAction = UIAlertAction.init(title: "OK", style: .default) { (action) in
let userInput = prompt.textFields![0].text
if (userInput!.isEmpty) {
return
}
FIRAuth.auth()?.sendPasswordReset(withEmail: userInput!) { (error) in
if let error = error {
print(error.localizedDescription)
return
}
}
}
prompt.addTextField(configurationHandler: nil)
prompt.addAction(okAction)
present(prompt, animated: true, completion: nil);
}
public func signedIn(_ user: FIRUser?) {
MeasurementHelper.sendLoginEvent()
AppState.sharedInstance.displayName = user?.displayName ?? user?.email
AppState.sharedInstance.photoURL = user?.photoURL
AppState.sharedInstance.signedIn = true
let notificationName = Notification.Name(rawValue: Constants.NotificationKeys.SignedIn)
NotificationCenter.default.post(name: notificationName, object: nil, userInfo: nil)
performSegue(withIdentifier: Constants.Segues.SignInToFp, sender: nil)
}
}
| mit |
blisslog/UI-Imitation-DailyBeast | NEWS/ArticleCell.swift | 1 | 926 | //
// NewsCell.swift
// NEWS
//
// Created by BlissLog on 2016. 1. 6..
// Copyright © 2016년 BlissLog. All rights reserved.
//
import UIKit
import MGSwipeTableCell
class ArticleCell: MGSwipeTableCell, BGImageFlowProtocol {
@IBOutlet weak var title: UILabel!
@IBOutlet weak var desc: UILabel!
@IBOutlet weak var bgImage: UIImageView!
@IBOutlet weak var viewFrame: UIView!
@IBOutlet weak var checkReaded: UIImageView!
@IBOutlet weak var readingProgress: UIProgressView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func flowCell(moveY value: CGFloat) {
self.bgImage.transform = CGAffineTransform(translationX: 0.0, y: value)
}
}
| mit |
KarlWarfel/nutshell-ios | Nutshell/Resources/NutshellUIView.swift | 1 | 1276 | /*
* Copyright (c) 2015, Tidepool Project
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the associated License, which is identical to the BSD 2-Clause
* License as published by the Open Source Initiative at opensource.org.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the License for more details.
*
* You should have received a copy of the License along with this program; if
* not, you can obtain one from Tidepool Project at tidepool.org.
*/
import Foundation
import UIKit
// This would be more useful if there was support for enums; right now this uses known string value to communicate the usage from the storyboard to this class, which sets the background color of the UIView based on this usage and the Styles color variables.
@IBDesignable class NutshellUIView: UIView {
@IBInspectable var usage: String = "" {
didSet {
updateBackgroundColor()
}
}
private func updateBackgroundColor() {
if let backColor = Styles.usageToBackgroundColor[usage] {
self.backgroundColor = backColor
}
}
}
| bsd-2-clause |
Suzhccc/DrawEffectWithSwift | 抽屉效果WithSwitf/抽屉效果WithSwitf/SSExtension.swift | 1 | 306 | //
// SSExtension.swift
// 抽屉效果WithSwitf
//
// Created by Suzh on 16/1/27.
// Copyright © 2016年 Suzh. All rights reserved.
//
import Foundation
import UIKit
class SSExtension {
//获取bounds
func getMainScreenBouns() -> CGRect {
return UIScreen.mainScreen().bounds
}
} | apache-2.0 |
kraffslol/react-native-braintree-xplat | ios/RCTBraintree/Braintree/UnitTests/BTDropInUtil_Tests.swift | 2 | 770 | import XCTest
class BTDropInUtil_Tests: XCTestCase {
func testBTDropInUtil_topViewControllerReturnsViewController() {
let topInitialTopController = BTDropInUtil.topViewController()
XCTAssertNotNil(topInitialTopController, "Top UIViewController should not be nil")
let windowRootController = UIViewController()
let secondWindow = UIWindow(frame: UIScreen.main.bounds)
secondWindow.rootViewController = windowRootController
secondWindow.makeKeyAndVisible()
secondWindow.windowLevel = 100
let topSecondTopController = BTDropInUtil.topViewController()
XCTAssertNotEqual(topInitialTopController, topSecondTopController)
XCTAssertEqual(windowRootController, topSecondTopController)
}
}
| mit |
Keenan144/SpaceKase | SpaceKase/GameScene.swift | 1 | 9887 | //
// GameScene.swift
// SpaceKase
//
// Created by Keenan Sturtevant on 5/29/16.
// Copyright (c) 2016 Keenan Sturtevant. All rights reserved.
//
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
let shipCategory: UInt32 = 0x1 << 1
let rockCategory: UInt32 = 0x1 << 2
let boundaryCategory: UInt32 = 0x1 << 3
let healthCategory: UInt32 = 0x2 << 4
var score = NSInteger()
var label = SKLabelNode(fontNamed: "Arial")
var ship = SKSpriteNode()
var rock = SKSpriteNode()
var health = SKSpriteNode()
var boosterRateTimer = NSTimer()
var rockRateTimer = NSTimer()
var healthRateTimer = NSTimer()
var scoreLabel = SKLabelNode(fontNamed: "Arial")
var exitLabel = SKLabelNode(fontNamed: "Arial")
var invincibleLabel = SKLabelNode()
var invincibilityTimer = Int32()
var invincibilityNSTimer = NSTimer()
var boundary = SKSpriteNode()
var boundaryColor = UIColor.yellowColor()
var backgroundColorCustom = UIColor(red: 0.1, green: 0.1, blue: 0.1, alpha: 1.0)
var touchLocation = CGPoint()
override func didMoveToView(view: SKView) {
view.showsPhysics = false
physicsWorld.contactDelegate = self
self.backgroundColor = backgroundColorCustom
setBoundaries()
spawnShip()
start()
}
func setBoundaries() {
setBottomBoundary()
setLeftSideBoundry()
setRightSideBoundry()
}
func start() {
score = 0
Helper.toggleRun(true)
showExitButton()
showScore()
rockTimer()
healthTimer()
boosterTimer()
}
func spawnShip(){
ship = SpaceShip.spawn(shipCategory, rockCategory: rockCategory, frame: self.frame)
SpaceShip.setShipHealth(Helper.setShipHealth())
showHealth()
self.addChild(ship)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches{
touchLocation = touch.locationInNode(self)
let pos = touch.locationInNode(self)
let node = self.nodeAtPoint(pos)
if node == exitLabel {
stopRocks()
endGame()
} else {
touchLocation = touch.locationInNode(self)
ship.position.x = touchLocation.x
print(ship.position.x)
}
}
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches{
touchLocation = touch.locationInNode(self)
ship.position.x = touchLocation.x
}
}
func didBeginContact(contact: SKPhysicsContact) {
if (contact.bodyA.categoryBitMask == boundaryCategory) {
contact.bodyB.node?.removeFromParent()
print("GAMESCENE: scoreIncresed")
increaseScore()
refreshScoreView()
}
if (contact.bodyA.categoryBitMask == shipCategory) {
contact.bodyB.node?.physicsBody?.collisionBitMask = 0
if (contact.bodyB.node?.name == "Health") {
contact.bodyB.node?.removeFromParent()
increaseHealth()
} else if (contact.bodyB.node?.name == "ScoreBump") {
contact.bodyB.node?.removeFromParent()
bumpScore()
} else if (contact.bodyB.node?.name == "Invincibility") {
contact.bodyB.node?.removeFromParent()
makeInvincible()
showInvincibleLabel()
} else if (contact.bodyB.node?.name == "Rock") {
if Helper.isInvincible() == false {
SpaceShip.deductHealth(Helper.deductHealth())
if SpaceShip.dead() {
stopRocks()
endGame()
}
}
}
refreshHealthView()
}
}
func increaseHealth() {
if Helper.canRun() {
SpaceShip.health = SpaceShip.health + 5
}
}
func bumpScore() {
if Helper.canRun() {
score = score + 50
}
}
func increaseScore() {
if Helper.canRun() {
score = score + 5
}
}
func spawnRock() {
if Helper.canRun() {
rock = Rock.spawn()
rock.position = Helper.randomSpawnPoint(frame.minX, valueHighX: frame.maxX, valueY: frame.maxY)
self.addChild(rock)
}
}
func spawnHealth() {
if Helper.canRun() {
health = Health.spawn()
health.position = Helper.randomSpawnPoint(frame.minX, valueHighX: frame.maxX, valueY: frame.maxY)
self.addChild(health)
}
}
func randomSpawn() {
if Helper.canRun() {
if Helper.randomSpawn() == 1 {
let boost = Boost.spawnInvincibility()
boost.position = Helper.randomSpawnPoint(frame.minX, valueHighX: frame.maxX, valueY: self.frame.maxY)
self.addChild(boost)
} else {
let boost = Boost.spawnScoreBump()
boost.position = Helper.randomSpawnPoint(frame.minX, valueHighX: frame.maxX, valueY: self.frame.maxY)
self.addChild(boost)
}
}
}
func boosterTimer() {
boosterRateTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: ("randomSpawn"), userInfo: nil, repeats: true)
}
func rockTimer() {
rockRateTimer = NSTimer.scheduledTimerWithTimeInterval(Helper.rockSpawnRate(), target: self, selector: ("spawnRock"), userInfo: nil, repeats: true)
}
func healthTimer() {
healthRateTimer = NSTimer.scheduledTimerWithTimeInterval(5.3, target: self, selector: ("spawnHealth"), userInfo: nil, repeats: true)
}
func stopRocks() {
Helper.toggleRun(false)
}
private func showHighScores() {
Helper.setLastScore(score)
}
private func setBottomBoundary() {
let boundary = Boundary.setBottomBoundary(boundaryCategory, rockCategory: rockCategory, frame: self.frame)
self.addChild(boundary)
}
private func setRightSideBoundry() {
let boundary = Boundary.setRightSideBoundary(boundaryCategory, rockCategory: rockCategory, frame: self.frame)
self.addChild(boundary)
}
private func setLeftSideBoundry() {
let boundary = Boundary.setLeftSideBoundary(boundaryCategory, rockCategory: rockCategory, frame: self.frame)
self.addChild(boundary)
}
private func showHealth() {
let health = Health.showHealth(label)
health.fontSize = 20
health.position = CGPoint(x: self.frame.minX + 55 , y: self.frame.maxY - 40)
self.addChild(health)
}
func showInvincibleLabel() {
if 15 - invincibilityTimer > 0 {
invincibleLabel.removeFromParent()
let invLabel = invincibleLabel
invLabel.text = "Invincible: \(15 - invincibilityTimer)"
invLabel.fontColor = UIColor.yellowColor()
invLabel.fontSize = 20
invLabel.position = CGPoint(x: self.frame.minX + 55 , y: self.frame.maxY - 65)
self.addChild(invLabel)
} else {
invincibleLabel.removeFromParent()
}
}
private func showScore() {
scoreLabel.text = "Score: \(score)"
scoreLabel.fontSize = 20
scoreLabel.position = CGPoint(x: self.frame.maxX - 75 , y: self.frame.maxY - 40)
self.addChild(scoreLabel)
}
func showExitButton() {
if Helper.canRun() {
exitLabel.text = "exit"
exitLabel.fontSize = 20
exitLabel.position = CGPoint(x: self.frame.maxX - 55, y: self.frame.maxY - 80)
self.addChild(exitLabel)
}
}
private func refreshHealthView() {
label.removeFromParent()
showHealth()
print("GAMESCENE: refreshHealthView")
}
private func refreshScoreView() {
scoreLabel.removeFromParent()
showScore()
print("GAMESCENE: refreshScoreView")
}
private func endGame() {
showHighScores()
ship.removeAllActions()
rock.removeAllActions()
invincibleLabel.removeAllActions()
let skView = self.view as SKView!;
let gameScene = EndScene(size: (skView?.bounds.size)!)
let transition = SKTransition.fadeWithDuration (2.0)
boosterRateTimer.invalidate()
rockRateTimer.invalidate()
healthRateTimer.invalidate()
view!.presentScene(gameScene, transition: transition)
}
private func makeInvincible() {
if Helper.invincible == false {
Helper.toggleInvincibility(true)
invincibilityTimer = 1
startInvincibilityTimer()
print("GAMESCENE: makeInvincible")
}
}
@objc private func incrementInvincibilityTimer() {
invincibilityTimer = invincibilityTimer + 1
showInvincibleLabel()
if invincibilityTimer >= 15 {
invincibilityNSTimer.invalidate()
Helper.toggleInvincibility(false)
print("GAMESCENE: incrementInvincibilityTimer")
}
}
private func returnInvincibilityTime() -> Int32 {
return invincibilityTimer
}
private func startInvincibilityTimer() {
invincibilityNSTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: (#selector(GameScene.incrementInvincibilityTimer)), userInfo: nil, repeats: true)
print("GAMESCENE: startInvincibilityTimer")
}
}
| mit |
TangGuowei/SwiftDemo | Chapter1/Chapter1/AppDelegate.swift | 1 | 2130 | //
// AppDelegate.swift
// Chapter1
//
// Created by Tom on 15/4/9.
// Copyright (c) 2015年 Tom. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
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:.
}
}
| mit |
rharri/EventsAndFestivals | Package.swift | 1 | 427 | import PackageDescription
let package = Package(
name: "EventsAndFestivals",
dependencies: [
.Package(url: "https://github.com/vapor/vapor.git", majorVersion: 1, minor: 3),
.Package(url: "https://github.com/OpenKitten/MongoKitten.git", majorVersion: 3)
],
exclude: [
"Config",
"Database",
"Localization",
"Public",
"Resources",
"Tests",
]
)
| mit |
eurofurence/ef-app_ios | Packages/EurofurenceComponents/Tests/ScheduleComponentTests/Presenter Tests/Share Command/SchedulePresenterShareCommandTests.swift | 1 | 1207 | import EurofurenceModel
import ScheduleComponent
import XCTest
import XCTScheduleComponent
class SchedulePresenterShareCommandTests: XCTestCase {
func testShareCommand() throws {
let eventViewModel = StubScheduleEventViewModel.random
let eventGroupViewModel = ScheduleEventGroupViewModel(title: .random, events: [eventViewModel])
let viewModel = CapturingScheduleViewModel(days: .random, events: [eventGroupViewModel], currentDay: 0)
let viewModelFactory = FakeScheduleViewModelFactory(viewModel: viewModel)
let context = SchedulePresenterTestBuilder().with(viewModelFactory).build()
context.simulateSceneDidLoad()
let searchResult = StubScheduleEventViewModel.random
searchResult.isFavourite = false
let indexPath = IndexPath(item: 0, section: 0)
let commands = context.scene.binder?.eventActionsForComponent(at: indexPath)
let action = try XCTUnwrap(commands?.command(titled: .share))
XCTAssertEqual("square.and.arrow.up", action.sfSymbol)
let sender = "Cell"
action.run(sender)
XCTAssertEqual(sender, eventViewModel.sharedSender as? String)
}
}
| mit |
Yalantis/EatFit | EatFit/Vendors/YALPageController/YALPageController.swift | 1 | 5547 | //
// YALPageController.swift
// EatFit
//
// Created by Dmitriy Demchenko on 7/12/16.
// Copyright © 2016 aleksey chernish. All rights reserved.
//
import UIKit
fileprivate 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
}
}
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
typealias YALPageControllerTransitionHook = ((_ pageViewController: UIPageViewController, _ viewController: UIViewController, _ pageIndex: Int) -> Void)
class YALPageController: NSObject {
// declare a static var to produce a unique address as the assoc object handle
static var YALPageControllerAssociatedObjectHandle: UInt8 = 123
var viewControllers = [UIViewController]()
var didFinishTransition: YALPageControllerTransitionHook?
var pagingEnabled = true
weak var pageViewController: UIPageViewController!
fileprivate weak var scrollView: UIScrollView!
func showPage(_ index: Int, animated: Bool) {
showViewController(viewControllers[Int(index)], animated: animated)
if let pageViewController = pageViewController, let firstControllers = viewControllers.first {
didFinishTransition?(
pageViewController,
firstControllers,
index
)
}
}
func showViewController(_ viewController: UIViewController, animated: Bool) {
guard let pageViewController = pageViewController else {
return
}
guard let lastViewController = pageViewController.viewControllers?.last else {
return
}
let currentIndex = viewControllers.firstIndex(of: lastViewController)
let index = viewControllers.firstIndex(of: viewController)
if currentIndex == index {
return
}
let direction: UIPageViewController.NavigationDirection = index > currentIndex ? .forward : .reverse
pageViewController.setViewControllers(
[viewController],
direction: direction,
animated: animated,
completion: { _ in
if let _ = self.scrollView {
self.scrollView.isScrollEnabled = self.pagingEnabled
}
}
)
}
func setupViewControllers(_ viewControllers: [UIViewController]) {
self.viewControllers = viewControllers
guard let pageViewController = pageViewController else {
return
}
guard let firstViewController = viewControllers.first else {
return
}
pageViewController.setViewControllers(
[firstViewController],
direction: .forward,
animated: false,
completion: nil
)
guard let pageIndex = viewControllers.firstIndex(of: firstViewController) else {
return
}
didFinishTransition?(
pageViewController,
firstViewController,
pageIndex
)
}
func setupPageViewController(_ pageViewController: UIPageViewController) {
self.pageViewController = pageViewController
self.pageViewController.view.subviews.forEach { view in
if let view = view as? UIScrollView {
scrollView = view
}
}
}
// MARK: - Paging Enabled
fileprivate func setupPagingEnabled(_ pagingEnabled: Bool) {
self.pagingEnabled = pagingEnabled
if let _ = scrollView {
scrollView.isScrollEnabled = pagingEnabled
}
}
}
extension YALPageController: UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let index = viewControllers.firstIndex(of: viewController) else {
return nil
}
if index >= viewControllers.count - 1 {
return nil
}
return viewControllers[index + 1]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let index = viewControllers.firstIndex(of: viewController) else {
return nil
}
if index <= 0 {
return nil
}
return viewControllers[index - 1]
}
}
extension YALPageController: UIPageViewControllerDelegate {
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if let _ = scrollView {
scrollView.isPagingEnabled = pagingEnabled
}
if let lastViewController = pageViewController.viewControllers?.last , lastViewController != previousViewControllers.last {
if let lastIndex = viewControllers.firstIndex(of: lastViewController) {
didFinishTransition?(
pageViewController,
lastViewController,
lastIndex
)
}
}
}
}
| mit |
ted005/Qiu_Suo | Qiu Suo/Qiu Suo/TWNodeSearchTableViewController.swift | 2 | 5132 | //
// TWNodeSearchTableViewController.swift
// V2EX Explorer
//
// Created by Robbie on 15/8/23.
// Copyright (c) 2015年 Ted Wei. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class TWNodeSearchTableViewController: UITableViewController, UISearchResultsUpdating, UISearchBarDelegate{
var searchController: UISearchController?
var nodes: [TWNode] = []
var filteredNodes: [TWNode] = []
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
self.clearsSelectionOnViewWillAppear = true
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "seachCell")
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
//search
searchController = UISearchController(searchResultsController: nil)
self.searchController!.searchResultsUpdater = self
self.navigationItem.titleView = searchController?.searchBar
self.searchController?.dimsBackgroundDuringPresentation = false
self.searchController?.searchBar.barStyle = UIBarStyle.Default
self.searchController?.hidesNavigationBarDuringPresentation = false
self.searchController?.searchBar.delegate = self
//load all nodes
Alamofire.request(.GET, "https://www.v2ex.com/api/nodes/all.json")
.responseJSON { (req, res, result)in
if(result.isFailure) {
NSLog("Fail to load data.")
}
else {
let json = JSON(result.value!)
for subJson in json {
let node: TWNode = TWNode()
node.title = subJson.1["title"].stringValue
node.name = subJson.1["name"].stringValue
node.header = subJson.1["header"].stringValue
node.topics = subJson.1["topics"].intValue
node.url = subJson.1["url"].stringValue
self.nodes.append(node)
}
self.filteredNodes = self.nodes
//dont show all nodes
// self.tableView.reloadData()
}
}
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
filteredNodes.removeAll(keepCapacity: true)
let searchText = searchController.searchBar.text
for node in nodes {
if (node.title?.lowercaseString.rangeOfString(searchText!.lowercaseString) != nil) {
filteredNodes.append(node)
}
}
tableView.reloadData()
tableView.separatorStyle = UITableViewCellSeparatorStyle.SingleLine
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredNodes.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("searchCell", forIndexPath: indexPath)
cell.textLabel?.text = filteredNodes[indexPath.row].title
cell.detailTextLabel?.text = filteredNodes[indexPath.row].header
return cell
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
//placeholder
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
//placeholder
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//wrong, will trigger receiver has no segue with identifier '***' error
// let destVC = TWExplorePostsTableViewController()
//init vc with storyboard, it has segue configured
let destVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("topicsInNodeVC") as! TWExplorePostsTableViewController
destVC.nodeName = filteredNodes[indexPath.row].name!
destVC.nodeNameForTitle = filteredNodes[indexPath.row].title!
self.navigationController?.pushViewController(destVC, animated: true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
//fix select back to Explore showing black screen
override func viewWillDisappear(animated: Bool) {
NSLog("will dispappear......")
super.viewWillDisappear(true)
self.searchController?.active = false
}
}
| gpl-2.0 |
RocketChat/Rocket.Chat.iOS | Rocket.ChatTests/Models/SubscriptionQueriesSpec.swift | 1 | 2506 | //
// SubscriptionQueriesSpec.swift
// Rocket.ChatTests
//
// Created by Rafael Kellermann Streit on 23/04/18.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import XCTest
import RealmSwift
@testable import Rocket_Chat
class SubscriptionManagerQueriesSpec: XCTestCase {
override func tearDown() {
super.tearDown()
Realm.clearDatabase()
}
func testFindByRoomId() throws {
let sub1 = Subscription()
sub1.identifier = "sub1-identifier"
sub1.rid = "sub1-rid"
let sub2 = Subscription()
sub2.identifier = "sub2-identifier"
sub2.rid = "sub2-rid"
Realm.current?.execute({ realm in
realm.add(sub1, update: true)
realm.add(sub2, update: true)
})
XCTAssertEqual(Subscription.find(rid: "sub2-rid"), sub2)
XCTAssertEqual(Subscription.find(rid: "sub1-rid"), sub1)
}
func testFindByNameAndType() throws {
let sub1 = Subscription()
sub1.identifier = "sub1-identifier"
sub1.name = "sub1-name"
sub1.type = .directMessage
let sub2 = Subscription()
sub2.identifier = "sub2-identifier"
sub2.name = "sub2-name"
sub2.type = .channel
Realm.current?.execute({ realm in
realm.add(sub1, update: true)
realm.add(sub2, update: true)
})
XCTAssertEqual(Subscription.find(name: "sub1-name", subscriptionType: [.directMessage]), sub1)
XCTAssertEqual(Subscription.find(name: "sub2-name", subscriptionType: [.channel]), sub2)
}
func testSetTemporaryMessagesFailed() {
let user = User.testInstance()
let sub = Subscription.testInstance()
let msg1 = Message.testInstance("msg1")
msg1.rid = sub.rid
msg1.failed = false
msg1.temporary = true
msg1.userIdentifier = user.identifier
let msg2 = Message.testInstance("msg2")
msg2.rid = sub.rid
msg2.failed = false
msg2.temporary = true
msg2.userIdentifier = user.identifier
Realm.current?.execute({ realm in
realm.add(user, update: true)
realm.add(sub, update: true)
realm.add(msg1, update: true)
realm.add(msg2, update: true)
})
sub.setTemporaryMessagesFailed(user: user)
XCTAssertTrue(msg1.failed)
XCTAssertFalse(msg1.temporary)
XCTAssertTrue(msg2.failed)
XCTAssertFalse(msg2.temporary)
}
}
| mit |
pffan91/FUSION | FUSION/Templates/FUSION/Scene.xctemplate/ConfiguratorUIViewController/___FILEBASENAME___ViewModel.swift | 2 | 417 | //___FILEHEADER___
// Powered by FUSION Architecture
import UIKit
class ___VARIABLE_sceneName___ViewModel: NSObject {
// MARK: - Variables
var cellItems: [AnyObject] = []
var inputData: ___VARIABLE_sceneName___SceneInputData = ___VARIABLE_sceneName___SceneInputData()
// MARK: - Generators
func generateCellItems() {
cellItems.removeAll()
}
// MARK: - Private
}
| mit |
MaartenBrijker/project | project/External/AudioKit-master/AudioKit/iOS/AudioKit/AudioKit.playground/Pages/Moog Ladder Filter.xcplaygroundpage/Contents.swift | 2 | 2635 | //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
//:
//: ---
//:
//: ## Moog Ladder Filter
//: ### One of the coolest filters available in AudioKit is the Moog Ladder. It's based off of Robert Moog's iconic ladder filter, which was the first implementation of a voltage - controlled filter used in an analog synthesizer. As such, it was the first filter that gave the ability to use voltage control to determine the cutoff frequency of the filter. As we're dealing with a software implementation, and not an analog synthesizer, we don't have to worry about dealing with voltage control directly. However, by using this node, you can emulate some of the sounds of classic analog synthesizers in your app.
import XCPlayground
import AudioKit
let bundle = NSBundle.mainBundle()
let file = bundle.pathForResource("mixloop", ofType: "wav")
var player = AKAudioPlayer(file!)
player.looping = true
var moogLadder = AKMoogLadder(player)
//: Set the parameters of the Moog Ladder Filter here.
moogLadder.cutoffFrequency = 300 // Hz
moogLadder.resonance = 0.6
AudioKit.output = moogLadder
AudioKit.start()
player.play()
//: User Interface Set up
class PlaygroundView: AKPlaygroundView {
var cutoffFrequencyLabel: Label?
var resonanceLabel: Label?
override func setup() {
addTitle("Moog Ladder Filter")
addLabel("Audio Playback")
addButton("Start", action: #selector(start))
addButton("Stop", action: #selector(stop))
cutoffFrequencyLabel = addLabel("Cutoff Frequency: \(moogLadder.cutoffFrequency)")
addSlider(#selector(setCutoffFrequency), value: moogLadder.cutoffFrequency, minimum: 0, maximum: 5000)
resonanceLabel = addLabel("Resonance: \(moogLadder.resonance)")
addSlider(#selector(setResonance), value: moogLadder.resonance, minimum: 0, maximum: 0.99)
}
func start() {
player.play()
}
func stop() {
player.stop()
}
func setCutoffFrequency(slider: Slider) {
moogLadder.cutoffFrequency = Double(slider.value)
cutoffFrequencyLabel!.text = "Cutoff Frequency: \(String(format: "%0.0f", moogLadder.cutoffFrequency))"
}
func setResonance(slider: Slider) {
moogLadder.resonance = Double(slider.value)
resonanceLabel!.text = "Resonance: \(String(format: "%0.3f", moogLadder.resonance))"
}
}
let view = PlaygroundView(frame: CGRect(x: 0, y: 0, width: 500, height: 300))
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
XCPlaygroundPage.currentPage.liveView = view
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
| apache-2.0 |
EstefaniaGilVaquero/ciceIOS | APP_CompartirContacto/SYBTableViewCell.swift | 1 | 889 | //
// SYBTableViewCell.swift
// APP_CompartirContacto
//
// Created by cice on 9/9/16.
// Copyright © 2016 cice. All rights reserved.
//
import UIKit
class SYBTableViewCell: UITableViewCell {
//parsear datos del json
//http://91.126.140.33:5554/pagina2/home/index
@IBOutlet weak var myNombreLBL: UILabel!
@IBOutlet weak var myApellidoLBL: UILabel!
@IBOutlet weak var myUsernameLBL: UILabel!
@IBOutlet weak var myDescripcionLBL: UILabel!
@IBOutlet weak var myFotoIV: UIImageView!
@IBOutlet weak var mySharedButton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| apache-2.0 |
hevertonrodrigues/HRSideBar | HRSideBar/HRSideBarView.swift | 1 | 1079 | //
// HRSideBarView.swift
// HRSideBar
//
// Created by Heverton Rodrigues on 23/09/14.
// Copyright (c) 2014 Heverton Rodrigues. All rights reserved.
//
import Foundation
import UIKit
class HRSideBarView :UIView
{
private var width :Double = Double()
private var height :Double = Double()
override init()
{
super.init()
self.backgroundColor = UIColor( rgba: "#AEAEAE" )
}
override init(frame: CGRect)
{
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setSize( width w :Double, height h :Double )
{
self.width = w
self.height = h
self.frame = CGRectMake( CGFloat( -w ), 0, CGFloat( w ) , CGFloat( h ) )
}
func open()
{
self.frame = CGRectMake( 0, 0, CGFloat( self.width ) , self.frame.size.height )
}
func close()
{
self.frame = CGRectMake( CGFloat( -self.width ), 0, CGFloat( self.width ) , self.frame.size.height )
}
} | mit |
apple/swift | test/refactoring/ConvertAsync/convert_params_single.swift | 7 | 17585 | // RUN: %empty-directory(%t)
// REQUIRES: concurrency
func withError() async throws -> String { "" }
func withError(_ completion: @escaping (String?, Error?) -> Void) { }
func notOptional() async throws -> String { "" }
func notOptional(_ completion: @escaping (String, Error?) -> Void) { }
func errorOnly() async throws { }
func errorOnly(_ completion: @escaping (Error?) -> Void) { }
func test(_ str: String) -> Bool { return false }
func testParamsSingle() async throws {
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNRELATED %s
withError { res, err in
if test("unrelated") {
print("unrelated")
} else {
print("else unrelated")
}
}
// UNRELATED: convert_params_single.swift
// UNRELATED-NEXT: let res = try await withError()
// UNRELATED-NEXT: if test("unrelated") {
// UNRELATED-NEXT: print("unrelated")
// UNRELATED-NEXT: } else {
// UNRELATED-NEXT: print("else unrelated")
// UNRELATED-NEXT: }
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=BOUND %s
withError { res, err in
print("before")
if let bad = err {
print("got error \(bad)")
return
}
if let str = res {
print("got result \(str)")
}
print("after")
}
// BOUND: do {
// BOUND-NEXT: let str = try await withError()
// BOUND-NEXT: print("before")
// BOUND-NEXT: print("got result \(str)")
// BOUND-NEXT: print("after")
// BOUND-NEXT: } catch let bad {
// BOUND-NEXT: print("got error \(bad)")
// BOUND-NEXT: }
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=BOUND-COMMENT %s
withError { res, err in // a
// b
print("before")
// c
if let bad = err { // d
// e
print("got error \(bad)")
// f
return
// g
}
// h
if let str = res { // i
// j
print("got result \(str)")
// k
}
// l
print("after")
// m
}
// BOUND-COMMENT: do {
// BOUND-COMMENT-NEXT: let str = try await withError()
// BOUND-COMMENT-NEXT: // a
// BOUND-COMMENT-NEXT: // b
// BOUND-COMMENT-NEXT: print("before")
// BOUND-COMMENT-NEXT: // c
// BOUND-COMMENT-NEXT: // h
// BOUND-COMMENT-NEXT: // i
// BOUND-COMMENT-NEXT: // j
// BOUND-COMMENT-NEXT: print("got result \(str)")
// BOUND-COMMENT-NEXT: // k
// BOUND-COMMENT-NEXT: // l
// BOUND-COMMENT-NEXT: print("after")
// BOUND-COMMENT-NEXT: // m
// BOUND-COMMENT-NEXT: } catch let bad {
// BOUND-COMMENT-NEXT: // d
// BOUND-COMMENT-NEXT: // e
// BOUND-COMMENT-NEXT: print("got error \(bad)")
// BOUND-COMMENT-NEXT: // f
// BOUND-COMMENT-NEXT: // g
// BOUND-COMMENT-NEXT: }
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND-ERR %s
withError { res, err in
print("before")
guard let str = res else {
print("got error \(err!)")
return
}
print("got result \(str)")
print("after")
}
// UNBOUND-ERR: do {
// UNBOUND-ERR-NEXT: let str = try await withError()
// UNBOUND-ERR-NEXT: print("before")
// UNBOUND-ERR-NEXT: print("got result \(str)")
// UNBOUND-ERR-NEXT: print("after")
// UNBOUND-ERR-NEXT: } catch let err {
// UNBOUND-ERR-NEXT: print("got error \(err)")
// UNBOUND-ERR-NEXT: }
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=BOUND %s
withError { res, err in
print("before")
if let bad = err {
print("got error \(bad)")
} else if let str = res {
print("got result \(str)")
}
print("after")
}
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=BOUND %s
withError { res, err in
print("before")
if let bad = err {
print("got error \(bad)")
return
}
if let str = res {
print("got result \(str)")
}
print("after")
}
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND-RES %s
withError { res, err in
print("before")
if let bad = err {
print("got error \(bad)")
return
}
print("got result \(res!)")
print("after")
}
// UNBOUND-RES: do {
// UNBOUND-RES-NEXT: let res = try await withError()
// UNBOUND-RES-NEXT: print("before")
// UNBOUND-RES-NEXT: print("got result \(res)")
// UNBOUND-RES-NEXT: print("after")
// UNBOUND-RES-NEXT: } catch let bad {
// UNBOUND-RES-NEXT: print("got error \(bad)")
// UNBOUND-RES-NEXT: }
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND-ERR %s
withError { res, err in
print("before")
if let str = res {
print("got result \(str)")
print("after")
return
}
print("got error \(err!)")
}
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND-RES %s
withError { res, err in
print("before")
if let bad = err {
print("got error \(bad)")
} else {
print("got result \(res!)")
}
print("after")
}
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND-ERR %s
withError { res, err in
print("before")
if let str = res {
print("got result \(str)")
} else {
print("got error \(err!)")
}
print("after")
}
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND %s
withError { res, err in
print("before")
if err != nil {
print("got error \(err!)")
return
}
print("got result \(res!)")
print("after")
}
// UNBOUND: do {
// UNBOUND-NEXT: let res = try await withError()
// UNBOUND-NEXT: print("before")
// UNBOUND-NEXT: print("got result \(res)")
// UNBOUND-NEXT: print("after")
// UNBOUND-NEXT: } catch let err {
// UNBOUND-NEXT: print("got error \(err)")
// UNBOUND-NEXT: }
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND %s
withError { res, err in
print("before")
if res != nil {
print("got result \(res!)")
print("after")
return
}
print("got error \(err!)")
}
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND %s
withError { res, err in
print("before")
if err != nil {
print("got error \(err!)")
} else {
print("got result \(res!)")
}
print("after")
}
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND %s
withError { res, err in
print("before")
if res != nil {
print("got result \(res!)")
} else {
print("got error \(err!)")
}
print("after")
}
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND %s
withError { res, err in
print("before")
if err == nil {
print("got result \(res!)")
} else {
print("got error \(err!)")
}
print("after")
}
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND %s
withError { res, err in
print("before")
if res == nil {
print("got error \(err!)")
} else {
print("got result \(res!)")
}
print("after")
}
// Cannot use refactor-check-compiles because of the placeholder, compiler is unable to infer 'str'.
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNHANDLEDNESTED %s
withError { res, err in
print("before")
if let bad = err {
print("got error \(bad)")
} else {
if let str = res {
print("got result \(str)")
}
}
print("after")
}
// UNHANDLEDNESTED: do {
// UNHANDLEDNESTED-NEXT: let res = try await withError()
// UNHANDLEDNESTED-NEXT: print("before")
// UNHANDLEDNESTED-NEXT: if let str = <#res#> {
// UNHANDLEDNESTED-NEXT: print("got result \(str)")
// UNHANDLEDNESTED-NEXT: }
// UNHANDLEDNESTED-NEXT: print("after")
// UNHANDLEDNESTED-NEXT: } catch let bad {
// UNHANDLEDNESTED-NEXT: print("got error \(bad)")
// UNHANDLEDNESTED-NEXT: }
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=NOERR %s
withError { res, err in
print("before")
if let str = res {
print("got result \(str)")
}
print("after")
}
// NOERR: convert_params_single.swift
// NOERR-NEXT: let str = try await withError()
// NOERR-NEXT: print("before")
// NOERR-NEXT: print("got result \(str)")
// NOERR-NEXT: print("after")
// NOERR-NOT: }
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=NORES %s
withError { res, err in
print("before")
if let bad = err {
print("got error \(bad)")
}
print("after")
}
// NORES: do {
// NORES-NEXT: let res = try await withError()
// NORES-NEXT: print("before")
// NORES-NEXT: print("after")
// NORES-NEXT: } catch let bad {
// NORES-NEXT: print("got error \(bad)")
// NORES-NEXT: }
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND %s
withError { res, err in
print("before")
if ((res != (nil)) && err == nil) {
print("got result \(res!)")
} else {
print("got error \(err!)")
}
print("after")
}
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNKNOWN-COND %s
withError { res, err in
print("before")
if res != nil && test(res!) {
print("got result \(res!)")
}
print("after")
}
// UNKNOWN-COND: convert_params_single.swift
// UNKNOWN-COND-NEXT: let res = try await withError()
// UNKNOWN-COND-NEXT: print("before")
// UNKNOWN-COND-NEXT: if <#res#> != nil && test(res) {
// UNKNOWN-COND-NEXT: print("got result \(res)")
// UNKNOWN-COND-NEXT: }
// UNKNOWN-COND-NEXT: print("after")
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNKNOWN-CONDELSE %s
withError { res, err in
print("before")
if res != nil && test(res!) {
print("got result \(res!)")
} else {
print("bad")
}
print("after")
}
// UNKNOWN-CONDELSE: var res: String? = nil
// UNKNOWN-CONDELSE-NEXT: var err: Error? = nil
// UNKNOWN-CONDELSE-NEXT: do {
// UNKNOWN-CONDELSE-NEXT: res = try await withError()
// UNKNOWN-CONDELSE-NEXT: } catch {
// UNKNOWN-CONDELSE-NEXT: err = error
// UNKNOWN-CONDELSE-NEXT: }
// UNKNOWN-CONDELSE-EMPTY:
// UNKNOWN-CONDELSE-NEXT: print("before")
// UNKNOWN-CONDELSE-NEXT: if res != nil && test(res!) {
// UNKNOWN-CONDELSE-NEXT: print("got result \(res!)")
// UNKNOWN-CONDELSE-NEXT: } else {
// UNKNOWN-CONDELSE-NEXT: print("bad")
// UNKNOWN-CONDELSE-NEXT: }
// UNKNOWN-CONDELSE-NEXT: print("after")
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=MULTIBIND %s
withError { res, err in
print("before")
if let str = res {
print("got result \(str)")
}
if let str2 = res {
print("got result \(str2)")
}
if case (let str3?) = (res) {
print("got result \(str3)")
}
print("after")
}
// MULTIBIND: let str = try await withError()
// MULTIBIND-NEXT: print("before")
// MULTIBIND-NEXT: print("got result \(str)")
// MULTIBIND-NEXT: print("got result \(str)")
// MULTIBIND-NEXT: print("got result \(str)")
// MULTIBIND-NEXT: print("after")
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=NESTEDRET %s
withError { res, err in
print("before")
if let str = res {
if test(str) {
return
}
print("got result \(str)")
}
print("after")
}
// NESTEDRET: convert_params_single.swift
// NESTEDRET-NEXT: let str = try await withError()
// NESTEDRET-NEXT: print("before")
// NESTEDRET-NEXT: if test(str) {
// NESTEDRET-NEXT: <#return#>
// NESTEDRET-NEXT: }
// NESTEDRET-NEXT: print("got result \(str)")
// NESTEDRET-NEXT: print("after")
// NESTEDRET-NOT: }
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND-ERR %s
withError { res, err in
print("before")
guard let str = res, err == nil else {
print("got error \(err!)")
return
}
print("got result \(str)")
print("after")
}
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND %s
withError { res, err in
print("before")
guard res != nil else {
print("got error \(err!)")
return
}
print("got result \(res!)")
print("after")
}
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND %s
withError { res, err in
print("before")
guard err == nil else {
print("got error \(err!)")
return
}
print("got result \(res!)")
print("after")
}
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND %s
withError { res, err in
print("before")
guard res != nil && err == nil else {
print("got error \(err!)")
return
}
print("got result \(res!)")
print("after")
}
// Cannot use refactor-check-compiles as transform results in invalid code,
// see comment below.
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNWRAPPING %s
withError { str, err in
print("before")
guard err == nil else { return }
_ = str!.count
_ = /*before*/str!/*after*/.count
_ = str?.count
_ = str!.count.bitWidth
_ = str?.count.bitWidth
_ = (str?.count.bitWidth)!
_ = str!.first?.isWhitespace
_ = str?.first?.isWhitespace
_ = (str?.first?.isWhitespace)!
print("after")
}
// UNWRAPPING: let str = try await withError()
// UNWRAPPING-NEXT: print("before")
// UNWRAPPING-NEXT: _ = str.count
// UNWRAPPING-NEXT: _ = /*before*/str/*after*/.count
// UNWRAPPING-NEXT: _ = str.count
// UNWRAPPING-NEXT: _ = str.count.bitWidth
// UNWRAPPING-NEXT: _ = str.count.bitWidth
// Note this transform results in invalid code as str.count.bitWidth is no
// longer optional, but arguably it's more useful than leaving str as a
// placeholder. In general, the transform we perform here is locally valid
// within the optional chain, but may change the type of the overall chain.
// UNWRAPPING-NEXT: _ = (str.count.bitWidth)!
// UNWRAPPING-NEXT: _ = str.first?.isWhitespace
// UNWRAPPING-NEXT: _ = str.first?.isWhitespace
// UNWRAPPING-NEXT: _ = (str.first?.isWhitespace)!
// UNWRAPPING-NEXT: print("after")
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=NOT-OPTIONAL %s
notOptional { str, err in
print("before")
if let err2 = err {
print("got error \(err2)")
return
}
print("got result \(str)")
print("after")
}
// NOT-OPTIONAL: do {
// NOT-OPTIONAL-NEXT: let str = try await notOptional()
// NOT-OPTIONAL-NEXT: print("before")
// NOT-OPTIONAL-NEXT: print("got result \(str)")
// NOT-OPTIONAL-NEXT: print("after")
// NOT-OPTIONAL-NEXT: } catch let err2 {
// NOT-OPTIONAL-NEXT: print("got error \(err2)")
// NOT-OPTIONAL-NEXT: }
// RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=ERROR-ONLY %s
errorOnly { err in
print("before")
if let err2 = err {
print("got error \(err2)")
return
}
print("after")
}
// ERROR-ONLY: convert_params_single.swift
// ERROR-ONLY-NEXT: do {
// ERROR-ONLY-NEXT: try await errorOnly()
// ERROR-ONLY-NEXT: print("before")
// ERROR-ONLY-NEXT: print("after")
// ERROR-ONLY-NEXT: } catch let err2 {
// ERROR-ONLY-NEXT: print("got error \(err2)")
// ERROR-ONLY-NEXT: }
// ERROR-ONLY-NOT: }
}
| apache-2.0 |
cburrows/swift-protobuf | Sources/SwiftProtobuf/timestamp.pb.swift | 1 | 9191 | // DO NOT EDIT.
// swift-format-ignore-file
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: google/protobuf/timestamp.proto
//
// For information on using the generated types, please see the documentation:
// https://github.com/apple/swift-protobuf/
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import Foundation
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that you are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _3: SwiftProtobuf.ProtobufAPIVersion_3 {}
typealias Version = _3
}
/// A Timestamp represents a point in time independent of any time zone or local
/// calendar, encoded as a count of seconds and fractions of seconds at
/// nanosecond resolution. The count is relative to an epoch at UTC midnight on
/// January 1, 1970, in the proleptic Gregorian calendar which extends the
/// Gregorian calendar backwards to year one.
///
/// All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap
/// second table is needed for interpretation, using a [24-hour linear
/// smear](https://developers.google.com/time/smear).
///
/// The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By
/// restricting to that range, we ensure that we can convert to and from [RFC
/// 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings.
///
/// # Examples
///
/// Example 1: Compute Timestamp from POSIX `time()`.
///
/// Timestamp timestamp;
/// timestamp.set_seconds(time(NULL));
/// timestamp.set_nanos(0);
///
/// Example 2: Compute Timestamp from POSIX `gettimeofday()`.
///
/// struct timeval tv;
/// gettimeofday(&tv, NULL);
///
/// Timestamp timestamp;
/// timestamp.set_seconds(tv.tv_sec);
/// timestamp.set_nanos(tv.tv_usec * 1000);
///
/// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
///
/// FILETIME ft;
/// GetSystemTimeAsFileTime(&ft);
/// UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
///
/// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
/// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
/// Timestamp timestamp;
/// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
/// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
///
/// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
///
/// long millis = System.currentTimeMillis();
///
/// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
/// .setNanos((int) ((millis % 1000) * 1000000)).build();
///
///
/// Example 5: Compute Timestamp from Java `Instant.now()`.
///
/// Instant now = Instant.now();
///
/// Timestamp timestamp =
/// Timestamp.newBuilder().setSeconds(now.getEpochSecond())
/// .setNanos(now.getNano()).build();
///
///
/// Example 6: Compute Timestamp from current time in Python.
///
/// timestamp = Timestamp()
/// timestamp.GetCurrentTime()
///
/// # JSON Mapping
///
/// In JSON format, the Timestamp type is encoded as a string in the
/// [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
/// format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
/// where {year} is always expressed using four digits while {month}, {day},
/// {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
/// seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
/// are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
/// is required. A proto3 JSON serializer should always use UTC (as indicated by
/// "Z") when printing the Timestamp type and a proto3 JSON parser should be
/// able to accept both UTC and other timezones (as indicated by an offset).
///
/// For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
/// 01:30 UTC on January 15, 2017.
///
/// In JavaScript, one can convert a Date object to this format using the
/// standard
/// [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)
/// method. In Python, a standard `datetime.datetime` object can be converted
/// to this format using
/// [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with
/// the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use
/// the Joda Time's [`ISODateTimeFormat.dateTime()`](
/// http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime%2D%2D
/// ) to obtain a formatter capable of generating timestamps in this format.
public struct Google_Protobuf_Timestamp {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
/// Represents seconds of UTC time since Unix epoch
/// 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
/// 9999-12-31T23:59:59Z inclusive.
public var seconds: Int64 = 0
/// Non-negative fractions of a second at nanosecond resolution. Negative
/// second values with fractions must still have non-negative nanos values
/// that count forward in time. Must be from 0 to 999,999,999
/// inclusive.
public var nanos: Int32 = 0
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
}
#if swift(>=5.5) && canImport(_Concurrency)
extension Google_Protobuf_Timestamp: @unchecked Sendable {}
#endif // swift(>=5.5) && canImport(_Concurrency)
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "google.protobuf"
extension Google_Protobuf_Timestamp: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".Timestamp"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "seconds"),
2: .same(proto: "nanos"),
]
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularInt64Field(value: &self.seconds) }()
case 2: try { try decoder.decodeSingularInt32Field(value: &self.nanos) }()
default: break
}
}
}
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if self.seconds != 0 {
try visitor.visitSingularInt64Field(value: self.seconds, fieldNumber: 1)
}
if self.nanos != 0 {
try visitor.visitSingularInt32Field(value: self.nanos, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
public static func ==(lhs: Google_Protobuf_Timestamp, rhs: Google_Protobuf_Timestamp) -> Bool {
if lhs.seconds != rhs.seconds {return false}
if lhs.nanos != rhs.nanos {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
| apache-2.0 |
apple/swift | test/Parse/operator_decl.swift | 4 | 5205 | // RUN: %target-typecheck-verify-swift
prefix operator +++ {} // expected-error {{operator should no longer be declared with body}} {{20-23=}}
postfix operator +++ {} // expected-error {{operator should no longer be declared with body}} {{21-24=}}
infix operator +++ {} // expected-error {{operator should no longer be declared with body}} {{19-22=}}
infix operator +++* { // expected-error {{operator should no longer be declared with body; use a precedence group instead}} {{none}}
associativity right
}
infix operator +++*+ : A { } // expected-error {{operator should no longer be declared with body}} {{25-29=}}
prefix operator +++** : A { }
// expected-error@-1 {{only infix operators may declare a precedence}} {{23-27=}}
// expected-error@-2 {{operator should no longer be declared with body}} {{26-30=}}
prefix operator ++*++ : A
// expected-error@-1 {{only infix operators may declare a precedence}} {{23-26=}}
postfix operator ++*+* : A { }
// expected-error@-1 {{only infix operators may declare a precedence}} {{24-28=}}
// expected-error@-2 {{operator should no longer be declared with body}} {{27-31=}}
postfix operator ++**+ : A
// expected-error@-1 {{only infix operators may declare a precedence}} {{24-27=}}
operator ++*** : A
// expected-error@-1 {{operator must be declared as 'prefix', 'postfix', or 'infix'}}
operator +*+++ { }
// expected-error@-1 {{operator must be declared as 'prefix', 'postfix', or 'infix'}}
// expected-error@-2 {{operator should no longer be declared with body}} {{15-19=}}
operator +*++* : A { }
// expected-error@-1 {{operator must be declared as 'prefix', 'postfix', or 'infix'}}
// expected-error@-2 {{operator should no longer be declared with body}} {{19-23=}}
prefix operator // expected-error {{expected operator name in operator declaration}}
;
prefix operator %%+
prefix operator ??
postfix operator ?? // expected-error {{postfix operator names starting with '?' or '!' are disallowed to avoid collisions with built-in unwrapping operators}}
prefix operator !!
postfix operator !! // expected-error {{postfix operator names starting with '?' or '!' are disallowed to avoid collisions with built-in unwrapping operators}}
postfix operator ?$$
// expected-error@-1 {{postfix operator names starting with '?' or '!' are disallowed}}
// expected-error@-2 {{'$$' is considered an identifier}}
infix operator --aa // expected-error {{'aa' is considered an identifier and must not appear within an operator name}}
infix operator aa--: A // expected-error {{'aa' is considered an identifier and must not appear within an operator name}}
infix operator <<$$@< // expected-error {{'$$' is considered an identifier and must not appear within an operator name}}
infix operator !!@aa // expected-error {{'@' is not allowed in operator names}}
infix operator #++= // expected-error {{'#' is not allowed in operator names}}
infix operator ++=# // expected-error {{'#' is not allowed in operator names}}
infix operator -># // expected-error {{'#' is not allowed in operator names}}
// FIXME: Ideally, we shouldn't emit the «consistent whitespace» diagnostic
// where = cannot possibly mean an assignment.
infix operator =#=
// expected-error@-1 {{'#' is not allowed in operator names}}
// expected-error@-2 {{'=' must have consistent whitespace on both sides}}
infix operator +++=
infix operator *** : A
infix operator --- : ; // expected-error {{expected precedence group name after ':' in operator declaration}}
precedencegroup { // expected-error {{expected identifier after 'precedencegroup'}}
associativity: right
}
precedencegroup A {
associativity right // expected-error {{expected colon after attribute name in precedence group}}
}
precedencegroup B {
precedence 123 // expected-error {{'precedence' is not a valid precedence group attribute}}
}
precedencegroup C {
associativity: sinister // expected-error {{expected 'none', 'left', or 'right' after 'associativity'}}
}
precedencegroup D {
assignment: no // expected-error {{expected 'true' or 'false' after 'assignment'}}
}
precedencegroup E {
higherThan:
} // expected-error {{expected name of related precedence group after 'higherThan'}}
precedencegroup F {
higherThan: A, B, C
}
precedencegroup BangBangBang {
associativity: none
associativity: left // expected-error{{'associativity' attribute for precedence group declared multiple times}}
}
precedencegroup CaretCaretCaret {
assignment: true
assignment: false // expected-error{{'assignment' attribute for precedence group declared multiple times}}
}
class Foo {
infix operator ||| // expected-error{{'operator' may only be declared at file scope}}
}
infix operator **<< : UndeclaredPrecedenceGroup
// expected-error@-1 {{unknown precedence group 'UndeclaredPrecedenceGroup'}}
protocol Proto {}
infix operator *<*< : F, Proto
// expected-error@-1 {{consecutive statements on a line must be separated by ';'}}
// expected-error@-2 {{expected expression}}
// https://github.com/apple/swift/issues/60932
// expected-error@+2 {{expected precedence group name after ':' in operator declaration}}
postfix operator ++: // expected-error {{only infix operators may declare a precedence}} {{20-21=}}
| apache-2.0 |
anasmeister/nRF-Coventry-University | nRF Toolbox/MainViewController/NORMainViewController.swift | 1 | 3369 | //
// NORMainViewController.swift
// nRF Toolbox
//
// Created by Mostafa Berg on 27/04/16.
// Copyright © 2016 Nordic Semiconductor. All rights reserved.
// Edited by Anastasios Panagoulias on 11/01/07
import UIKit
class NORMainViewController: UIViewController, UICollectionViewDataSource, UIAlertViewDelegate {
// MARK: - Outlets & Actions
@IBOutlet weak var collectionView: UICollectionView!
@IBAction func aboutButtonTapped(_ sender: AnyObject) {
showAboutAlertView()
}
// MARK: - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self;
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.lightContent, animated: true)
}
override func viewDidAppear(_ animated: Bool) {
let isUserLoggedIn = UserDefaults.standard.bool(forKey: "isUserLoggedIn")
if (!isUserLoggedIn){
self.performSegue(withIdentifier: "loginView", sender: self)
}
}
@IBAction func logoutButtonTapped(_ sender: Any) {
UserDefaults.standard.set(false, forKey: "isUserLoggedIn")
UserDefaults.standard.synchronize()
self.performSegue(withIdentifier: "loginView", sender: self)
}
func showAboutAlertView() {
//let appVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
//Note: The character \u{2022} found here is a unicode bullet, used just for styling purposes
let aboutMessage = String("This application is a creation of Anastasios Panagoulias on behalf of Coventry University and the Module M99 EKM of the academic year 2016-2017. This application is part of the Dissertation Module. Several parts of this application are taken from the nRF Toolbox official open source App. This application is designed to work with the most popular Low Energy Bluetooth accessories that use standard BLE profiles. This Application has been tested with the Nordic Semiconductor nRF 52 - DK. It supports Nordic Semiconductor's proprietary profiles:\n\n\u{2022}UART (Universal Asynchronous Receiver/Transmitter),\n\n\u{2022}DFU (Device Firmware Update).\n\nMore information and the source code may be found on GitHub.\n\nVersion 0.2")
let alertView = UIAlertView.init(title: "About", message: aboutMessage!, delegate: self, cancelButtonTitle: "Ok", otherButtonTitles:"GitHub")
alertView.show()
}
// MARK: - UIalertViewDelegate
func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) {
if buttonIndex == 1 {
UIApplication.shared.openURL(URL(string: "https://github.com/anasmeister/nRF-Coventry-University")!)
}
}
// MARK: - UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cellName = String(format: "profile_%d", (indexPath as NSIndexPath).item)
return collectionView.dequeueReusableCell(withReuseIdentifier: cellName, for: indexPath)
}
}
| bsd-3-clause |
ben-ng/swift | validation-test/compiler_crashers_fixed/00947-void.swift | 1 | 716 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
class b(f() {
}
return S) -> {
}
import Foundation
case b {
extension NSSet {
}
S.Type) -> (object1: d where T> Int = T> Bool {
}
struct c(bytes: Int][1])).Type) -> U)
}
var b = { c]
}
return self.Type) {
}
protocol a {
typealias e where T -> {
}
typealias B : B(t: A, A
func x: A.E == a: (["[Byte], "")
let t: b(i(x)
| apache-2.0 |
ben-ng/swift | validation-test/compiler_crashers_fixed/26238-swift-archetypebuilder-potentialarchetype-isbetterarchetypeanchor.swift | 1 | 451 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
protocol f{struct S<T:y}struct d{struct w{protocol c
| apache-2.0 |
ben-ng/swift | validation-test/compiler_crashers_fixed/27067-swift-valuedecl-settype.swift | 1 | 458 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
func c(){if true{class b<T where g:a{struct T{func f{{f<f w
| apache-2.0 |
cloudinary/cloudinary_ios | Cloudinary/Classes/Core/Features/CacheSystem/StorehouseLibrary/Enum/StorehouseError.swift | 1 | 1754 | //
// StorehouseError.swift
//
// Copyright (c) 2020 Cloudinary (http://cloudinary.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
///
///
///
internal enum StorehouseError : Error {
/// Object can not be found
case notFound
/// Object is found, but casting to requested type failed
case typeNotMatch
/// The file attributes are malformed
case malformedFileAttributes
/// Can't perform Decode
case decodingFailed
/// Can't perform Encode
case encodingFailed
// /// The storage has been deallocated
// case deallocated
//
// /// Fail to perform transformation to or from Data
// case transformerFail
}
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/15065-swift-sourcemanager-getmessage.swift | 11 | 248 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{
case
var
[ {
class
String {
{
}
let a {
for {
deinit {
func a {
class
case ,
| mit |
tlax/looper | looper/Model/Camera/Record/MCameraRecord.swift | 1 | 575 | import Foundation
class MCameraRecord
{
var items:[MCameraRecordItem]
init()
{
items = []
}
//MARK: public
func activeVersion() -> MCameraRecord?
{
var active:MCameraRecord?
for item:MCameraRecordItem in items
{
if item.active
{
if active == nil
{
active = MCameraRecord()
}
active!.items.append(item)
}
}
return active
}
}
| mit |
brentdax/swift | test/Driver/multi-threaded.swift | 1 | 4722 | // RUN: %empty-directory(%t)
// RUN: %target-swiftc_driver -driver-print-jobs -module-name=ThisModule -wmo -num-threads 4 %S/Inputs/main.swift %s -emit-module -o test.swiftmodule | %FileCheck -check-prefix=MODULE %s
// RUN: echo "{\"%s\": {\"assembly\": \"/build/multi-threaded.s\"}, \"%S/Inputs/main.swift\": {\"assembly\": \"/build/main.s\"}}" > %t/ofms.json
// RUN: %target-swiftc_driver -driver-print-jobs -module-name=ThisModule -wmo -num-threads 4 %S/Inputs/main.swift %s -output-file-map %t/ofms.json -S | %FileCheck -check-prefix=ASSEMBLY %s
// RUN: %target-swiftc_driver -driver-print-jobs -module-name=ThisModule -wmo -num-threads 4 %S/Inputs/main.swift %s -c | %FileCheck -check-prefix=OBJECT %s
// RUN: %target-swiftc_driver -parseable-output -module-name=ThisModule -wmo -num-threads 4 %S/Inputs/main.swift %s -c 2> %t/parseable-output
// RUN: cat %t/parseable-output | %FileCheck -check-prefix=PARSEABLE %s
// RUN: (cd %t && env TMPDIR=/tmp %swiftc_driver -driver-print-jobs -module-name=ThisModule -wmo -num-threads 4 %S/Inputs/main.swift %s -o a.out ) | %FileCheck -check-prefix=EXEC %s
// RUN: echo "{\"%s\": {\"llvm-bc\": \"multi-threaded.bc\", \"object\": \"%t/multi-threaded.o\"}, \"%S/Inputs/main.swift\": {\"llvm-bc\": \"main.bc\", \"object\": \"%t/main.o\"}}" > %t/ofmo.json
// RUN: %target-swiftc_driver -module-name=ThisModule -wmo -num-threads 4 %S/Inputs/main.swift %s -emit-dependencies -output-file-map %t/ofmo.json -c
// RUN: cat %t/*.d | %FileCheck -check-prefix=DEPENDENCIES %s
// Check if -embed-bitcode works
// RUN: %target-swiftc_driver -driver-print-jobs -module-name=ThisModule -embed-bitcode -wmo -num-threads 4 %S/Inputs/main.swift %s -output-file-map %t/ofmo.json -c | %FileCheck -check-prefix=BITCODE %s
// Check if -embed-bitcode works with -parseable-output
// RUN: %target-swiftc_driver -parseable-output -module-name=ThisModule -embed-bitcode -wmo -num-threads 4 %S/Inputs/main.swift %s -output-file-map %t/ofmo.json -c 2> %t/parseable2
// RUN: cat %t/parseable2 | %FileCheck -check-prefix=PARSEABLE2 %s
// Check if linking works with -parseable-output
// RUN: (cd %t && %target-swiftc_driver -parseable-output -module-name=ThisModule -wmo -num-threads 4 %S/Inputs/main.swift %s -output-file-map %t/ofmo.json -o a.out) 2> %t/parseable3
// RUN: cat %t/parseable3 | %FileCheck -check-prefix=PARSEABLE3 %s
// MODULE: -frontend
// MODULE-DAG: -num-threads 4
// MODULE-DAG: {{[^ ]*}}/Inputs/main.swift {{[^ ]*}}/multi-threaded.swift
// MODULE-DAG: -o test.swiftmodule
// MODULE-NOT: ld
// ASSEMBLY: -frontend
// ASSEMBLY-DAG: -num-threads 4
// ASSEMBLY-DAG: {{[^ ]*}}/Inputs/main.swift {{[^ ]*}}/multi-threaded.swift
// ASSEMBLY-DAG: -o /build/main.s -o /build/multi-threaded.s
// ASSEMBLY-NOT: ld
// OBJECT: -frontend
// OBJECT-DAG: -num-threads 4
// OBJECT-DAG: {{[^ ]*}}/Inputs/main.swift {{[^ ]*}}/multi-threaded.swift
// OBJECT-DAG: -o main.o -o multi-threaded.o
// OBJECT-NOT: ld
// BITCODE: -frontend
// BITCODE-DAG: -num-threads 4
// BITCODE-DAG: {{[^ ]*}}/Inputs/main.swift {{[^ ]*}}/multi-threaded.swift
// BITCODE-DAG: -o main.bc -o multi-threaded.bc
// BITCODE-DAG: -frontend -c -primary-file main.bc {{.*}} -o {{[^ ]*}}main.o
// BITCODE-DAG: -frontend -c -primary-file multi-threaded.bc {{.*}} -o {{[^ ]*}}multi-threaded.o
// BITCODE-NOT: ld
// PARSEABLE: "outputs": [
// PARSEABLE: "path": "main.o"
// PARSEABLE: "path": "multi-threaded.o"
// EXEC: -frontend
// EXEC-DAG: -num-threads 4
// EXEC-DAG: {{[^ ]*}}/Inputs/main.swift {{[^ ]*}}/multi-threaded.swift
// EXEC-DAG: -o /tmp/main{{[^ ]*}}.o -o /tmp/multi-threaded{{[^ ]*}}.o
// EXEC: ld
// EXEC: /tmp/main{{[^ ]*}}.o /tmp/multi-threaded{{[^ ]*}}.o
// DEPENDENCIES-DAG: {{.*}}/multi-threaded.o : {{.*}}/multi-threaded.swift {{.*}}/Inputs/main.swift
// DEPENDENCIES-DAG: {{.*}}/main.o : {{.*}}/multi-threaded.swift {{.*}}/Inputs/main.swift
// PARSEABLE2: "name": "compile"
// PARSEABLE2: "outputs": [
// PARSEABLE2: "path": "main.bc"
// PARSEABLE2: "path": "multi-threaded.bc"
// PARSEABLE2: "name": "backend"
// PARSEABLE2: "inputs": [
// PARSEABLE2: "main.bc"
// PARSEABLE2: "outputs": [
// PARSEABLE2: "path": "{{.*}}/main.o"
// PARSEABLE2: "name": "backend"
// PARSEABLE2: "inputs": [
// PARSEABLE2: "multi-threaded.bc"
// PARSEABLE2: "outputs": [
// PARSEABLE2: "path": "{{.*}}/multi-threaded.o"
// PARSEABLE3: "name": "compile"
// PARSEABLE3: "outputs": [
// PARSEABLE3: "path": "{{.*}}/main.o"
// PARSEABLE3: "path": "{{.*}}/multi-threaded.o"
// PARSEABLE3: "name": "link"
// PARSEABLE3: "inputs": [
// PARSEABLE3-NEXT: "{{.*}}/main.o"
// PARSEABLE3-NEXT: "{{.*}}/multi-threaded.o"
// PARSEABLE3: "outputs": [
// PARSEABLE3: "path": "a.out"
func libraryFunction() {}
| apache-2.0 |
DaiYue/HAMLeetcodeSwiftSolutions | solutions/31_Next_Permutation.playground/Contents.swift | 1 | 1792 | // #31 Next Permutation https://leetcode.com/problems/next-permutation/
// 代码写起来很简单,数学推导稍微多一些。方法如下:
// 从右往左找第一个比右边小的数字(如果找不到,逆转整个数组即可),其 index 为 leftNumIndex。再找它右边比它大的数字(一定存在)里最小的,由于右边是降序,从右往左找的第一个即是,index 为 rightNumIndex。swap 两个 index 的 num。
// leftNumIndex 左边是不变的,下面看右边。右边本来是降序,能保证 swap 过后也是(不严格的)降序。换成升序,只需逆转这部分。
// 时间复杂度:O(n) 空间复杂度:O(1)
class Solution {
func nextPermutation(_ nums: inout [Int]) {
var leftNumIndex = -1
for (index, num) in nums.enumerated().reversed() {
if index != nums.count - 1 && num < nums[index + 1] {
leftNumIndex = index
break
}
}
if leftNumIndex == -1 {
reverse(&nums, fromIndex: 0)
return
}
var rightNumIndex = -1
for (index, num) in nums.enumerated().reversed() {
if num > nums[leftNumIndex] {
rightNumIndex = index
break
}
}
swap(&nums[leftNumIndex], &nums[rightNumIndex])
reverse(&nums, fromIndex: leftNumIndex + 1)
}
func reverse(_ nums: inout [Int], fromIndex: Int) {
var leftIndex = fromIndex, rightIndex = nums.count - 1
while leftIndex < rightIndex {
swap(&nums[leftIndex], &nums[rightIndex])
leftIndex += 1
rightIndex -= 1
}
}
}
var nums = [3, 1, 2]
Solution().nextPermutation(&nums)
nums | mit |
alexsteinerde/KHAForm | KHAForm/KHAPickerFormCell.swift | 1 | 1674 | //
// KHAPickerFormCell.swift
// Pods
//
// Created by Alex on 06.09.17.
//
//
import UIKit
class KHAPickerFormCell: KHAFormCell {
class var cellID: String {
return "KHAPickerCell"
}
fileprivate let kCellHeight: CGFloat = 216
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
frame = CGRect(
x: frame.origin.x,
y: frame.origin.y,
width: frame.width,
height: kCellHeight)
pickerView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(pickerView)
contentView.addConstraints([
NSLayoutConstraint(
item: pickerView,
attribute: .left,
relatedBy: .equal,
toItem: contentView,
attribute: .left,
multiplier: 1,
constant: 0),
NSLayoutConstraint(
item: pickerView,
attribute: .right,
relatedBy: .equal,
toItem: contentView,
attribute: .right,
multiplier: 1,
constant: 0),
NSLayoutConstraint(
item: pickerView,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: kCellHeight)]
)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit |
tkremenek/swift | validation-test/compiler_crashers_fixed/28707-false-encountered-error-in-diagnostic-text.swift | 40 | 440 | // 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
// RUN: not %target-swift-frontend %s -emit-ir
class a{@usableFromInline
public
protocol r
| apache-2.0 |
Vespen/SimpleJson | Tests/Features/Json+Number.swift | 1 | 4867 | //
// Json+Number.swift
//
// Copyright (c) 2017 Anton Lagutin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import XCTest
import KnfaJson
/// `JsonNumberTestCase` class.
final class JsonNumberTestCase: BaseTestCase {
/// Tests `asNumber()`.
func testAsNumber() throws {
let jsonPath: JsonPath = "0.location.0"
XCTAssertNoThrow(try json.json(at: jsonPath).asNumber())
if let number = try? json.json(at: jsonPath).asNumber() {
XCTAssertEqual(number.doubleValue, 40.730610, accuracy: 1e-6)
}
XCTAssertThrowsError(try json.json(at: 0).asNumber())
}
/// Tests `asInt()`.
func testAsInt() throws {
let jsonPath: JsonPath = "0.population"
XCTAssertNoThrow(try json.json(at: jsonPath).asInt())
if let population = try? json.json(at: jsonPath).asInt() {
XCTAssertEqual(population, 8537673)
}
XCTAssertThrowsError(try json.json(at: 0).asInt())
}
/// Tests `asFloat()`.
func testAsFloat() throws {
let jsonPath: JsonPath = "0.location.0"
XCTAssertNoThrow(try json.json(at: jsonPath).asFloat())
if let float = try? json.json(at: jsonPath).asFloat() {
XCTAssertEqual(float, 40.730610, accuracy: 1e-6)
}
XCTAssertThrowsError(try json.json(at: 0).asFloat())
}
/// Tests `asDouble()`.
func testAsDouble() throws {
let jsonPath: JsonPath = "0.location.0"
XCTAssertNoThrow(try json.json(at: jsonPath).asDouble())
if let double = try? json.json(at: jsonPath).asDouble() {
XCTAssertEqual(double, 40.730610, accuracy: 1e-6)
}
XCTAssertThrowsError(try json.json(at: 0).asDouble())
}
/// Tests `asBool()`.
func testAsBool() throws {
let jsonPath: JsonPath = "0.favorite"
XCTAssertNoThrow(try json.json(at: jsonPath).asBool())
if let bool = try? json.json(at: jsonPath).asBool() {
XCTAssertEqual(bool, true)
}
XCTAssertThrowsError(try json.json(at: 0).asBool())
}
/// Tests `number(at:)`.
func testNumberAt() throws {
let jsonPath: JsonPath = "0.location.0"
XCTAssertNoThrow(try json.number(at: jsonPath))
if let number = try? json.number(at: jsonPath) {
XCTAssertEqual(number.doubleValue, 40.730610, accuracy: 1e-6)
}
XCTAssertThrowsError(try json.number(at: 0))
}
/// Tests `int(at:)`.
func testIntAt() throws {
let jsonPath: JsonPath = "0.population"
XCTAssertNoThrow(try json.int(at: jsonPath))
if let population = try? json.int(at: jsonPath) {
XCTAssertEqual(population, 8537673)
}
XCTAssertThrowsError(try json.int(at: 0))
}
/// Tests `float(at:)`.
func testFloatAt() throws {
let jsonPath: JsonPath = "0.location.0"
XCTAssertNoThrow(try json.float(at: jsonPath))
if let float = try? json.float(at: jsonPath) {
XCTAssertEqual(float, 40.730610, accuracy: 1e-6)
}
XCTAssertThrowsError(try json.float(at: 0))
}
/// Tests `double(at:)`.
func testDoubleAt() throws {
let jsonPath: JsonPath = "0.location.0"
XCTAssertNoThrow(try json.double(at: jsonPath))
if let double = try? json.double(at: jsonPath) {
XCTAssertEqual(double, 40.730610, accuracy: 1e-6)
}
XCTAssertThrowsError(try json.double(at: 0))
}
/// Tests `bool(at:)`.
func testBoolAt() throws {
let jsonPath: JsonPath = "0.favorite"
XCTAssertNoThrow(try json.bool(at: jsonPath))
if let bool = try? json.bool(at: jsonPath) {
XCTAssertEqual(bool, true)
}
XCTAssertThrowsError(try json.bool(at: 0))
}
}
| mit |
APUtils/APExtensions | APExtensions/Classes/Core/_Extensions/_Foundation/UInt+Utils.swift | 1 | 856 | //
// UInt+Utils.swift
// APExtensions-example
//
// Created by Anton Plebanovich on 4/3/21.
// Copyright © 2021 Anton Plebanovich. All rights reserved.
//
import Foundation
public extension UInt {
/// Returns `self` as `Int` if possible
var asInt: Int? { Int(exactly: self) }
/// Returns `self` as `CGFloat`
var asCGFloat: CGFloat { .init(self) }
/// Returns `self` as `Double`
var asDouble: Double { .init(self) }
/// Returns `self` as `Float`
var asFloat: Float { .init(self) }
/// Returns `self` as `String`
var asString: String { .init(self) }
/// Returns `self` as HEX `String` in a format like `0xAABB11`
var asHexString: String { .init(format: "0x%02X", self) }
/// Returns `self` as `TimeInterval`
var asTimeInterval: TimeInterval { .init(self) }
}
| mit |
aptyr/-github-iOS | #github-ios/presenter/LoginPresentable.swift | 1 | 298 | //
// LoginPresenter.swift
// #github-ios
//
// Created by Artur on 05/04/2017.
// Copyright © 2017 Artur Matusiak. All rights reserved.
//
import Foundation
protocol LoginPresentable : class, BasePresenter {
init(view: LoginView)
func obtain(accessToken: AccessToken)
}
| apache-2.0 |
midoks/Swift-Learning | GitHubStar/GitHubStar/GitHubStar/Vendor/MDDropDownList/MDDropDownList.swift | 1 | 7663 | //
//
// Created by midoks on 15/12/30.
// Copyright © 2015年 midoks. All rights reserved.
//
import UIKit
class MDDropDownBackView:UIView {
var _backView:UIView?
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clear
//背景色
_backView = UIView(frame: frame)
_backView!.backgroundColor = UIColor.black
_backView!.layer.opacity = 0.2
addSubview(_backView!)
let tap = UITapGestureRecognizer(target: self, action: #selector(self.tap))
self.addGestureRecognizer(tap)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//点击消失
func tap(){
UIView.animate(withDuration: 0.25, delay: 0,
options: UIViewAnimationOptions.curveLinear,
animations: { () -> Void in
self.layer.opacity = 0.0
}) { (status) -> Void in
self.hide()
self.layer.opacity = 1
}
}
func hide(){
self.removeFromSuperview()
}
override func layoutSubviews() {
super.layoutSubviews()
self._backView?.frame = frame
}
}
class MDDropDownListView:UIView {
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//下拉类
class MDDropDownList : UIView {
var listClick:(( _ tag:Int) -> ())?
var bbView:MDDropDownBackView?
var listView:UIView?
var listButton: Array<UIButton> = Array<UIButton>()
var listTriangleButton:UIButton?
var listSize:CGSize = CGSize(width: 150.0, height: 50.0)
var listImageSize:CGSize = CGSize(width: 40.0, height: 30.0)
var navHeight:CGFloat = 64.0
override init(frame: CGRect) {
super.init(frame:frame)
self.bbView = MDDropDownBackView(frame: frame)
self.listView = MDDropDownListView(frame: CGRect(x: frame.width - self.listSize.width - 5, y: self.navHeight, width: self.listSize.width, height: 0))
self.listView!.backgroundColor = UIColor.white
self.listView!.layer.cornerRadius = 3
self.bbView?.addSubview(self.listView!)
self.listTriangleButton = UIButton(frame: CGRect(x: frame.width - 33, y: self.navHeight - 13, width: 15, height: 15))
self.listTriangleButton?.setTitle("▲", for: .normal)
self.listTriangleButton?.titleLabel?.font = UIFont.boldSystemFont(ofSize: 15.0)
self.bbView?.addSubview(self.listTriangleButton!)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//重新设置位置
func setViewFrame(frame: CGRect){
if UIDevice.current.orientation.isLandscape {
self.listView?.frame = CGRect(x: frame.width - self.listSize.width - 5, y: self.navHeight+1, width: self.listSize.width, height: self.listView!.frame.height)
self.listTriangleButton?.frame = CGRect(x: frame.width - 35, y: self.navHeight - 11, width: 15, height: 15)
} else {
self.listView?.frame = CGRect(x: frame.width - self.listSize.width - 5, y: self.navHeight, width: self.listSize.width, height: self.listView!.frame.height)
self.listTriangleButton?.frame = CGRect(x: frame.width - 33, y: self.navHeight - 12, width: 15, height: 15)
}
self.bbView?.frame = frame
self.frame = frame
}
//MARK: - Private Methods -
//生成纯色背景
func imageWithColor(color:UIColor, size: CGSize) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: size.height, height: size.height)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context!.setFillColor(color.cgColor)
context!.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
//点击
func listClick(s:UIButton){
//if listClick != nil {
//listClick?(tag: s.tag)
//}
// self.hide()
// self.touchDragOutside(s: s)
}
//鼠标按下操作
func touchDown(s:UIButton){
//s.backgroundColor = UIColor(red: 239/255, green: 239/255, blue: 244/255, alpha: 1)
}
//鼠标按下离开操作
func touchDragOutside(s:UIButton){
s.backgroundColor = UIColor.white
}
//添加按钮
func add(icon:UIImage, title:String){
let c = self.listButton.count
let bheight = self.listSize.height * CGFloat(c)
let bbViewHeight = self.listSize.height * CGFloat(c+1)
self.listView?.frame = CGRect(x: (self.listView?.frame.origin.x)!, y: (self.listView?.frame.origin.y)!, width: (self.listView?.frame.size.width)!, height: bbViewHeight)
let u = UIButton(frame: CGRect(x: 0, y: bheight, width: self.listSize.width, height: self.listSize.height))
u.tag = c
u.setImage(icon, for: .normal)
u.setImage(icon, for: .highlighted)
u.setTitle(title, for: .normal)
u.setTitleColor(UIColor.black, for: .normal)
u.layer.cornerRadius = 3
u.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14.0)
u.backgroundColor = UIColor.white
u.contentHorizontalAlignment = .left
u.imageEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 0)
u.titleEdgeInsets = UIEdgeInsetsMake(0, 40, 0, 0)
u.addTarget(self, action: Selector(("listClick:")), for: UIControlEvents.touchUpInside)
// u.addTarget(self, action: "touchDown:", for: UIControlEvents.touchDown)
// u.addTarget(self, action: "touchDragOutside:", for: UIControlEvents.touchDragOutside)
if ( c>0 ) {
let line = UIView(frame: CGRect(x: 0, y: 0, width: u.frame.width, height: 1))
line.backgroundColor = UIColor(red: 239/255, green: 239/255, blue: 244/255, alpha: 1)
u.addSubview(line)
}
self.listView!.addSubview(u)
self.listButton.append(u)
}
//动画显示特效
func showAnimation(){
UIApplication.shared.windows.first?.addSubview(self.bbView!)
let sFrame = self.listView?.frame
self.listView?.frame.size = CGSize(width: 0.0, height: 0.0)
self.listView?.frame.origin.x = sFrame!.origin.x + (sFrame?.width)!
self.listView?.layer.opacity = 0
self.listTriangleButton?.layer.opacity = 0
UIView.animate(withDuration: 0.3, delay: 0, options: UIViewAnimationOptions.curveLinear, animations: { () -> Void in
self.listView?.frame.size.height += sFrame!.size.height
self.listView?.frame.origin.x -= (sFrame?.width)!
self.listView?.layer.opacity = 1
self.listTriangleButton?.layer.opacity = 0.6
}) { (status) -> Void in
self.listView?.layer.opacity = 1
self.listTriangleButton?.layer.opacity = 1
self.listView?.frame = sFrame!
}
}
//隐藏
func hide(){
self.bbView!.removeFromSuperview()
}
}
| apache-2.0 |
cdmx/MiniMancera | miniMancera/View/Option/TamalesOaxaquenos/Physic/VOptionTamalesOaxaquenosPhysicFinish.swift | 1 | 1597 | import SpriteKit
class VOptionTamalesOaxaquenosPhysicFinish:ViewGameNode<MOptionTamalesOaxaquenos>
{
private let positionX:CGFloat
private let height:CGFloat
private let width_2:CGFloat
private let height_2:CGFloat
private let kWidth:CGFloat = 250
override init(controller:ControllerGame<MOptionTamalesOaxaquenos>)
{
let areaWidth:CGFloat = MOptionTamalesOaxaquenosArea.kWidth
height = MGame.sceneSize.height
let size:CGSize = CGSize(
width:kWidth,
height:height)
width_2 = kWidth / 2.0
height_2 = height / 2.0
positionX = areaWidth - width_2
super.init(
controller:controller,
size:size,
zPosition:MOptionTamalesOaxaquenosZPosition.Physics.rawValue)
startPhysics()
}
required init?(coder:NSCoder)
{
return nil
}
//MARK: private
override func positionStart()
{
position = CGPoint(x:positionX, y:height_2)
}
private func startPhysics()
{
let edgeFrame:CGRect = CGRect(
x:-width_2,
y:-height_2,
width:kWidth,
height:height)
let physicsBody:SKPhysicsBody = SKPhysicsBody(edgeLoopFrom:edgeFrame)
physicsBody.categoryBitMask = MOptionTamalesOaxaquenosPhysicsStruct.Finish
physicsBody.contactTestBitMask = MOptionTamalesOaxaquenosPhysicsStruct.Player
physicsBody.collisionBitMask = MOptionTamalesOaxaquenosPhysicsStruct.None
self.physicsBody = physicsBody
}
}
| mit |
mrdepth/EVEUniverse | Legacy/Neocom/Neocom/MapLocationPickerPresenter.swift | 2 | 524 | //
// MapLocationPickerPresenter.swift
// Neocom
//
// Created by Artem Shimanski on 9/27/18.
// Copyright © 2018 Artem Shimanski. All rights reserved.
//
import Foundation
class MapLocationPickerPresenter: Presenter {
typealias View = MapLocationPickerViewController
typealias Interactor = MapLocationPickerInteractor
weak var view: View?
lazy var interactor: Interactor! = Interactor(presenter: self)
required init(view: View) {
self.view = view
}
func configure() {
interactor.configure()
}
}
| lgpl-2.1 |
lieonCX/Live | Live/View/Home/Room/CollectionLiveTagView.swift | 1 | 2317 | //
// CollectionLiveTagView.swift
// Live
//
// Created by fanfans on 2017/7/4.
// Copyright © 2017年 ChengDuHuanLeHui. All rights reserved.
//
import UIKit
class CollectionLiveTagView: UIView {
fileprivate lazy var bgView: UIView = {
let bgView = UIView()
self.backgroundColor = UIColor.black .withAlphaComponent(0.6)
return bgView
}()
fileprivate lazy var statusLabel: UILabel = {
let statusLabel = UILabel()
statusLabel.font = UIFont.systemFont(ofSize: 11)
statusLabel.textColor = UIColor.white
statusLabel.textAlignment = .center
return statusLabel
}()
fileprivate lazy var statusView: UIView = {
let statusView = UIView()
statusView.layer.cornerRadius = 5 * 0.5
statusView.layer.masksToBounds = true
return statusView
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.layer.borderWidth = 0.5
self.layer.borderColor = UIColor.white.cgColor
self.layer.cornerRadius = 16 * 0.5
self.layer.masksToBounds = true
self.addSubview(bgView)
self.addSubview(statusView)
self.addSubview(statusLabel)
bgView.snp.makeConstraints { (maker) in
maker.left.equalTo(0)
maker.right.equalTo(0)
maker.top.equalTo(0)
maker.bottom.equalTo(0)
}
statusView.snp.makeConstraints { (maker) in
maker.centerY.equalTo(bgView.snp.centerY)
maker.left.equalTo(3)
maker.width.equalTo(5)
maker.height.equalTo(5)
}
statusLabel.snp.makeConstraints { (maker) in
maker.left.equalTo(5)
maker.right.equalTo(0)
maker.top.equalTo(0)
maker.bottom.equalTo(0)
}
}
func configWithListLiveType(type: ListLiveType) {
if type == .living {
statusLabel.text = "直播中"
statusView.backgroundColor = UIColor(hex: CustomKey.Color.mainColor)
} else {
statusLabel.text = "回放中"
statusView.backgroundColor = UIColor(hex:0x14eff)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit |
ddddxxx/LyricsX | LyricsX/Controller/MenuBarLyricsController.swift | 2 | 5172 | //
// MenuBarLyrics.swift
// LyricsX - https://github.com/ddddxxx/LyricsX
//
// 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 https://mozilla.org/MPL/2.0/.
//
import Cocoa
import CXExtensions
import CXShim
import GenericID
import LyricsCore
import MusicPlayer
import OpenCC
import SwiftCF
import AccessibilityExt
class MenuBarLyricsController {
static let shared = MenuBarLyricsController()
let statusItem: NSStatusItem
var lyricsItem: NSStatusItem?
var buttonImage = #imageLiteral(resourceName: "status_bar_icon")
var buttonlength: CGFloat = 30
private var screenLyrics = "" {
didSet {
DispatchQueue.main.async {
self.updateStatusItem()
}
}
}
private var cancelBag = Set<AnyCancellable>()
private init() {
statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
AppController.shared.$currentLyrics
.combineLatest(AppController.shared.$currentLineIndex)
.receive(on: DispatchQueue.lyricsDisplay.cx)
.invoke(MenuBarLyricsController.handleLyricsDisplay, weaklyOn: self)
.store(in: &cancelBag)
workspaceNC.cx
.publisher(for: NSWorkspace.didActivateApplicationNotification)
.signal()
.invoke(MenuBarLyricsController.updateStatusItem, weaklyOn: self)
.store(in: &cancelBag)
defaults.publisher(for: [.menuBarLyricsEnabled, .combinedMenubarLyrics])
.prepend()
.invoke(MenuBarLyricsController.updateStatusItem, weaklyOn: self)
.store(in: &cancelBag)
}
private func handleLyricsDisplay(event: (lyrics: Lyrics?, index: Int?)) {
guard !defaults[.disableLyricsWhenPaused] || selectedPlayer.playbackState.isPlaying,
let lyrics = event.lyrics,
let index = event.index else {
screenLyrics = ""
return
}
var newScreenLyrics = lyrics.lines[index].content
if let converter = ChineseConverter.shared, lyrics.metadata.language?.hasPrefix("zh") == true {
newScreenLyrics = converter.convert(newScreenLyrics)
}
if newScreenLyrics == screenLyrics {
return
}
screenLyrics = newScreenLyrics
}
@objc private func updateStatusItem() {
guard defaults[.menuBarLyricsEnabled], !screenLyrics.isEmpty else {
setImageStatusItem()
lyricsItem = nil
return
}
if defaults[.combinedMenubarLyrics] {
updateCombinedStatusLyrics()
} else {
updateSeparateStatusLyrics()
}
}
private func updateSeparateStatusLyrics() {
setImageStatusItem()
if lyricsItem == nil {
lyricsItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
lyricsItem?.highlightMode = false
}
lyricsItem?.title = screenLyrics
}
private func updateCombinedStatusLyrics() {
lyricsItem = nil
setTextStatusItem(string: screenLyrics)
if statusItem.isVisibe {
return
}
// truncation
var components = screenLyrics.components(options: [.byWords])
while !components.isEmpty, !statusItem.isVisibe {
components.removeLast()
let proposed = components.joined() + "..."
setTextStatusItem(string: proposed)
}
}
private func setTextStatusItem(string: String) {
statusItem.title = string
statusItem.image = nil
statusItem.length = NSStatusItem.variableLength
}
private func setImageStatusItem() {
statusItem.title = ""
statusItem.image = buttonImage
statusItem.length = buttonlength
}
}
// MARK: - Status Item Visibility
private extension NSStatusItem {
var isVisibe: Bool {
guard let buttonFrame = button?.frame,
let frame = button?.window?.convertToScreen(buttonFrame) else {
return false
}
let point = CGPoint(x: frame.midX, y: frame.midY)
guard let screen = NSScreen.screens.first(where: { $0.frame.contains(point) }) else {
return false
}
let carbonPoint = CGPoint(x: point.x, y: screen.frame.height - point.y - 1)
guard let element = try? AXUIElement.systemWide().element(at: carbonPoint),
let pid = try? element.pid() else {
return false
}
return getpid() == pid
}
}
private extension String {
func components(options: String.EnumerationOptions) -> [String] {
var components: [String] = []
let range = Range(uncheckedBounds: (startIndex, endIndex))
enumerateSubstrings(in: range, options: options) { _, _, range, _ in
components.append(String(self[range]))
}
return components
}
}
| mpl-2.0 |
emadhegab/GenericDataSource | Example/Example/TitleCollectionViewCell.swift | 2 | 447 | //
// TitleCollectionViewCell.swift
// Example
//
// Created by Mohamed Afifi on 4/3/16.
// Copyright © 2016 Mohamed Afifi. All rights reserved.
//
import UIKit
class TitleCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var textLabel: UILabel?
override func awakeFromNib() {
super.awakeFromNib()
contentView.layer.borderColor = UIColor.lightGray.cgColor
contentView.layer.borderWidth = 1
}
}
| mit |
luckymore0520/GreenTea | Loyalty/Cards/Model/Card.swift | 1 | 3017 | //
// Card.swift
// Loyalty
//
// Created by WangKun on 16/4/29.
// Copyright © 2016年 WangKun. All rights reserved.
//
import UIKit
import AVOSCloud
class Card: AVObject,AVSubclassing {
@NSManaged var activity:Activity
@NSManaged var ownerId:String
@NSManaged var currentCount:Int
func getFullInfo(){
let query = Activity.query()
query.getObjectInBackgroundWithId(self.activity.objectId) { (activity, error) in
if let activity = activity as? Activity {
self.activity = activity
}
}
}
var isFull:Bool {
return activity.loyaltyCoinMaxCount == self.currentCount
}
static func parseClassName() -> String! {
return "Card"
}
}
extension Card {
func collect(code:String, completionHandler:(success:Bool)->Void) {
if self.currentCount == self.activity.loyaltyCoinMaxCount {
completionHandler(success: false)
} else {
Coin.checkCode(self.activity, code: code, completionHandler: { (success) in
if success {
self.currentCount += 1
self.saveInBackgroundWithBlock({ (success, error) in
completionHandler(success: success)
})
} else {
completionHandler(success: false)
}
})
}
}
static func queryCardWithId(objectId:String, completionHandler:Card?->Void) {
let query = Card.query()
query.includeKey("activity")
query.getObjectInBackgroundWithId(objectId) { (card, error) in
if let card = card as? Card {
completionHandler(card)
} else {
completionHandler(nil)
}
}
}
static func queryCardsOfUser(userName:String,completionHandler:[Card]->Void) {
let query = Card.query()
query.whereKey("ownerId", equalTo: userName)
query.includeKey("activity")
query.findObjectsInBackgroundWithBlock { (cards, error) in
if cards.count > 0 {
let cardList = cards as! [Card]
completionHandler(cardList)
}
}
}
static func obtainNewCard(activity:Activity, completionHandler:(card:Card?,errorMsg:String?) -> Void) {
guard let user = UserInfoManager.sharedManager.currentUser else {
completionHandler(card: nil, errorMsg: "登录后才能领取集点卡")
return
}
let card = Card()
card.activity = activity
card.ownerId = user.username
card.currentCount = 0
card.saveInBackgroundWithBlock { (success, error) in
if success {
user.addNewCard(card)
completionHandler(card: card,errorMsg: nil)
} else {
completionHandler(card: nil, errorMsg: NSError.errorMsg(error))
}
}
}
} | mit |
lorentey/swift | test/decl/protocol/req/where_clause.swift | 36 | 907 | // RUN: %target-typecheck-verify-swift
// rdar://problem/31401161
class C1 {}
protocol P1 {
associatedtype Element
}
protocol P2 : P1 {
associatedtype SubSequence : P1 // expected-note{{'SubSequence' declared here}}
}
protocol P3 : P2 {
associatedtype SubSequence : P2 // expected-warning{{redeclaration of associated type 'SubSequence' from protocol 'P2' is better expressed as a 'where' clause on the protocol}}
}
func foo<S>(_: S) where S.SubSequence.Element == C1, S : P3 {}
protocol SelfWhereClause where Self: AnyObject {}
func takesAnyObject<T : AnyObject>(_: T) {}
func takesSelfWhereClause<T : SelfWhereClause>(_ t: T) {
takesAnyObject(t)
}
class AlsoBad {}
protocol InvalidWhereClause2 {
associatedtype T where Self: AlsoBad
// expected-error@-1 {{constraint with subject type of 'Self' is not supported; consider adding requirement to protocol inheritance clause instead}}
}
| apache-2.0 |
Rapid-SDK/ios | Examples/RapiDO - ToDo list/RapiDO iOS/ListViewController.swift | 1 | 9786 | //
// ListViewController.swift
// ExampleApp
//
// Created by Jan on 05/05/2017.
// Copyright © 2017 Rapid. All rights reserved.
//
import UIKit
import Rapid
class ListViewController: UIViewController {
var searchedTerm = ""
var searchTimer: Timer?
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var orderButton: UIBarButtonItem!
@IBOutlet weak var filterButton: UIBarButtonItem!
fileprivate var tasks: [Task] = []
fileprivate var subscription: RapidSubscription?
fileprivate var ordering = RapidOrdering(keyPath: Task.createdAttributeName, ordering: .descending)
fileprivate var filter: RapidFilter?
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
subscribe()
}
// MARK: Actions
@IBAction func addTask(_ sender: Any) {
presentNewTaskController()
}
@objc func showOrderModal(_ sender: Any) {
presentOrderModal()
}
@objc func showFilterModal(_ sender: Any) {
presentFilterModal()
}
}
fileprivate extension ListViewController {
func setupUI() {
navigationController?.navigationBar.prefersLargeTitles = true
let searchController = UISearchController(searchResultsController: nil)
searchController.delegate = self
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
definesPresentationContext = true
navigationItem.searchController = searchController
navigationItem.title = "Tasks"
navigationItem.largeTitleDisplayMode = .always
tableView.dataSource = self
tableView.delegate = self
tableView.separatorColor = .appSeparator
tableView.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
tableView.estimatedRowHeight = 100
tableView.rowHeight = UITableViewAutomaticDimension
orderButton.target = self
orderButton.action = #selector(self.showOrderModal(_:))
filterButton.target = self
filterButton.action = #selector(self.showFilterModal(_:))
}
/// Subscribe to a collection
func subscribe() {
// If there is a previous subscription then unsubscribe from it
subscription?.unsubscribe()
tasks.removeAll()
tableView.reloadData()
// Get Rapid collection reference with a given name
var collection = Rapid.collection(named: Constants.collectionName)
// If a filter is set, modify the collection reference with it
if let filter = filter {
// If the search bar text is not empty, filter also by the text
if !searchedTerm.isEmpty {
// The search bar text can be in a title or in a description
// Combine two "CONTAINS" filters with logical "OR"
let combinedFilter = RapidFilter.or([
RapidFilter.contains(keyPath: Task.titleAttributeName, subString: searchedTerm),
RapidFilter.contains(keyPath: Task.descriptionAttributeName, subString: searchedTerm)
])
// And then, combine the search bar text filter with a filter from the filter modal
collection.filtered(by: RapidFilter.and([filter, combinedFilter]))
}
else {
// Associate the collection reference with the filter
collection.filtered(by: filter)
}
}
// If the searchBar text is not empty, filter by the text
else if !searchedTerm.isEmpty {
let combinedFilter = RapidFilter.or([
RapidFilter.contains(keyPath: Task.titleAttributeName, subString: searchedTerm),
RapidFilter.contains(keyPath: Task.descriptionAttributeName, subString: searchedTerm)
])
collection.filtered(by: combinedFilter)
}
// Order the collection by a given ordering
// Subscribe to the collection
// Store a subscribtion reference to be able to unsubscribe from it
subscription = collection.order(by: ordering).subscribeWithChanges { result in
switch result {
case .success(let changes):
let (documents, insert, update, delete) = changes
let previousSet = self.tasks
self.tasks = documents.flatMap({ Task(withSnapshot: $0) })
self.tableView.animateChanges(previousData: previousSet, data: self.tasks, new: insert, updated: update, deleted: delete)
case .failure:
self.tasks = []
self.tableView.reloadData()
}
}
}
func presentNewTaskController() {
let controller = self.storyboard!.instantiateViewController(withIdentifier: "TaskNavigationViewController")
present(controller, animated: true, completion: nil)
}
func presentOrderModal() {
let controller = self.storyboard?.instantiateViewController(withIdentifier: "OrderViewController") as! OrderViewController
controller.delegate = self
controller.ordering = ordering
controller.modalPresentationStyle = .custom
controller.modalTransitionStyle = .crossDissolve
present(controller, animated: true, completion: nil)
}
func presentFilterModal() {
let controller = self.storyboard?.instantiateViewController(withIdentifier: "FilterViewController") as! FilterViewController
controller.delegate = self
controller.filter = filter
controller.modalPresentationStyle = .custom
controller.modalTransitionStyle = .crossDissolve
present(controller, animated: true, completion: nil)
}
func presentEditTask(_ task: Task) {
let controller = self.storyboard?.instantiateViewController(withIdentifier: "TaskViewController") as! TaskViewController
controller.task = task
navigationController?.pushViewController(controller, animated: true)
}
}
// MARK: Table view
extension ListViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tasks.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TaskCell", for: indexPath) as! TaskCell
let task = tasks[indexPath.row]
cell.configure(withTask: task, delegate: self)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let task = tasks[indexPath.row]
presentEditTask(task)
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let action = UIContextualAction(style: .destructive, title: "Delete") { (_, _, completion) in
let task = self.tasks[indexPath.row]
task.delete()
}
action.backgroundColor = .appRed
return UISwipeActionsConfiguration(actions: [action])
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let task = tasks[indexPath.row]
task.delete()
}
}
}
extension ListViewController: TaskCellDelegate {
func cellCheckmarkChanged(_ cell: TaskCell, value: Bool) {
if let indexPath = tableView.indexPath(for: cell) {
let task = tasks[indexPath.row]
task.updateCompleted(value)
}
}
}
// MARK: Search bar delegate
extension ListViewController: UISearchControllerDelegate, UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
guard searchedTerm != (searchController.searchBar.text ?? "") else {
return
}
searchedTerm = searchController.searchBar.text ?? ""
searchTimer?.invalidate()
searchTimer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { [weak self] _ in
self?.subscribe()
}
}
}
// MARK: Ordering delegate
extension ListViewController: OrderViewControllerDelegate {
func orderViewControllerDidCancel(_ controller: OrderViewController) {
controller.dismiss(animated: true, completion: nil)
}
func orderViewControllerDidFinish(_ controller: OrderViewController, withOrdering ordering: RapidOrdering) {
self.ordering = ordering
subscribe()
controller.dismiss(animated: true, completion: nil)
}
}
// MARK: Filter delegate
extension ListViewController: FilterViewControllerDelegate {
func filterViewControllerDidCancel(_ controller: FilterViewController) {
controller.dismiss(animated: true, completion: nil)
}
func filterViewControllerDidFinish(_ controller: FilterViewController, withFilter filter: RapidFilter?) {
self.filter = filter
subscribe()
controller.dismiss(animated: true, completion: nil)
}
}
| mit |
alblue/swift | test/SILGen/global_resilience.swift | 1 | 4303 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -enable-sil-ownership -enable-resilience -emit-module-path=%t/resilient_global.swiftmodule -module-name=resilient_global %S/../Inputs/resilient_global.swift
// RUN: %target-swift-emit-silgen -I %t -enable-resilience -enable-sil-ownership -parse-as-library %s | %FileCheck %s
// RUN: %target-swift-emit-sil -I %t -O -enable-resilience -parse-as-library %s | %FileCheck --check-prefix=CHECK-OPT %s
import resilient_global
public struct MyEmptyStruct {}
// CHECK-LABEL: sil_global @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvp : $MyEmptyStruct
public var myEmptyGlobal = MyEmptyStruct()
// CHECK-LABEL: sil_global @$s17global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVvp : $MyEmptyStruct
@_fixed_layout public var myFixedLayoutGlobal = MyEmptyStruct()
// Mutable addressor for resilient global
// CHECK-LABEL: sil hidden [global_init] @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvau : $@convention(thin) () -> Builtin.RawPointer
// CHECK: global_addr @$s17global_resilience13myEmptyGlobalAA02MyD6StructVv
// CHECK: return
// Synthesized accessors for our resilient global variable
// CHECK-LABEL: sil @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvg
// CHECK: function_ref @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvau
// CHECK: return
// CHECK-LABEL: sil @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvs
// CHECK: function_ref @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvau
// CHECK: return
// CHECK-LABEL: sil @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvM
// CHECK: function_ref @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvau
// CHECK: begin_access [modify] [dynamic]
// CHECK: yield
// CHECK: end_access
// Mutable addressor for fixed-layout global
// CHECK-LABEL: sil [global_init] @$s17global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVvau
// CHECK: global_addr @$s17global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVv
// CHECK: return
// CHECK-OPT-LABEL: sil private @globalinit_{{.*}}_func0
// CHECK-OPT: alloc_global @$s17global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVv
// CHECK-OPT: return
// CHECK-OPT-LABEL: sil [global_init] @$s17global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVvau
// CHECK-OPT: global_addr @$s17global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVvp
// CHECK-OPT: function_ref @globalinit_{{.*}}_func0
// CHECK-OPT: return
// Accessing resilient global from our resilience domain --
// call the addressor directly
// CHECK-LABEL: sil @$s17global_resilience16getMyEmptyGlobalAA0dE6StructVyF
// CHECK: function_ref @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvau
// CHECK: return
public func getMyEmptyGlobal() -> MyEmptyStruct {
return myEmptyGlobal
}
// Accessing resilient global from a different resilience domain --
// access it with accessors
// CHECK-LABEL: sil @$s17global_resilience14getEmptyGlobal010resilient_A00D15ResilientStructVyF
// CHECK: function_ref @$s16resilient_global11emptyGlobalAA20EmptyResilientStructVvg
// CHECK: return
public func getEmptyGlobal() -> EmptyResilientStruct {
return emptyGlobal
}
// CHECK-LABEL: sil @$s17global_resilience17modifyEmptyGlobalyyF
// CHECK: [[MODIFY:%.*]] = function_ref @$s16resilient_global11emptyGlobalAA20EmptyResilientStructVvM
// CHECK-NEXT: ([[ADDR:%.*]], [[TOKEN:%.*]]) = begin_apply [[MODIFY]]()
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[FN:%.*]] = function_ref @$s16resilient_global20EmptyResilientStructV6mutateyyF
// CHECK-NEXT: apply [[FN]]([[ADDR]])
// CHECK-NEXT: end_apply [[TOKEN]]
// CHECK-NEXT: tuple
// CHECK-NEXT: return
public func modifyEmptyGlobal() {
emptyGlobal.mutate()
}
// Accessing fixed-layout global from a different resilience domain --
// call the addressor directly
// CHECK-LABEL: sil @$s17global_resilience20getFixedLayoutGlobal010resilient_A020EmptyResilientStructVyF
// CHECK: function_ref @$s16resilient_global17fixedLayoutGlobalAA20EmptyResilientStructVvau
// CHECK: return
public func getFixedLayoutGlobal() -> EmptyResilientStruct {
return fixedLayoutGlobal
}
| apache-2.0 |
mozilla-mobile/firefox-ios | Client/Frontend/Browser/Tab Management/TabFileManager.swift | 2 | 637 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/
import Foundation
import Shared
protocol TabFileManager {
func removeItem(at URL: URL) throws
func fileExists(atPath path: String) -> Bool
var tabPath: String? { get }
}
extension FileManager: TabFileManager {
var tabPath: String? {
return containerURL(forSecurityApplicationGroupIdentifier: AppInfo.sharedContainerIdentifier)?
.appendingPathComponent("profile.profile")
.path
}
}
| mpl-2.0 |
mozilla-mobile/firefox-ios | Client/Frontend/Login Management/LoginListSelectionHelper.swift | 2 | 1472 | // 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
/// Helper that keeps track of selected indexes for LoginListViewController
public class LoginListSelectionHelper {
private unowned let tableView: UITableView
private(set) var selectedIndexPaths = [IndexPath]()
var selectedCount: Int {
return selectedIndexPaths.count
}
init(tableView: UITableView) {
self.tableView = tableView
}
func selectIndexPath(_ indexPath: IndexPath) {
selectedIndexPaths.append(indexPath)
}
func indexPathIsSelected(_ indexPath: IndexPath) -> Bool {
return selectedIndexPaths.contains(indexPath) { path1, path2 in
return path1.row == path2.row && path1.section == path2.section
}
}
func deselectIndexPath(_ indexPath: IndexPath) {
guard let foundSelectedPath = (selectedIndexPaths.filter { $0.row == indexPath.row && $0.section == indexPath.section }).first,
let indexToRemove = selectedIndexPaths.firstIndex(of: foundSelectedPath) else {
return
}
selectedIndexPaths.remove(at: indexToRemove)
}
func deselectAll() {
selectedIndexPaths.removeAll()
}
func selectIndexPaths(_ indexPaths: [IndexPath]) {
selectedIndexPaths += indexPaths
}
}
| mpl-2.0 |
mozilla-mobile/firefox-ios | Client/Frontend/TabContentsScripts/NightModeHelper.swift | 2 | 2141 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import Foundation
import WebKit
import Shared
struct NightModePrefsKey {
static let NightModeButtonIsInMenu = PrefsKeys.KeyNightModeButtonIsInMenu
static let NightModeStatus = PrefsKeys.KeyNightModeStatus
static let NightModeEnabledDarkTheme = PrefsKeys.KeyNightModeEnabledDarkTheme
}
class NightModeHelper: TabContentScript {
fileprivate weak var tab: Tab?
required init(tab: Tab) {
self.tab = tab
}
static func name() -> String {
return "NightMode"
}
func scriptMessageHandlerName() -> String? {
return "NightMode"
}
func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
// Do nothing.
}
static func toggle(_ prefs: Prefs, tabManager: TabManager) {
let isActive = prefs.boolForKey(NightModePrefsKey.NightModeStatus) ?? false
setNightMode(prefs, tabManager: tabManager, enabled: !isActive)
}
static func setNightMode(_ prefs: Prefs, tabManager: TabManager, enabled: Bool) {
prefs.setBool(enabled, forKey: NightModePrefsKey.NightModeStatus)
for tab in tabManager.tabs {
tab.nightMode = enabled
tab.webView?.scrollView.indicatorStyle = enabled ? .white : .default
}
}
static func setEnabledDarkTheme(_ prefs: Prefs, darkTheme enabled: Bool) {
prefs.setBool(enabled, forKey: NightModePrefsKey.NightModeEnabledDarkTheme)
}
static func hasEnabledDarkTheme(_ prefs: Prefs) -> Bool {
return prefs.boolForKey(NightModePrefsKey.NightModeEnabledDarkTheme) ?? false
}
static func isActivated(_ prefs: Prefs) -> Bool {
return prefs.boolForKey(NightModePrefsKey.NightModeStatus) ?? false
}
}
class NightModeAccessors {
static func isNightMode(_ prefs: Prefs) -> Bool {
return prefs.boolForKey(NightModePrefsKey.NightModeStatus) ?? false
}
}
| mpl-2.0 |
paymentez/paymentez-ios | PaymentSDK/SkyFloatingLabelTextField.swift | 1 | 19615 | // Copyright 2016-2017 Skyscanner Ltd
//
// 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
/**
A beautiful and flexible textfield implementation with support for title label, error message and placeholder.
*/
@IBDesignable
open class SkyFloatingLabelTextField: UITextField { // swiftlint:disable:this type_body_length
/**
A Boolean value that determines if the language displayed is LTR.
Default value set automatically from the application language settings.
*/
open var isLTRLanguage = UIApplication.shared.userInterfaceLayoutDirection == .leftToRight {
didSet {
updateTextAligment()
}
}
fileprivate func updateTextAligment() {
if isLTRLanguage {
textAlignment = .left
titleLabel.textAlignment = .left
} else {
textAlignment = .right
titleLabel.textAlignment = .right
}
}
// MARK: Animation timing
/// The value of the title appearing duration
@objc dynamic open var titleFadeInDuration: TimeInterval = 0.2
/// The value of the title disappearing duration
@objc dynamic open var titleFadeOutDuration: TimeInterval = 0.3
// MARK: Colors
fileprivate var cachedTextColor: UIColor?
/// A UIColor value that determines the text color of the editable text
@IBInspectable
override dynamic open var textColor: UIColor? {
set {
cachedTextColor = newValue
updateControl(false)
}
get {
return cachedTextColor
}
}
/// A UIColor value that determines text color of the placeholder label
@IBInspectable dynamic open var placeholderColor: UIColor = UIColor.lightGray {
didSet {
updatePlaceholder()
}
}
/// A UIFont value that determines text color of the placeholder label
@objc dynamic open var placeholderFont: UIFont? {
didSet {
updatePlaceholder()
}
}
fileprivate func updatePlaceholder() {
if let placeholder = placeholder, let font = placeholderFont ?? font {
attributedPlaceholder = NSAttributedString(
string: placeholder,
attributes: [NSAttributedString.Key.foregroundColor: placeholderColor, NSAttributedString.Key.font: font]
)
}
}
/// A UIFont value that determines the text font of the title label
@objc dynamic open var titleFont: UIFont = .systemFont(ofSize: 13) {
didSet {
updateTitleLabel()
}
}
/// A UIColor value that determines the text color of the title label when in the normal state
@IBInspectable dynamic open var titleColor: UIColor = .gray {
didSet {
updateTitleColor()
}
}
/// A UIColor value that determines the color of the bottom line when in the normal state
@IBInspectable dynamic open var lineColor: UIColor = .lightGray {
didSet {
updateLineView()
}
}
/// A UIColor value that determines the color used for the title label and line when the error message is not `nil`
@IBInspectable dynamic open var errorColor: UIColor = .red {
didSet {
updateColors()
}
}
/// A UIColor value that determines the text color of the title label when editing
@IBInspectable dynamic open var selectedTitleColor: UIColor = .blue {
didSet {
updateTitleColor()
}
}
/// A UIColor value that determines the color of the line in a selected state
@IBInspectable dynamic open var selectedLineColor: UIColor = .black {
didSet {
updateLineView()
}
}
// MARK: Line height
/// A CGFloat value that determines the height for the bottom line when the control is in the normal state
@IBInspectable dynamic open var lineHeight: CGFloat = 0.5 {
didSet {
updateLineView()
setNeedsDisplay()
}
}
/// A CGFloat value that determines the height for the bottom line when the control is in a selected state
@IBInspectable dynamic open var selectedLineHeight: CGFloat = 1.0 {
didSet {
updateLineView()
setNeedsDisplay()
}
}
// MARK: View components
/// The internal `UIView` to display the line below the text input.
open var lineView: UIView!
/// The internal `UILabel` that displays the selected, deselected title or error message based on the current state.
open var titleLabel: UILabel!
// MARK: Properties
/**
The formatter used before displaying content in the title label.
This can be the `title`, `selectedTitle` or the `errorMessage`.
The default implementation converts the text to uppercase.
*/
open var titleFormatter: ((String) -> String) = { (text: String) -> String in
return text
}
/**
Identifies whether the text object should hide the text being entered.
*/
override open var isSecureTextEntry: Bool {
set {
super.isSecureTextEntry = newValue
fixCaretPosition()
}
get {
return super.isSecureTextEntry
}
}
/// A String value for the error message to display.
open var errorMessage: String? {
didSet {
updateControl(true)
}
}
/// The backing property for the highlighted property
fileprivate var _highlighted = false
/**
A Boolean value that determines whether the receiver is highlighted.
When changing this value, highlighting will be done with animation
*/
override open var isHighlighted: Bool {
get {
return _highlighted
}
set {
_highlighted = newValue
updateTitleColor()
updateLineView()
}
}
/// A Boolean value that determines whether the textfield is being edited or is selected.
open var editingOrSelected: Bool {
return super.isEditing || isSelected
}
/// A Boolean value that determines whether the receiver has an error message.
open var hasErrorMessage: Bool {
return errorMessage != nil && errorMessage != ""
}
fileprivate var _renderingInInterfaceBuilder: Bool = false
/// The text content of the textfield
@IBInspectable
override open var text: String? {
didSet {
updateControl(false)
}
}
/**
The String to display when the input field is empty.
The placeholder can also appear in the title label when both `title` `selectedTitle` and are `nil`.
*/
@IBInspectable
override open var placeholder: String? {
didSet {
setNeedsDisplay()
updatePlaceholder()
updateTitleLabel()
}
}
/// The String to display when the textfield is editing and the input is not empty.
@IBInspectable open var selectedTitle: String? {
didSet {
updateControl()
}
}
/// The String to display when the textfield is not editing and the input is not empty.
@IBInspectable open var title: String? {
didSet {
updateControl()
}
}
// Determines whether the field is selected. When selected, the title floats above the textbox.
open override var isSelected: Bool {
didSet {
updateControl(true)
}
}
// MARK: - Initializers
/**
Initializes the control
- parameter frame the frame of the control
*/
override public init(frame: CGRect) {
super.init(frame: frame)
init_SkyFloatingLabelTextField()
}
/**
Intialzies the control by deserializing it
- parameter coder the object to deserialize the control from
*/
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
init_SkyFloatingLabelTextField()
}
fileprivate final func init_SkyFloatingLabelTextField() {
borderStyle = .none
createTitleLabel()
createLineView()
updateColors()
addEditingChangedObserver()
updateTextAligment()
}
fileprivate func addEditingChangedObserver() {
self.addTarget(self, action: #selector(SkyFloatingLabelTextField.editingChanged), for: .editingChanged)
}
/**
Invoked when the editing state of the textfield changes. Override to respond to this change.
*/
@objc open func editingChanged() {
updateControl(true)
updateTitleLabel(true)
}
// MARK: create components
fileprivate func createTitleLabel() {
let titleLabel = UILabel()
titleLabel.autoresizingMask = [.flexibleWidth, .flexibleHeight]
titleLabel.font = titleFont
titleLabel.alpha = 0.0
titleLabel.textColor = titleColor
addSubview(titleLabel)
self.titleLabel = titleLabel
}
fileprivate func createLineView() {
if lineView == nil {
let lineView = UIView()
lineView.isUserInteractionEnabled = false
self.lineView = lineView
configureDefaultLineHeight()
}
lineView.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
addSubview(lineView)
}
fileprivate func configureDefaultLineHeight() {
let onePixel: CGFloat = 1.0 / UIScreen.main.scale
lineHeight = 2.0 * onePixel
selectedLineHeight = 2.0 * self.lineHeight
}
// MARK: Responder handling
/**
Attempt the control to become the first responder
- returns: True when successfull becoming the first responder
*/
@discardableResult
override open func becomeFirstResponder() -> Bool {
let result = super.becomeFirstResponder()
updateControl(true)
return result
}
/**
Attempt the control to resign being the first responder
- returns: True when successfull resigning being the first responder
*/
@discardableResult
override open func resignFirstResponder() -> Bool {
let result = super.resignFirstResponder()
updateControl(true)
return result
}
// MARK: - View updates
fileprivate func updateControl(_ animated: Bool = false) {
updateColors()
updateLineView()
updateTitleLabel(animated)
}
fileprivate func updateLineView() {
if let lineView = lineView {
lineView.frame = lineViewRectForBounds(bounds, editing: editingOrSelected)
}
updateLineColor()
}
// MARK: - Color updates
/// Update the colors for the control. Override to customize colors.
open func updateColors() {
updateLineColor()
updateTitleColor()
updateTextColor()
}
fileprivate func updateLineColor() {
if hasErrorMessage {
lineView.backgroundColor = errorColor
} else {
lineView.backgroundColor = editingOrSelected ? selectedLineColor : lineColor
}
}
fileprivate func updateTitleColor() {
if hasErrorMessage {
titleLabel.textColor = errorColor
} else {
if editingOrSelected || isHighlighted {
titleLabel.textColor = selectedTitleColor
} else {
titleLabel.textColor = titleColor
}
}
}
fileprivate func updateTextColor() {
if hasErrorMessage {
super.textColor = errorColor
} else {
super.textColor = cachedTextColor
}
}
// MARK: - Title handling
fileprivate func updateTitleLabel(_ animated: Bool = false) {
var titleText: String? = nil
if hasErrorMessage {
titleText = titleFormatter(errorMessage!)
} else {
if editingOrSelected {
titleText = selectedTitleOrTitlePlaceholder()
if titleText == nil {
titleText = titleOrPlaceholder()
}
} else {
titleText = titleOrPlaceholder()
}
}
titleLabel.text = titleText
titleLabel.font = titleFont
updateTitleVisibility(animated)
}
fileprivate var _titleVisible = false
/*
* Set this value to make the title visible
*/
open func setTitleVisible(
_ titleVisible: Bool,
animated: Bool = false,
animationCompletion: ((_ completed: Bool) -> Void)? = nil
) {
if _titleVisible == titleVisible {
return
}
_titleVisible = titleVisible
updateTitleColor()
updateTitleVisibility(animated, completion: animationCompletion)
}
/**
Returns whether the title is being displayed on the control.
- returns: True if the title is displayed on the control, false otherwise.
*/
open func isTitleVisible() -> Bool {
return hasText || hasErrorMessage || _titleVisible
}
fileprivate func updateTitleVisibility(_ animated: Bool = false, completion: ((_ completed: Bool) -> Void)? = nil) {
let alpha: CGFloat = isTitleVisible() ? 1.0 : 0.0
let frame: CGRect = titleLabelRectForBounds(bounds, editing: isTitleVisible())
let updateBlock = { () -> Void in
self.titleLabel.alpha = alpha
self.titleLabel.frame = frame
}
if animated {
let animationOptions: UIView.AnimationOptions = .curveEaseOut
let duration = isTitleVisible() ? titleFadeInDuration : titleFadeOutDuration
UIView.animate(withDuration: duration, delay: 0, options: animationOptions, animations: { () -> Void in
updateBlock()
}, completion: completion)
} else {
updateBlock()
completion?(true)
}
}
// MARK: - UITextField text/placeholder positioning overrides
/**
Calculate the rectangle for the textfield when it is not being edited
- parameter bounds: The current bounds of the field
- returns: The rectangle that the textfield should render in
*/
override open func textRect(forBounds bounds: CGRect) -> CGRect {
let superRect = super.textRect(forBounds: bounds)
let titleHeight = self.titleHeight()
let rect = CGRect(
x: superRect.origin.x,
y: titleHeight,
width: superRect.size.width,
height: superRect.size.height - titleHeight - selectedLineHeight
)
return rect
}
/**
Calculate the rectangle for the textfield when it is being edited
- parameter bounds: The current bounds of the field
- returns: The rectangle that the textfield should render in
*/
override open func editingRect(forBounds bounds: CGRect) -> CGRect {
let superRect = super.editingRect(forBounds: bounds)
let titleHeight = self.titleHeight()
let rect = CGRect(
x: superRect.origin.x,
y: titleHeight,
width: superRect.size.width,
height: superRect.size.height - titleHeight - selectedLineHeight
)
return rect
}
/**
Calculate the rectangle for the placeholder
- parameter bounds: The current bounds of the placeholder
- returns: The rectangle that the placeholder should render in
*/
override open func placeholderRect(forBounds bounds: CGRect) -> CGRect {
let rect = CGRect(
x: 0,
y: titleHeight(),
width: bounds.size.width,
height: bounds.size.height - titleHeight() - selectedLineHeight
)
return rect
}
// MARK: - Positioning Overrides
/**
Calculate the bounds for the title label. Override to create a custom size title field.
- parameter bounds: The current bounds of the title
- parameter editing: True if the control is selected or highlighted
- returns: The rectangle that the title label should render in
*/
open func titleLabelRectForBounds(_ bounds: CGRect, editing: Bool) -> CGRect {
if editing {
return CGRect(x: 0, y: 0, width: bounds.size.width, height: titleHeight())
}
return CGRect(x: 0, y: titleHeight(), width: bounds.size.width, height: titleHeight())
}
/**
Calculate the bounds for the bottom line of the control.
Override to create a custom size bottom line in the textbox.
- parameter bounds: The current bounds of the line
- parameter editing: True if the control is selected or highlighted
- returns: The rectangle that the line bar should render in
*/
open func lineViewRectForBounds(_ bounds: CGRect, editing: Bool) -> CGRect {
let height = editing ? selectedLineHeight : lineHeight
return CGRect(x: 0, y: bounds.size.height - height, width: bounds.size.width, height: height)
}
/**
Calculate the height of the title label.
-returns: the calculated height of the title label. Override to size the title with a different height
*/
open func titleHeight() -> CGFloat {
if let titleLabel = titleLabel,
let font = titleLabel.font {
return font.lineHeight
}
return 15.0
}
/**
Calcualte the height of the textfield.
-returns: the calculated height of the textfield. Override to size the textfield with a different height
*/
open func textHeight() -> CGFloat {
return self.font!.lineHeight + 7.0
}
// MARK: - Layout
/// Invoked when the interface builder renders the control
override open func prepareForInterfaceBuilder() {
if #available(iOS 8.0, *) {
super.prepareForInterfaceBuilder()
}
borderStyle = .none
isSelected = true
_renderingInInterfaceBuilder = true
updateControl(false)
invalidateIntrinsicContentSize()
}
/// Invoked by layoutIfNeeded automatically
override open func layoutSubviews() {
super.layoutSubviews()
titleLabel.frame = titleLabelRectForBounds(bounds, editing: isTitleVisible() || _renderingInInterfaceBuilder)
lineView.frame = lineViewRectForBounds(bounds, editing: editingOrSelected || _renderingInInterfaceBuilder)
}
/**
Calculate the content size for auto layout
- returns: the content size to be used for auto layout
*/
override open var intrinsicContentSize: CGSize {
return CGSize(width: bounds.size.width, height: titleHeight() + textHeight())
}
// MARK: - Helpers
fileprivate func titleOrPlaceholder() -> String? {
guard let title = title ?? placeholder else {
return nil
}
return titleFormatter(title)
}
fileprivate func selectedTitleOrTitlePlaceholder() -> String? {
guard let title = selectedTitle ?? title ?? placeholder else {
return nil
}
return titleFormatter(title)
}
} // swiftlint:disable:this file_length
| mit |
biohazardlover/NintendoEverything | Pods/SwiftSoup/Sources/Attribute.swift | 1 | 4267 | //
// Attribute.swift
// SwifSoup
//
// Created by Nabil Chatbi on 29/09/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
open class Attribute {
/// The element type of a dictionary: a tuple containing an individual
/// key-value pair.
static let booleanAttributes: [String] = [
"allowfullscreen", "async", "autofocus", "checked", "compact", "declare", "default", "defer", "disabled",
"formnovalidate", "hidden", "inert", "ismap", "itemscope", "multiple", "muted", "nohref", "noresize",
"noshade", "novalidate", "nowrap", "open", "readonly", "required", "reversed", "seamless", "selected",
"sortable", "truespeed", "typemustmatch"
]
var key: String
var value: String
public init(key: String, value: String) throws {
try Validate.notEmpty(string: key)
self.key = key.trim()
self.value = value
}
/**
Get the attribute key.
@return the attribute key
*/
open func getKey() -> String {
return key
}
/**
Set the attribute key; case is preserved.
@param key the new key; must not be null
*/
open func setKey(key: String) throws {
try Validate.notEmpty(string: key)
self.key = key.trim()
}
/**
Get the attribute value.
@return the attribute value
*/
open func getValue() -> String {
return value
}
/**
Set the attribute value.
@param value the new attribute value; must not be null
*/
@discardableResult
open func setValue(value: String) -> String {
let old = self.value
self.value = value
return old
}
/**
Get the HTML representation of this attribute; e.g. {@code href="index.html"}.
@return HTML
*/
public func html() -> String {
let accum = StringBuilder()
html(accum: accum, out: (Document("")).outputSettings())
return accum.toString()
}
public func html(accum: StringBuilder, out: OutputSettings ) {
accum.append(key)
if (!shouldCollapseAttribute(out: out)) {
accum.append("=\"")
Entities.escape(accum, value, out, true, false, false)
accum.append("\"")
}
}
/**
Get the string representation of this attribute, implemented as {@link #html()}.
@return string
*/
open func toString() -> String {
return html()
}
/**
* Create a new Attribute from an unencoded key and a HTML attribute encoded value.
* @param unencodedKey assumes the key is not encoded, as can be only run of simple \w chars.
* @param encodedValue HTML attribute encoded value
* @return attribute
*/
open static func createFromEncoded(unencodedKey: String, encodedValue: String) throws ->Attribute {
let value = try Entities.unescape(string: encodedValue, strict: true)
return try Attribute(key: unencodedKey, value: value)
}
public func isDataAttribute() -> Bool {
return key.startsWith(Attributes.dataPrefix) && key.count > Attributes.dataPrefix.count
}
/**
* Collapsible if it's a boolean attribute and value is empty or same as name
*
* @param out Outputsettings
* @return Returns whether collapsible or not
*/
public final func shouldCollapseAttribute(out: OutputSettings) -> Bool {
return ("" == value || value.equalsIgnoreCase(string: key))
&& out.syntax() == OutputSettings.Syntax.html
&& isBooleanAttribute()
}
public func isBooleanAttribute() -> Bool {
return Attribute.booleanAttributes.contains(key)
}
public func hashCode() -> Int {
var result = key.hashValue
result = 31 * result + value.hashValue
return result
}
public func clone() -> Attribute {
do {
return try Attribute(key: key, value: value)
} catch Exception.Error( _, let msg) {
print(msg)
} catch {
}
return try! Attribute(key: "", value: "")
}
}
extension Attribute : Equatable {
static public func == (lhs: Attribute, rhs: Attribute) -> Bool {
return lhs.value == rhs.value && lhs.key == rhs.key
}
}
| mit |
borglab/SwiftFusion | Sources/SwiftFusion/Inference/PCAEncoder.swift | 1 | 2929 | // Copyright 2020 The SwiftFusion 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 TensorFlow
import PenguinStructures
/// A class that does PCA decomposition
/// Input shape for training: [N, H, W, C]
/// W matrix: [H, W, C, latent]
/// Output: [H, W, C]
public struct PCAEncoder {
public typealias Patch = Tensor<Double>
/// Basis
public let U: Tensor<Double>
/// Data mean
public let mu: Tensor<Double>
/// Size of latent
public var d: Int {
get {
U.shape[1]
}
}
/// Input dimension for one sample
public var n: Int {
get {
U.shape[0]
}
}
/// Train a PCAEncoder model
/// images should be a Tensor of shape [N, H, W, C]
/// default feature size is 10
/// Input: [N, H, W, C]
public typealias HyperParameters = Int
public init(from imageBatch: Tensor<Double>, given p: HyperParameters? = nil) {
precondition(imageBatch.rank == 4, "Wrong image shape \(imageBatch.shape)")
let (N_, H_, W_, C_) = (imageBatch.shape[0], imageBatch.shape[1], imageBatch.shape[2], imageBatch.shape[3])
let n = H_ * W_ * C_
let d = p ?? 10
let images_flattened = imageBatch.reshaped(to: [N_, n])
let mu = images_flattened.mean(squeezingAxes: 0)
let images_flattened_without_mean = (images_flattened - mu).transposed()
let (_, U, _) = images_flattened_without_mean.svd(computeUV: true, fullMatrices: false)
self.init(withBasis: U![TensorRange.ellipsis, 0..<d], andMean: mu)
}
/// Initialize a PCAEncoder
public init(withBasis U: Tensor<Double>, andMean mu: Tensor<Double>) {
self.U = U
self.mu = mu
}
/// Generate an image according to a latent
/// Input: [H, W, C]
/// Output: [d]
@differentiable
public func encode(_ image: Patch) -> Tensor<Double> {
precondition(image.rank == 3 || (image.rank == 4), "wrong latent dimension \(image.shape)")
let (N_) = (image.shape[0])
if image.rank == 4 {
if N_ == 1 {
return matmul(U, transposed: true, image.reshaped(to: [n, 1]) - mu.reshaped(to: [n, 1])).reshaped(to: [1, d])
} else {
let v = image.reshaped(to: [N_, n]) - mu.reshaped(to: [1, n])
return matmul(v, U)
}
} else {
let v = image.reshaped(to: [n, 1]) - mu.reshaped(to: [n, 1])
return matmul(U, transposed: true, v).reshaped(to: [d])
}
}
}
extension PCAEncoder: AppearanceModelEncoder {}
| apache-2.0 |
lizhaoLoveIT/sinaWeiBo | sinaWeiBo/sinaWeiBo/main.swift | 1 | 234 | //
// main.swift
// sinaWeiBo
//
// Created by 李朝 on 16/6/3.
// Copyright © 2016年 IFengXY. All rights reserved.
//
import UIKit
UIApplicationMain(Process.argc, Process.unsafeArgv, nil, NSStringFromClass(AppDelegate.self)) | mit |
AlexLittlejohn/OMDBMovies | OMDBMovies/Models/MovieResult.swift | 1 | 615 | //
// MovieResult.swift
// OMDBMovies
//
// Created by Alex Littlejohn on 2016/04/04.
// Copyright © 2016 Alex Littlejohn. All rights reserved.
//
import UIKit
struct MovieResult {
let title: String
let year: String
let poster: String
let imdbID: String
let type: String
}
extension MovieResult: JSONInitializable {
init(JSON: JSONObject) {
title = JSON["Title"] as? String ?? ""
year = JSON["Year"] as? String ?? ""
poster = JSON["Poster"] as? String ?? ""
imdbID = JSON["imdbID"] as? String ?? ""
type = JSON["Type"] as? String ?? ""
}
} | mit |
wuleijun/SwiftPractice | SwiftPractice/SwiftPractice/RJUpDownPresentedVC.swift | 1 | 1158 | //
// RJUpDownPresentedVC.swift
// SwiftPractice
//
// Created by 吴蕾君 on 16/3/14.
// Copyright © 2016年 rayjuneWu. All rights reserved.
//
import UIKit
class RJUpDownPresentedVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController?.navigationBarHidden = true
}
@IBAction func dismiss(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// 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 |
wj2061/ios7ptl-swift3.0 | ch24-DeepObjc/MethodSwizzle/MethodSwizzle/RNSwizzle.swift | 1 | 562 | //
// RNSwizzle.swift
// MethodSwizzle
//
// Created by WJ on 15/12/3.
// Copyright © 2015年 wj. All rights reserved.
//
import Foundation
extension NSObject{
class func swizzleSelector(_ origSelector:Selector,newIMP:IMP)->IMP{
let origMethod = class_getInstanceMethod(self, origSelector)
let origIMP = method_getImplementation(origMethod)
if !class_addMethod(self, origSelector, newIMP, method_getTypeEncoding(origMethod)){
method_setImplementation(origMethod, newIMP)
}
return origIMP!
}
}
| mit |
kstaring/swift | test/IRGen/closure.swift | 4 | 3284 | // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir | %FileCheck %s
// REQUIRES: CPU=x86_64
// -- partial_apply context metadata
// CHECK: [[METADATA:@.*]] = private constant %swift.full_boxmetadata { void (%swift.refcounted*)* @objectdestroy, i8** null, %swift.type { i64 64 }, i32 16, i8* bitcast (<{ i32, i32, i32, i32 }>* @"\01l__swift3_reflection_descriptor" to i8*) }
func a(i i: Int) -> (Int) -> Int {
return { x in i }
}
// -- Closure entry point
// CHECK: define linkonce_odr hidden i64 @_TFF7closure1aFT1iSi_FSiSiU_FSiSi(i64, i64)
protocol Ordinable {
func ord() -> Int
}
func b<T : Ordinable>(seq seq: T) -> (Int) -> Int {
return { i in i + seq.ord() }
}
// -- partial_apply stub
// CHECK: define internal i64 @_TPA__TFF7closure1aFT1iSi_FSiSiU_FSiSi(i64, %swift.refcounted*)
// CHECK: }
// -- Closure entry point
// CHECK: define linkonce_odr hidden i64 @[[CLOSURE2:_TFF7closure1buRxS_9OrdinablerFT3seqx_FSiSiU_FSiSi]](i64, %swift.refcounted*, %swift.type* %T, i8** %T.Ordinable) {{.*}} {
// -- partial_apply stub
// CHECK: define internal i64 @_TPA_[[CLOSURE2]](i64, %swift.refcounted*) {{.*}} {
// CHECK: entry:
// CHECK: [[CONTEXT:%.*]] = bitcast %swift.refcounted* %1 to <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>*
// CHECK: [[BINDINGSADDR:%.*]] = getelementptr inbounds <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>, <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>* [[CONTEXT]], i32 0, i32 1
// CHECK: [[TYPEADDR:%.*]] = bitcast [16 x i8]* [[BINDINGSADDR]]
// CHECK: [[TYPE:%.*]] = load %swift.type*, %swift.type** [[TYPEADDR]], align 8
// CHECK: [[WITNESSADDR_0:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[TYPEADDR]], i32 1
// CHECK: [[WITNESSADDR:%.*]] = bitcast %swift.type** [[WITNESSADDR_0]]
// CHECK: [[WITNESS:%.*]] = load i8**, i8*** [[WITNESSADDR]], align 8
// CHECK: [[BOXADDR:%.*]] = getelementptr inbounds <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>, <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>* [[CONTEXT]], i32 0, i32 2
// CHECK: [[BOX:%.*]] = load %swift.refcounted*, %swift.refcounted** [[BOXADDR]], align 8
// CHECK: call void @swift_rt_swift_retain(%swift.refcounted* [[BOX]])
// CHECK: call void @swift_rt_swift_release(%swift.refcounted* %1)
// CHECK: [[RES:%.*]] = tail call i64 @[[CLOSURE2]](i64 %0, %swift.refcounted* [[BOX]], %swift.type* [[TYPE]], i8** [[WITNESS]])
// CHECK: ret i64 [[RES]]
// CHECK: }
// -- <rdar://problem/14443343> Boxing of tuples with generic elements
// CHECK: define hidden { i8*, %swift.refcounted* } @_TF7closure14captures_tupleu0_rFT1xTxq___FT_Txq__(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T, %swift.type* %U)
func captures_tuple<T, U>(x x: (T, U)) -> () -> (T, U) {
// CHECK: [[METADATA:%.*]] = call %swift.type* @swift_getTupleTypeMetadata2(%swift.type* %T, %swift.type* %U, i8* null, i8** null)
// CHECK-NOT: @swift_getTupleTypeMetadata2
// CHECK: [[BOX:%.*]] = call { %swift.refcounted*, %swift.opaque* } @swift_allocBox(%swift.type* [[METADATA]])
// CHECK: [[ADDR:%.*]] = extractvalue { %swift.refcounted*, %swift.opaque* } [[BOX]], 1
// CHECK: bitcast %swift.opaque* [[ADDR]] to <{}>*
return {x}
}
| apache-2.0 |
diegosanchezr/Chatto | ChattoAdditions/Source/Input/ChatInputBarAppearance.swift | 1 | 1481 | /*
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.
*/
public struct ChatInputBarAppearance {
public var textFont = UIFont.systemFontOfSize(12)
public var textColor = UIColor.blackColor()
public var textPlaceholderFont = UIFont.systemFontOfSize(12)
public var textPlaceholderColor = UIColor.grayColor()
public var textPlaceholder = ""
public var sendButtonTitle = ""
public init() {}
}
| mit |
natecook1000/swift | validation-test/Sema/type_checker_perf/slow/rdar22770433.swift | 2 | 333 | // RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1
// REQUIRES: tools-release,no_asserts
func test(n: Int) -> Int {
return n == 0 ? 0 : (0..<n).reduce(0) {
// expected-error@-1 {{reasonable time}}
($0 > 0 && $1 % 2 == 0) ? ((($0 + $1) - ($0 + $1)) / ($1 - $0)) + (($0 + $1) / ($1 - $0)) : $0
}
}
| apache-2.0 |
deltaDNA/ios-sdk | Tests/DDNAEventActionTests.swift | 1 | 7576 | import XCTest
@testable import DeltaDNA
class DDNAEventActionTests: XCTestCase {
var event: DDNAEvent!
var actionStore: DDNAActionStore!
var uut: DDNAEventAction!
override func setUpWithError() throws {
event = DDNAEvent(name: "test")
actionStore = DDNAActionStoreMock(path: "test")
uut = DDNAEventAction()
}
func test_runEmptyEvent_noErrorsReturned() throws {
do {
try ObjC.catchException {
self.uut.run()
}
}
catch {
XCTFail()
}
XCTAssertTrue(true)
}
func test_runThreeTriggersWithPriorities_triggersRunInOrder() throws {
let trigger1 = DDNAEventTrigger(dictionary: ["priority" : 5])
let trigger2 = DDNAEventTrigger(dictionary: ["priority" : 3])
let trigger3 = DDNAEventTrigger(dictionary: ["priority" : 1])
let triggers: NSOrderedSet = NSOrderedSet(orderedSet: [trigger1!, trigger2!, trigger3!])
let mockSettings: DDNASettings = DDNASettings()
let mockSdk: DDNASdkInterfaceMock = DDNASdkInterfaceMock()
uut = DDNAEventAction(eventSchema: event.dictionary(), eventTriggers: triggers, sdk: mockSdk, store: actionStore, settings: mockSettings)
uut.run()
XCTAssertEqual(mockSdk.recordedEvents.count, 3)
let firstRecordedEventParams = mockSdk.recordedEvents[0].dictionary()["eventParams"] as! [String : Any]
let secondRecordedEventParams = mockSdk.recordedEvents[1].dictionary()["eventParams"] as! [String : Any]
let thirdRecordedEventParams = mockSdk.recordedEvents[2].dictionary()["eventParams"] as! [String : Any]
XCTAssertEqual(firstRecordedEventParams["ddnaEventTriggeredCampaignPriority"] as! Int, 5)
XCTAssertEqual(secondRecordedEventParams["ddnaEventTriggeredCampaignPriority"] as! Int, 3)
XCTAssertEqual(thirdRecordedEventParams["ddnaEventTriggeredCampaignPriority"] as! Int, 1)
}
func test_handlesAreRun_finishWhenOneHandlesTheAction() throws {
let trigger = DDNAEventTriggerMock()
let triggers: NSOrderedSet = NSOrderedSet(orderedSet: [trigger])
let mockSettings: DDNASettings = DDNASettings()
let mockSdk: DDNASdkInterfaceMock = DDNASdkInterfaceMock()
let h1: DDNAEventActionHandlerMock = DDNAEventActionHandlerMock()
let h2: DDNAEventActionHandlerMock = DDNAEventActionHandlerMock()
let h3: DDNAEventActionHandlerMock = DDNAEventActionHandlerMock()
trigger.expectedResponseToResponds = true
h1.expectedHandleReturn = false
h2.expectedHandleReturn = true
uut = DDNAEventAction(eventSchema: event.dictionary(), eventTriggers: triggers, sdk: mockSdk, store: actionStore, settings: mockSettings)
uut.add(h1)
uut.add(h2)
uut.add(h3)
uut.run()
XCTAssertEqual(h1.handleTriggerCountForValues.count, 1)
XCTAssertEqual(h2.handleTriggerCountForValues.count, 1)
XCTAssertEqual(h3.handleTriggerCountForValues.count, 0)
XCTAssertTrue(h1.handleTriggerCountForValues[0]["eventTrigger"]! as! NSObject == trigger)
XCTAssertEqual(h1.handleTriggerCountForValues[0]["store"] as? DDNAActionStore, actionStore)
XCTAssertTrue(h2.handleTriggerCountForValues[0]["eventTrigger"]! as! NSObject == trigger)
XCTAssertEqual(h2.handleTriggerCountForValues[0]["store"] as? DDNAActionStore, actionStore)
}
func test_emptyAction_doNothing() throws {
let trigger = DDNAEventTriggerMock()
let h1: DDNAEventActionHandlerMock = DDNAEventActionHandlerMock()
trigger.expectedResponseToResponds = true
h1.expectedHandleReturn = true
uut.add(h1)
uut.run()
XCTAssertEqual(h1.handleTriggerCountForValues.count, 0)
}
func test_postAction_triggerEvent() throws {
let trigger = DDNAEventTriggerMock(dictionary: [
"campaignID" : 1,
"priority" : 2,
"variantID" : 3,
"response" : [ "eventParams" :
["responseEngagementName" : "campaignName",
"responseVariantName" : "variantName"] ],
"actionType" : "gameParameters",
"count" : 1])
let triggers: NSOrderedSet = NSOrderedSet(orderedSet: [trigger!])
let mockSettings: DDNASettings = DDNASettings()
let mockSdk: DDNASdkInterfaceMock = DDNASdkInterfaceMock()
mockSettings.multipleActionsForEventTriggerEnabled = false
trigger!.expectedResponseToResponds = true
uut = DDNAEventAction(eventSchema: event.dictionary(), eventTriggers: triggers, sdk: mockSdk, store: actionStore, settings: mockSettings)
uut.run()
XCTAssertEqual(mockSdk.recordedEvents.count, 1)
let recordedEvent = mockSdk.recordedEvents[0].dictionary() as! [String : Any]
XCTAssertEqual(recordedEvent["eventName"] as! String, "ddnaEventTriggeredAction")
let recordedEventParams = recordedEvent["eventParams"] as! [String : Any]
XCTAssertEqual(recordedEvent["eventName"] as! String, "ddnaEventTriggeredAction")
XCTAssertEqual(recordedEventParams["ddnaEventTriggeredCampaignID"] as! Int, 1)
XCTAssertEqual(recordedEventParams["ddnaEventTriggeredCampaignPriority"] as! Int, 2)
XCTAssertEqual(recordedEventParams["ddnaEventTriggeredVariantID"] as! Int, 3)
XCTAssertEqual(recordedEventParams["ddnaEventTriggeredCampaignName"] as! String, "campaignName")
XCTAssertEqual(recordedEventParams["ddnaEventTriggeredVariantName"] as! String, "variantName")
XCTAssertEqual(recordedEventParams["ddnaEventTriggeredActionType"] as! String, "gameParameters")
XCTAssertEqual(recordedEventParams["ddnaEventTriggeredSessionCount"] as! Int, 1)
}
func test_eventMissingOptionalFields_postActionFinishedWithoutErrors() throws {
let trigger = DDNAEventTriggerMock(dictionary: [
"campaignID" : 1,
"priority" : 2,
"variantID" : 3,
"actionType" : "gameParameters",
"count" : 1])
let triggers: NSOrderedSet = NSOrderedSet(orderedSet: [trigger!])
let mockSettings: DDNASettings = DDNASettings()
let mockSdk: DDNASdkInterfaceMock = DDNASdkInterfaceMock()
trigger!.expectedResponseToResponds = true
uut = DDNAEventAction(eventSchema: event.dictionary(), eventTriggers: triggers, sdk: mockSdk, store: actionStore, settings: mockSettings)
uut.run()
XCTAssertEqual(mockSdk.recordedEvents.count, 1)
let recordedEvent = mockSdk.recordedEvents[0].dictionary() as! [String : Any]
let recordedEventParams = recordedEvent["eventParams"] as! [String : Any]
XCTAssertEqual(recordedEventParams["ddnaEventTriggeredCampaignID"] as! Int, 1)
XCTAssertEqual(recordedEventParams["ddnaEventTriggeredCampaignPriority"] as! Int, 2)
XCTAssertEqual(recordedEventParams["ddnaEventTriggeredVariantID"] as! Int, 3)
XCTAssertEqual(recordedEventParams["ddnaEventTriggeredActionType"] as! String, "gameParameters")
XCTAssertEqual(recordedEventParams["ddnaEventTriggeredSessionCount"] as! Int, 1)
XCTAssertNil(recordedEventParams["ddnaEventTriggeredCampaignName"])
XCTAssertNil(recordedEventParams["ddnaEventTriggeredVariantName"])
}
}
| apache-2.0 |
practicalswift/swift | test/Interpreter/class_resilience.swift | 1 | 10484 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift-dylib(%t/%target-library-name(resilient_struct)) -Xfrontend -enable-resilience %S/../Inputs/resilient_struct.swift -emit-module -emit-module-path %t/resilient_struct.swiftmodule -module-name resilient_struct
// RUN: %target-codesign %t/%target-library-name(resilient_struct)
// RUN: %target-build-swift-dylib(%t/%target-library-name(resilient_class)) -Xfrontend -enable-resilience %S/../Inputs/resilient_class.swift -emit-module -emit-module-path %t/resilient_class.swiftmodule -module-name resilient_class -I%t -L%t -lresilient_struct
// RUN: %target-codesign %t/%target-library-name(resilient_class)
// RUN: %target-build-swift-dylib(%t/%target-library-name(fixed_layout_class)) -Xfrontend -enable-resilience %S/../Inputs/fixed_layout_class.swift -emit-module -emit-module-path %t/fixed_layout_class.swiftmodule -module-name fixed_layout_class -I%t -L%t -lresilient_struct
// RUN: %target-codesign %t/%target-library-name(fixed_layout_class)
// RUN: %target-build-swift %s -L %t -I %t -lresilient_struct -lresilient_class -lfixed_layout_class -o %t/main %target-rpath(%t)
// RUN: %target-codesign %t/main
// RUN: %target-run %t/main %t/%target-library-name(resilient_struct) %t/%target-library-name(resilient_class) %t/%target-library-name(fixed_layout_class)
// RUN: %target-build-swift-dylib(%t/%target-library-name(resilient_struct_wmo)) -Xfrontend -enable-resilience %S/../Inputs/resilient_struct.swift -emit-module -emit-module-path %t/resilient_struct.swiftmodule -module-name resilient_struct -whole-module-optimization
// RUN: %target-codesign %t/%target-library-name(resilient_struct_wmo)
// RUN: %target-build-swift-dylib(%t/%target-library-name(resilient_class_wmo)) -Xfrontend -enable-resilience %S/../Inputs/resilient_class.swift -emit-module -emit-module-path %t/resilient_class.swiftmodule -module-name resilient_class -I%t -L%t -lresilient_struct_wmo -whole-module-optimization
// RUN: %target-codesign %t/%target-library-name(resilient_class_wmo)
// RUN: %target-build-swift-dylib(%t/%target-library-name(fixed_layout_class_wmo)) -Xfrontend -enable-resilience %S/../Inputs/fixed_layout_class.swift -emit-module -emit-module-path %t/fixed_layout_class.swiftmodule -module-name fixed_layout_class -I%t -L%t -lresilient_struct_wmo -whole-module-optimization
// RUN: %target-codesign %t/%target-library-name(fixed_layout_class_wmo)
// RUN: %target-build-swift %s -L %t -I %t -lresilient_struct_wmo -lresilient_class_wmo -lfixed_layout_class_wmo -o %t/main2 %target-rpath(%t) -module-name main
// RUN: %target-codesign %t/main2
// RUN: %target-run %t/main2 %t/%target-library-name(resilient_struct_wmo) %t/%target-library-name(resilient_class_wmo) %t/%target-library-name(fixed_layout_class_wmo)
// REQUIRES: executable_test
import StdlibUnittest
import fixed_layout_class
import resilient_class
import resilient_struct
var ResilientClassTestSuite = TestSuite("ResilientClass")
// Concrete class with resilient stored property
protocol ProtocolWithResilientProperty {
var s: Size { get }
}
public class ClassWithResilientProperty : ProtocolWithResilientProperty {
public let p: Point
public let s: Size
public let color: Int32
public init(p: Point, s: Size, color: Int32) {
self.p = p
self.s = s
self.color = color
}
}
@inline(never) func getS(_ p: ProtocolWithResilientProperty) -> Size {
return p.s
}
ResilientClassTestSuite.test("ClassWithResilientProperty") {
let c = ClassWithResilientProperty(
p: Point(x: 10, y: 20),
s: Size(w: 30, h: 40),
color: 50)
expectEqual(c.p.x, 10)
expectEqual(c.p.y, 20)
expectEqual(c.s.w, 30)
expectEqual(c.s.h, 40)
expectEqual(c.color, 50)
// Make sure the conformance works
expectEqual(getS(c).w, 30)
expectEqual(getS(c).h, 40)
}
ResilientClassTestSuite.test("OutsideClassWithResilientProperty") {
let c = OutsideParentWithResilientProperty(
p: Point(x: 10, y: 20),
s: Size(w: 30, h: 40),
color: 50)
expectEqual(c.p.x, 10)
expectEqual(c.p.y, 20)
expectEqual(c.s.w, 30)
expectEqual(c.s.h, 40)
expectEqual(c.color, 50)
expectEqual(0, c.laziestNumber)
c.laziestNumber = 1
expectEqual(1, c.laziestNumber)
}
// Generic class with resilient stored property
public class GenericClassWithResilientProperty<T> {
public let s1: Size
public let t: T
public let s2: Size
public init(s1: Size, t: T, s2: Size) {
self.s1 = s1
self.t = t
self.s2 = s2
}
}
ResilientClassTestSuite.test("GenericClassWithResilientProperty") {
let c = GenericClassWithResilientProperty<Int32>(
s1: Size(w: 10, h: 20),
t: 30,
s2: Size(w: 40, h: 50))
expectEqual(c.s1.w, 10)
expectEqual(c.s1.h, 20)
expectEqual(c.t, 30)
expectEqual(c.s2.w, 40)
expectEqual(c.s2.h, 50)
}
// Concrete class with non-fixed size stored property
public class ClassWithResilientlySizedProperty {
public let r: Rectangle
public let color: Int32
public init(r: Rectangle, color: Int32) {
self.r = r
self.color = color
}
}
ResilientClassTestSuite.test("ClassWithResilientlySizedProperty") {
let c = ClassWithResilientlySizedProperty(
r: Rectangle(
p: Point(x: 10, y: 20),
s: Size(w: 30, h: 40),
color: 50),
color: 60)
expectEqual(c.r.p.x, 10)
expectEqual(c.r.p.y, 20)
expectEqual(c.r.s.w, 30)
expectEqual(c.r.s.h, 40)
expectEqual(c.r.color, 50)
expectEqual(c.color, 60)
}
// Concrete subclass of fixed-layout class with resilient stored property
public class ChildOfParentWithResilientStoredProperty : ClassWithResilientProperty {
let enabled: Int32
public init(p: Point, s: Size, color: Int32, enabled: Int32) {
self.enabled = enabled
super.init(p: p, s: s, color: color)
}
}
ResilientClassTestSuite.test("ChildOfParentWithResilientStoredProperty") {
let c = ChildOfParentWithResilientStoredProperty(
p: Point(x: 10, y: 20),
s: Size(w: 30, h: 40),
color: 50,
enabled: 60)
expectEqual(c.p.x, 10)
expectEqual(c.p.y, 20)
expectEqual(c.s.w, 30)
expectEqual(c.s.h, 40)
expectEqual(c.color, 50)
expectEqual(c.enabled, 60)
}
// Concrete subclass of fixed-layout class with resilient stored property
public class ChildOfOutsideParentWithResilientStoredProperty : OutsideParentWithResilientProperty {
let enabled: Int32
public init(p: Point, s: Size, color: Int32, enabled: Int32) {
self.enabled = enabled
super.init(p: p, s: s, color: color)
}
}
ResilientClassTestSuite.test("ChildOfOutsideParentWithResilientStoredProperty") {
let c = ChildOfOutsideParentWithResilientStoredProperty(
p: Point(x: 10, y: 20),
s: Size(w: 30, h: 40),
color: 50,
enabled: 60)
expectEqual(c.p.x, 10)
expectEqual(c.p.y, 20)
expectEqual(c.s.w, 30)
expectEqual(c.s.h, 40)
expectEqual(c.color, 50)
expectEqual(c.enabled, 60)
}
// Resilient class from a different resilience domain
ResilientClassTestSuite.test("ResilientOutsideParent") {
let c = ResilientOutsideParent()
expectEqual(c.property, "ResilientOutsideParent.property")
expectEqual(c.finalProperty, "ResilientOutsideParent.finalProperty")
}
// Concrete subclass of resilient class
public class ChildOfResilientOutsideParent : ResilientOutsideParent {
let enabled: Int32
public init(enabled: Int32) {
self.enabled = enabled
super.init()
}
}
ResilientClassTestSuite.test("ChildOfResilientOutsideParent") {
let c = ChildOfResilientOutsideParent(enabled: 60)
expectEqual(c.property, "ResilientOutsideParent.property")
expectEqual(c.finalProperty, "ResilientOutsideParent.finalProperty")
expectEqual(c.enabled, 60)
}
// Concrete subclass of resilient class
public class ChildOfResilientOutsideParentWithResilientStoredProperty : ResilientOutsideParent {
public let p: Point
public let s: Size
public let color: Int32
public init(p: Point, s: Size, color: Int32) {
self.p = p
self.s = s
self.color = color
super.init()
}
}
ResilientClassTestSuite.test("ChildOfResilientOutsideParentWithResilientStoredProperty") {
let c = ChildOfResilientOutsideParentWithResilientStoredProperty(
p: Point(x: 10, y: 20),
s: Size(w: 30, h: 40),
color: 50)
expectEqual(c.property, "ResilientOutsideParent.property")
expectEqual(c.finalProperty, "ResilientOutsideParent.finalProperty")
expectEqual(c.p.x, 10)
expectEqual(c.p.y, 20)
expectEqual(c.s.w, 30)
expectEqual(c.s.h, 40)
expectEqual(c.color, 50)
}
class ChildWithMethodOverride : ResilientOutsideParent {
override func getValue() -> Int {
return 1
}
}
ResilientClassTestSuite.test("ChildWithMethodOverride") {
let c = ChildWithMethodOverride()
expectEqual(c.getValue(), 1)
}
ResilientClassTestSuite.test("TypeByName") {
expectTrue(_typeByName("main.ClassWithResilientProperty")
== ClassWithResilientProperty.self)
expectTrue(_typeByName("main.ClassWithResilientlySizedProperty")
== ClassWithResilientlySizedProperty.self)
expectTrue(_typeByName("main.ChildOfParentWithResilientStoredProperty")
== ChildOfParentWithResilientStoredProperty.self)
expectTrue(_typeByName("main.ChildOfOutsideParentWithResilientStoredProperty")
== ChildOfOutsideParentWithResilientStoredProperty.self)
}
@_fixed_layout
public struct Empty {}
// rdar://48031465
public class ClassWithEmptyThenResilient {
public let empty: Empty
public let resilient: ResilientInt
public init(empty: Empty, resilient: ResilientInt) {
self.empty = empty
self.resilient = resilient
}
}
ResilientClassTestSuite.test("EmptyThenResilient") {
let c = ClassWithEmptyThenResilient(empty: Empty(),
resilient: ResilientInt(i: 17))
expectEqual(c.resilient.i, 17)
}
public class ClassWithResilientThenEmpty {
public let resilient: ResilientInt
public let empty: Empty
public init(empty: Empty, resilient: ResilientInt) {
self.empty = empty
self.resilient = resilient
}
}
ResilientClassTestSuite.test("ResilientThenEmpty") {
let c = ClassWithResilientThenEmpty(empty: Empty(),
resilient: ResilientInt(i: 17))
expectEqual(c.resilient.i, 17)
}
// This test triggers SR-815 (rdar://problem/25318716) on macOS 10.9 and iOS 7.
// Disable it for now when testing on those versions.
if #available(macOS 10.10, iOS 8, *) {
runAllTests()
} else {
runNoTests()
}
| apache-2.0 |
sjpsega/JustDoIt | JustDoIt/view/base/JDIBaseVC.swift | 1 | 845 | //
// JDIBaseVCViewController.swift
// JustDoIt
//
// Created by sjpsega on 15/10/9.
// Copyright © 2015年 sjpsega. All rights reserved.
//
import UIKit
class JDIBaseVC: UIViewController {
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil);
self.tabBarItem = UITabBarItem(title: "", image: UIImage(named: "check"), tag: 0);
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
zalando/ModularDemo | ZContainer/ZContainerTests/DefaultContainerTests.swift | 1 | 716 | //
// DefaultContainerTests.swift
// ZContainerTests
//
// Created by Oliver Eikemeier on 25.09.15.
// Copyright © 2015 Zalando SE. All rights reserved.
//
import XCTest
@testable import ZContainer
class DefaultContainerTests: XCTestCase {
override func setUp() {
super.setUp()
let registry = ZContainer.defaultRegistry()
registry.register { ServiceImplementation() as Service }
}
struct ContainerTest {
private let service: Service
init() {
let container = ZContainer.defaultContainer()
service = container.resolve()
}
}
func testDefaultZContainer() {
let _ = ContainerTest()
}
}
| bsd-2-clause |
huangboju/Moots | Examples/SwiftUI/Mac/swiftui-mac-master/SwiftUI-Mac/Prefs/Prefs.swift | 1 | 417 | //
// Prefs.swift
// SwiftUI-Mac
//
// Created by Sarah Reichelt on 7/11/19.
// Copyright © 2019 Sarah Reichelt. All rights reserved.
//
import Foundation
class Prefs: ObservableObject {
@Published var showCopyright: Bool = UserDefaults.standard.bool(forKey: "showCopyright") {
didSet {
UserDefaults.standard.set(self.showCopyright, forKey: "showCopyright")
}
}
}
| mit |
ResearchSuite/ResearchSuiteAppFramework-iOS | Source/Core/Classes/RSAFCoreState.swift | 1 | 2949 | //
// RSAFReduxState.swift
// Pods
//
// Created by James Kizer on 3/22/17.
//
//
import UIKit
import ReSwift
import ResearchKit
import ResearchSuiteTaskBuilder
import ResearchSuiteResultsProcessor
public final class RSAFCoreState: RSAFBaseState {
let loggedIn: Bool
public typealias ActivityQueueElement = (UUID, RSAFActivityRun, RSTBTaskBuilder)
let activityQueue: [ActivityQueueElement]
// let resultsQueue: [(UUID, RSAFActivityRun, ORKTaskResult)]
let extensibleStorage: [String: NSObject]
let taskBuilder: RSTBTaskBuilder?
let resultsProcessor: RSRPResultsProcessor?
let titleLabelText: String?
let titleImage: UIImage?
public init(loggedIn: Bool = false,
activityQueue: [ActivityQueueElement] = [],
resultsQueue: [(UUID, RSAFActivityRun, ORKTaskResult)] = [],
extensibleStorage: [String: NSObject] = [:],
taskBuilder: RSTBTaskBuilder? = nil,
resultsProcessor: RSRPResultsProcessor? = nil,
titleLabelText: String? = nil,
titleImage: UIImage? = nil
) {
self.loggedIn = loggedIn
self.activityQueue = activityQueue
// self.resultsQueue = resultsQueue
self.extensibleStorage = extensibleStorage
self.taskBuilder = taskBuilder
self.resultsProcessor = resultsProcessor
self.titleLabelText = titleLabelText
self.titleImage = titleImage
super.init()
}
public required override convenience init() {
self.init(loggedIn: false)
}
static func newState(
fromState: RSAFCoreState,
loggedIn: Bool? = nil,
activityQueue: [ActivityQueueElement]? = nil,
resultsQueue: [(UUID, RSAFActivityRun, ORKTaskResult)]? = nil,
extensibleStorage: [String: NSObject]? = nil,
taskBuilder: (RSTBTaskBuilder?)? = nil,
resultsProcessor: (RSRPResultsProcessor?)? = nil,
titleLabelText: (String?)? = nil,
titleImage: (UIImage?)? = nil
) -> RSAFCoreState {
return RSAFCoreState(
loggedIn: loggedIn ?? fromState.loggedIn,
activityQueue: activityQueue ?? fromState.activityQueue,
// resultsQueue: resultsQueue ?? fromState.resultsQueue,
extensibleStorage: extensibleStorage ?? fromState.extensibleStorage,
taskBuilder: taskBuilder ?? fromState.taskBuilder,
resultsProcessor: resultsProcessor ?? fromState.resultsProcessor,
titleLabelText: titleLabelText ?? fromState.titleLabelText,
titleImage: titleImage ?? fromState.titleImage
)
}
open override var description: String {
return
"\n\tloggedIn: \(self.loggedIn)" +
"\n\tactivityQueue: \(self.activityQueue)" +
// "\n\tresultsQueue: \(self.resultsQueue)"+
"\n\textensibleStorage: \(self.extensibleStorage)"
}
}
| apache-2.0 |
DragonCherry/AssetsPickerViewController | AssetsPickerViewController/Classes/Photo/Controller/AssetsPhotoViewController+Selection.swift | 1 | 4248 | //
// AssetsPhotoViewController+Selection.swift
// AssetsPickerViewController
//
// Created by DragonCherry on 2020/07/03.
//
import UIKit
import Photos
// MARK: - UICollectionViewDelegate
extension AssetsPhotoViewController: UICollectionViewDelegate {
@available(iOS 13.0, *)
public func collectionView(_ collectionView: UICollectionView, shouldBeginMultipleSelectionInteractionAt indexPath: IndexPath) -> Bool {
return true
}
public func collectionView(_ collectionView: UICollectionView, didBeginMultipleSelectionInteractionAt indexPath: IndexPath) {
isDragSelectionEnabled = true
}
public func collectionViewDidEndMultipleSelectionInteraction(_ collectionView: UICollectionView) {
isDragSelectionEnabled = false
}
public func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
return true
}
public func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
if LogConfig.isSelectLogEnabled { logi("shouldSelectItemAt: \(indexPath.row)") }
if let delegate = self.delegate {
guard let fetchResult = AssetsManager.shared.fetchResult else { return false }
let shouldSelect = delegate.assetsPicker?(controller: picker, shouldSelect: fetchResult.object(at: indexPath.row), at: indexPath) ?? true
guard shouldSelect else { return false }
}
if isDragSelectionEnabled {
if selectedArray.count < pickerConfig.assetsMaximumSelectionCount {
select(at: indexPath)
return true
} else {
return false
}
} else {
select(at: indexPath)
return true
}
}
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if LogConfig.isSelectLogEnabled { logi("didSelectItemAt: \(indexPath.row)") }
if !isDragSelectionEnabled {
deselectOldestIfNeeded()
}
updateSelectionCount()
updateNavigationStatus()
checkInconsistencyForSelection()
}
public func collectionView(_ collectionView: UICollectionView, shouldDeselectItemAt indexPath: IndexPath) -> Bool {
if LogConfig.isSelectLogEnabled { logi("shouldDeselectItemAt: \(indexPath.row)") }
if let delegate = self.delegate {
guard let fetchResult = AssetsManager.shared.fetchResult else { return false }
let shouldDeselect = delegate.assetsPicker?(controller: picker, shouldDeselect: fetchResult.object(at: indexPath.row), at: indexPath) ?? true
guard shouldDeselect else { return false }
}
deselect(at: indexPath)
return true
}
public func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
if LogConfig.isSelectLogEnabled { logi("didDeselectItemAt: \(indexPath.row)") }
updateSelectionCount()
updateNavigationStatus()
checkInconsistencyForSelection()
}
}
extension AssetsPhotoViewController {
func checkInconsistencyForSelection() {
guard LogConfig.isSelectLogEnabled else { return }
if let indexPathsForSelectedItems = collectionView.indexPathsForSelectedItems, !indexPathsForSelectedItems.isEmpty {
if selectedArray.count != indexPathsForSelectedItems.count || selectedMap.count != indexPathsForSelectedItems.count {
loge("selected item count not matched!")
return
}
for selectedIndexPath in indexPathsForSelectedItems {
guard let fetchResult = AssetsManager.shared.fetchResult else { return }
if let _ = selectedMap[fetchResult.object(at: selectedIndexPath.row).localIdentifier] {
} else {
loge("selected item not found in local map!")
}
}
} else {
if !selectedMap.isEmpty || !selectedArray.isEmpty {
loge("selected items not matched!")
}
}
}
}
| mit |
dasdom/Storybard2CodeApp | Example/LoginDemo/LoginDemo/FooViewController.swift | 2 | 864 | //
// FooViewController.swift
// LoginDemo
//
// Created by dasdom on 13.05.16.
// Copyright © 2016 dasdom. All rights reserved.
//
import UIKit
class FooViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// 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 |
alldne/PolarKit | PolarKit/Classes/PolarCoordinatedView.swift | 1 | 1131 | //
// PolarCoordinatedView.swift
// PolarKit
//
// Created by Yonguk Jeong on 2016. 4. 18..
// Copyright © 2016년 Yonguk Jeong. All rights reserved.
//
import UIKit
open class PolarCoordinatedView: UIView {
override open class var layerClass : AnyClass {
return PolarCoordinatedLayer.self
}
override open var layer: PolarCoordinatedLayer {
return super.layer as! PolarCoordinatedLayer
}
open var radius: Double {
set {
self.layer.radius = newValue
}
get {
return self.layer.radius
}
}
open var angle: Double {
set {
self.layer.angle = newValue
}
get {
return self.layer.angle
}
}
public init(radius: Double, angle: Double, frame: CGRect) {
super.init(frame: frame)
self.radius = radius
self.angle = angle
}
convenience public init() {
self.init(radius: 0, angle: 0, frame: CGRect.zero)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit |
wangjianquan/wjKeyBoard | wjKeyBoard/PhotoBrowersViewController.swift | 1 | 2003 | //
// PhotoBrowersViewController.swift
// CustomKeyboard
//
// Created by landixing on 2017/6/16.
// Copyright © 2017年 WJQ. All rights reserved.
//
import UIKit
class PhotoBrowersViewController: UIViewController {
var imageView : UIImageView = {
let imageview : UIImageView = UIImageView()
imageview.contentMode = .scaleAspectFit
imageview.clipsToBounds = true
return imageview
}()
var image : UIImage?
{
didSet{
guard let image = image else { return
}
self.imageView.image = image
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
displayPhoto()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension PhotoBrowersViewController {
fileprivate func setupUI() {
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "back", style: .plain, target: self, action: #selector(PhotoBrowersViewController.back))
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "delete", style: .plain, target: self, action: #selector(PhotoBrowersViewController.deleteImage))
view.addSubview(imageView)
imageView.frame = CGRect(x: 0, y: 64, width: view.frame.size.width, height: view.frame.size.height - 64)
}
fileprivate func displayPhoto() {
}
}
extension PhotoBrowersViewController {
@objc fileprivate func back() {
}
@objc fileprivate func deleteImage() {
navigationController?.popViewController(animated: true)
}
}
| apache-2.0 |
artkirillov/DesignPatterns | Iterator.playground/Pages/2.xcplaygroundpage/Contents.swift | 1 | 1500 | final class Destination {
let name: String
init(name: String) {
self.name = name
}
}
final class DestinationList: Sequence {
var destinations: [Destination]
init(destinations: [Destination]) {
self.destinations = destinations
}
func makeIterator() -> DestinationIterator {
return DestinationIterator(destinationList: self)
}
}
final class DestinationIterator: IteratorProtocol {
private var current = 0
private let destinations: [Destination]
init(destinationList: DestinationList) {
self.destinations = destinationList.destinations
}
func next() -> Destination? {
let next = current < destinations.count ? destinations[current] : nil
current += 1
return next
}
}
final class DestinationIterator2: IteratorProtocol {
private var current: Int
private let destinations: [Destination]
init(destinationList: DestinationList) {
self.destinations = destinationList.destinations
self.current = destinations.count - 1
}
func next() -> Destination? {
let next = current >= 0 ? destinations[current] : nil
current -= 1
return next
}
}
let list = DestinationList(destinations: [
Destination(name: "Destination 1"),
Destination(name: "Destination 2"),
Destination(name: "Destination 3")
]
)
for destination in list {
print(destination.name)
}
list.forEach { print($0.name) }
| mit |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformUIKit/NewActivity/ActivityItemViewModel.swift | 1 | 16355 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BlockchainComponentLibrary
import Localization
import PlatformKit
import RxDataSources
import ToolKit
public final class ActivityItemViewModel: IdentifiableType, Hashable {
typealias AccessibilityId = Accessibility.Identifier.Activity
typealias LocalizationStrings = LocalizationConstants.Activity.MainScreen.Item
public typealias Descriptors = AssetBalanceViewModel.Value.Presentation.Descriptors
public var identity: AnyHashable {
event
}
public var descriptors: Descriptors {
let accessibility = AccessibilityId.ActivityCell.self
switch event.status {
case .pending:
return .muted(
cryptoAccessiblitySuffix: accessibility.cryptoValuePrefix,
fiatAccessiblitySuffix: accessibility.fiatValuePrefix
)
case .complete:
return .activity(
cryptoAccessiblitySuffix: accessibility.cryptoValuePrefix,
fiatAccessiblitySuffix: accessibility.fiatValuePrefix
)
case .product:
return .activity(
cryptoAccessiblitySuffix: accessibility.cryptoValuePrefix,
fiatAccessiblitySuffix: accessibility.fiatValuePrefix
)
}
}
public var titleLabelContent: LabelContent {
var text = ""
switch event {
case .buySell(let orderDetails):
switch (orderDetails.status, orderDetails.isBuy) {
case (.pending, true):
text = "\(LocalizationStrings.buying) \(orderDetails.outputValue.currency.displayCode)"
case (_, true):
text = "\(LocalizationStrings.buy) \(orderDetails.outputValue.currency.displayCode)"
case (_, false):
text = [
LocalizationStrings.sell,
orderDetails.inputValue.currency.displayCode,
"->",
orderDetails.outputValue.currency.displayCode
].joined(separator: " ")
}
case .interest(let event):
switch (event.type, event.state) {
case (.withdraw, .complete):
text = LocalizationStrings.withdraw + " \(event.cryptoCurrency.code)"
case (.withdraw, .pending),
(.withdraw, .processing),
(.withdraw, .manualReview):
text = LocalizationStrings.withdrawing + " \(event.cryptoCurrency.code)"
case (.interestEarned, _):
text = event.cryptoCurrency.code + " \(LocalizationStrings.rewardsEarned)"
case (.transfer, _):
text = LocalizationStrings.added + " \(event.cryptoCurrency.code)"
default:
unimplemented()
}
case .swap(let event):
let pair = event.pair
switch (event.status, pair.outputCurrencyType) {
case (.complete, .crypto):
text = LocalizationStrings.swap
case (.complete, .fiat):
text = LocalizationStrings.sell
case (_, .crypto):
text = LocalizationStrings.pendingSwap
case (_, .fiat):
text = LocalizationStrings.pendingSell
}
text += " \(pair.inputCurrencyType.displayCode) -> \(pair.outputCurrencyType.displayCode)"
case .simpleTransactional(let event):
switch (event.status, event.type) {
case (.pending, .receive):
text = LocalizationStrings.receiving + " \(event.currency.displayCode)"
case (.pending, .send):
text = LocalizationStrings.sending + " \(event.currency.displayCode)"
case (.complete, .receive):
text = LocalizationStrings.receive + " \(event.currency.displayCode)"
case (.complete, .send):
text = LocalizationStrings.send + " \(event.currency.displayCode)"
}
case .transactional(let event):
switch (event.status, event.type) {
case (.pending, .receive):
text = LocalizationStrings.receiving + " \(event.currency.displayCode)"
case (.pending, .send):
text = LocalizationStrings.sending + " \(event.currency.displayCode)"
case (.complete, .receive):
text = LocalizationStrings.receive + " \(event.currency.displayCode)"
case (.complete, .send):
text = LocalizationStrings.send + " \(event.currency.displayCode)"
}
case .fiat(let event):
switch (event.type, event.state) {
case (.deposit, .completed):
text = LocalizationStrings.deposit + " \(event.amount.displayCode)"
case (.withdrawal, .completed):
text = LocalizationStrings.withdraw + " \(event.amount.displayCode)"
case (.deposit, _):
text = LocalizationStrings.depositing + " \(event.amount.displayCode)"
case (.withdrawal, _):
text = LocalizationStrings.withdrawing + " \(event.amount.displayCode)"
}
case .crypto(let event):
switch (event.state, event.type) {
case (.pending, .deposit):
text = LocalizationStrings.receiving + " \(event.amount.displayCode)"
case (.pending, .withdrawal):
text = LocalizationStrings.sending + " \(event.amount.displayCode)"
case (_, .deposit):
text = LocalizationStrings.receive + " \(event.amount.displayCode)"
case (_, .withdrawal):
text = LocalizationStrings.send + " \(event.amount.displayCode)"
}
}
return .init(
text: text,
font: descriptors.primaryFont,
color: descriptors.primaryTextColor,
alignment: .left,
adjustsFontSizeToFitWidth: .true(factor: 0.75),
accessibility: .id(AccessibilityId.ActivityCell.titleLabel)
)
}
public var descriptionLabelContent: LabelContent {
switch event.status {
case .pending(confirmations: let confirmations):
return .init(
text: "\(confirmations.current) \(LocalizationStrings.of) \(confirmations.total)",
font: descriptors.secondaryFont,
color: descriptors.secondaryTextColor,
alignment: .left,
accessibility: .id(AccessibilityId.ActivityCell.descriptionLabel)
)
case .complete:
return .init(
text: DateFormatter.medium.string(from: event.creationDate),
font: descriptors.secondaryFont,
color: descriptors.secondaryTextColor,
alignment: .left,
accessibility: .id(AccessibilityId.ActivityCell.descriptionLabel)
)
case .product(let status):
let failedLabelContent: LabelContent = .init(
text: LocalizationStrings.failed,
font: descriptors.secondaryFont,
color: .destructive,
alignment: .left,
accessibility: .id(AccessibilityId.ActivityCell.descriptionLabel)
)
switch status {
case .custodial(let status):
switch status {
case .failed:
return failedLabelContent
case .completed, .pending:
break
}
case .interest(let state):
switch state {
case .processing,
.pending,
.manualReview:
return .init(
text: LocalizationStrings.pending,
font: descriptors.secondaryFont,
color: descriptors.secondaryTextColor,
alignment: .left,
accessibility: .id(AccessibilityId.ActivityCell.descriptionLabel)
)
case .failed,
.rejected,
.refunded:
return failedLabelContent
case .cleared,
.complete,
.unknown:
return .init(
text: DateFormatter.medium.string(from: event.creationDate),
font: descriptors.secondaryFont,
color: descriptors.secondaryTextColor,
alignment: .left,
accessibility: .id(AccessibilityId.ActivityCell.descriptionLabel)
)
}
case .buySell(let status):
if status == .failed {
return failedLabelContent
}
case .swap(let status):
if status == .failed {
return failedLabelContent
}
}
return .init(
text: DateFormatter.medium.string(from: event.creationDate),
font: descriptors.secondaryFont,
color: descriptors.secondaryTextColor,
alignment: .left,
accessibility: .id(AccessibilityId.ActivityCell.descriptionLabel)
)
}
}
/// The color of the `EventType` image.
public var eventColor: UIColor {
switch event {
case .buySell(let orderDetails):
switch (orderDetails.status, orderDetails.isBuy) {
case (.failed, _):
return .destructive
case (_, true):
return orderDetails.outputValue.currency.brandUIColor
case (_, false):
return orderDetails.inputValue.currency.brandUIColor
}
case .swap(let event):
if event.status == .failed {
return .destructive
}
return event.pair.inputCurrencyType.brandUIColor
case .interest(let interest):
switch interest.state {
case .pending,
.processing,
.manualReview:
return .mutedText
case .failed,
.rejected:
return .destructive
case .refunded,
.cleared,
.unknown,
.complete:
return interest.cryptoCurrency.brandUIColor
}
case .fiat(let event):
switch event.state {
case .failed:
return .destructive
case .pending:
return .mutedText
case .completed:
return event.amount.currency.brandColor
}
case .crypto(let event):
switch event.state {
case .failed:
return .destructive
case .pending:
return .mutedText
case .completed:
return event.amount.currencyType.brandUIColor
}
case .simpleTransactional(let event):
switch event.status {
case .complete:
return event.currency.brandUIColor
case .pending:
return .mutedText
}
case .transactional(let event):
switch event.status {
case .complete:
return event.currency.brandUIColor
case .pending:
return .mutedText
}
}
}
/// The fill color of the `BadgeImageView`
public var backgroundColor: UIColor {
eventColor.withAlphaComponent(0.15)
}
/// The `imageResource` for the `BadgeImageViewModel`
public var imageResource: ImageResource {
switch event {
case .interest(let interest):
switch interest.state {
case .pending,
.processing,
.manualReview:
return .local(name: "clock-icon", bundle: .platformUIKit)
case .failed,
.rejected:
return .local(name: "activity-failed-icon", bundle: .platformUIKit)
case .complete:
switch interest.type {
case .transfer:
return .local(name: "plus-icon", bundle: .platformUIKit)
case .withdraw:
return .local(name: "minus-icon", bundle: .platformUIKit)
case .interestEarned:
return .local(name: Icon.interest.name, bundle: .componentLibrary)
case .unknown:
// NOTE: `.unknown` is filtered out in
// the `ActivityScreenInteractor`
assertionFailure("Unexpected case for interest \(interest.state)")
return .local(name: Icon.question.name, bundle: .componentLibrary)
}
case .cleared:
return .local(name: "clock-icon", bundle: .platformUIKit)
case .refunded,
.unknown:
assertionFailure("Unexpected case for interest \(interest.state)")
return .local(name: Icon.question.name, bundle: .componentLibrary)
}
case .buySell(let value):
if value.status == .failed {
return .local(name: "activity-failed-icon", bundle: .platformUIKit)
}
let imageName = value.isBuy ? "plus-icon" : "minus-icon"
return .local(name: imageName, bundle: .platformUIKit)
case .fiat(let event):
switch event.state {
case .failed:
return .local(name: "activity-failed-icon", bundle: .platformUIKit)
case .pending:
return .local(name: "clock-icon", bundle: .platformUIKit)
case .completed:
switch event.type {
case .deposit:
return .local(name: "deposit-icon", bundle: .platformUIKit)
case .withdrawal:
return .local(name: "withdraw-icon", bundle: .platformUIKit)
}
}
case .crypto(let event):
switch event.state {
case .failed:
return .local(name: "activity-failed-icon", bundle: .platformUIKit)
case .pending:
return .local(name: "clock-icon", bundle: .platformUIKit)
case .completed:
switch event.type {
case .deposit:
return .local(name: "receive-icon", bundle: .platformUIKit)
case .withdrawal:
return .local(name: "send-icon", bundle: .platformUIKit)
}
}
case .swap(let event):
if event.status == .failed {
return .local(name: "activity-failed-icon", bundle: .platformUIKit)
}
return .local(name: "swap-icon", bundle: .platformUIKit)
case .transactional(let event):
switch (event.status, event.type) {
case (.pending, _):
return .local(name: "clock-icon", bundle: .platformUIKit)
case (_, .send):
return .local(name: "send-icon", bundle: .platformUIKit)
case (_, .receive):
return .local(name: "receive-icon", bundle: .platformUIKit)
}
case .simpleTransactional(let event):
switch (event.status, event.type) {
case (.pending, _):
return .local(name: "clock-icon", bundle: .platformUIKit)
case (_, .send):
return .local(name: "send-icon", bundle: .platformUIKit)
case (_, .receive):
return .local(name: "receive-icon", bundle: .platformUIKit)
}
}
}
public let event: ActivityItemEvent
public init(event: ActivityItemEvent) {
self.event = event
}
public func hash(into hasher: inout Hasher) {
hasher.combine(event)
}
}
extension ActivityItemViewModel: Equatable {
public static func == (lhs: ActivityItemViewModel, rhs: ActivityItemViewModel) -> Bool {
lhs.event == rhs.event
}
}
| lgpl-3.0 |
blockchain/My-Wallet-V3-iOS | Modules/FeatureNFT/Sources/FeatureNFTData/Core/Repository/ViewWaitlistRegistrationRepository.swift | 1 | 1122 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import Errors
import FeatureNFTDomain
import NetworkKit
import ToolKit
public final class ViewWaitlistRegistrationRepository: ViewWaitlistRegistrationRepositoryAPI {
private let client: FeatureNFTClientAPI
private let emailAddressPublisher: AnyPublisher<String, Error>
public init(
client: FeatureNFTClientAPI,
emailAddressPublisher: AnyPublisher<String, Error>
) {
self.client = client
self.emailAddressPublisher = emailAddressPublisher
}
// MARK: - ViewWaitlistRegistrationRepositoryAPI
public func registerEmailForNFTViewWaitlist()
-> AnyPublisher<Void, ViewWalletRegistrationServiceError>
{
emailAddressPublisher
.replaceError(with: ViewWalletRegistrationServiceError.emailUnavailable)
.flatMap { [client] email in
client
.registerEmailForNFTViewWaitlist(email)
.mapError(ViewWalletRegistrationServiceError.network)
}
.eraseToAnyPublisher()
}
}
| lgpl-3.0 |
andreamazz/Tropos | Sources/TroposIntents/IntentHandler.swift | 3 | 312 | import Intents
import TroposCore
final class IntentHandler: INExtension {
override func handler(for intent: INIntent) -> Any {
guard intent is CheckWeatherIntent else {
preconditionFailure("Unexpected intent type: \(intent)")
}
return CheckWeatherIntentHandler()
}
}
| mit |
slavapestov/swift | validation-test/compiler_crashers_fixed/26948-swift-nominaltypedecl-getmembers.swift | 4 | 373 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct c<T where h:A{
struct b{
var b
let a=b{
if{
{
protocol A{
{{
}
}
struct b
{
class A{
let a{class
e c{D>{
extension{struct B{
class b{
let a{{
}
enum b
| apache-2.0 |
Reality-Virtually-Hackathon/Team-2 | WorkspaceAR/User Flow VCs/ViewController+Prompts.swift | 1 | 2972 | //
// ViewController+Prompts.swift
// WorkspaceAR
//
// Created by Avery Lamp on 10/7/17.
// Copyright © 2017 Apple. All rights reserved.
//
import UIKit
let hidePromptNotificationName = Notification.Name("HidePromptNotification")
extension ViewController{
func checkPrompts(){
if DataManager.shared().userType == nil, let hostClientPickerVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "HostClientPickerVC") as? HostClientPickerViewController{
hostClientPickerVC.view.frame = CGRect(x: 0, y: 0, width: 300, height: 200)
displayPrompt(viewController: hostClientPickerVC)
}
}
func sendSimpleMessage(text: String, confirm: String = "Okay", size: CGSize = CGSize(width: 300, height: 200)){
if let simpleMessageVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SimpleMessageVC") as? SimpleMessageViewController {
simpleMessageVC.view.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
simpleMessageVC.titleLabel.text = text
simpleMessageVC.confirmButton.setTitle(confirm, for: .normal)
displayPrompt(viewController: simpleMessageVC)
}
}
func displayPrompt(viewController: UIViewController) {
if currentPromptViewController != nil {
hidePrompt()
}
self.view.bringSubview(toFront: fadeView)
let animationDistance:CGFloat = 80
let animationDuration = 0.5
self.addChildViewController(viewController)
self.view.addSubview(viewController.view)
viewController.didMove(toParentViewController: self)
viewController.view.center = CGPoint(x: self.view.center.x, y: self.view.center.y - animationDistance)
viewController.view.alpha = 0.0
UIView.animate(withDuration: animationDuration) {
viewController.view.alpha = 1.0
viewController.view.center.y += animationDistance
self.fadeView.alpha = 0.5
}
fadeView.isUserInteractionEnabled = true
currentPromptViewController = viewController
}
@objc func hidePrompt(){
if let vc = currentPromptViewController{
let animationDistance:CGFloat = 80
let animationDuration = 0.5
UIView.animate(withDuration: animationDuration, animations: {
vc.view.center.y += animationDistance
vc.view.alpha = 0.0
self.fadeView.alpha = 0.0
}, completion: { (finished) in
vc.view.removeFromSuperview()
vc.removeFromParentViewController()
self.currentPromptViewController = nil
})
fadeView.isUserInteractionEnabled = false
}
}
@objc func fadeViewClicked(sender:UIButton){
print("Fade View clicked")
}
}
| mit |
otto-schnurr/MetalMatrixMultiply-swift | Test/MultiplicationData_tests.swift | 1 | 1897 | //
// MultiplicationData_tests.swift
//
// Created by Otto Schnurr on 12/29/2015.
// Copyright © 2015 Otto Schnurr. All rights reserved.
//
// MIT License
// file: ../LICENSE.txt
// http://opensource.org/licenses/MIT
//
import XCTest
class MultiplicationData_tests: XCTestCase {
func test_validDimensions() {
let inputA = CPUMatrix(rowCount: 2, columnCount: 4, alignment: 8)!
let inputB = CPUMatrix(rowCount: 2, columnCount: 6, alignment: 8)!
let output = CPUMatrix(rowCount: 4, columnCount: 6, alignment: 8)!
let data = TestData(inputA: inputA, inputB: inputB, output: output)
XCTAssertTrue(data.inputDimensionsAreValid)
XCTAssertTrue(data.outputDimensionsAreValid)
}
func test_invalidInputDimensions() {
let inputA = CPUMatrix(rowCount: 2, columnCount: 4, alignment: 8)!
let inputB = CPUMatrix(rowCount: 3, columnCount: 6, alignment: 8)!
let output = CPUMatrix(rowCount: 4, columnCount: 6, alignment: 8)!
let data = TestData(inputA: inputA, inputB: inputB, output: output)
XCTAssertFalse(data.inputDimensionsAreValid)
XCTAssertTrue(data.outputDimensionsAreValid)
}
func test_invalidOutputDimensions() {
let inputA = CPUMatrix(rowCount: 2, columnCount: 4, alignment: 8)!
let inputB = CPUMatrix(rowCount: 2, columnCount: 6, alignment: 8)!
let output = CPUMatrix(rowCount: 5, columnCount: 6, alignment: 8)!
let data = TestData(inputA: inputA, inputB: inputB, output: output)
XCTAssertTrue(data.inputDimensionsAreValid)
XCTAssertFalse(data.outputDimensionsAreValid)
}
}
// MARK: - Private
private struct TestData: MultiplicationData {
typealias MatrixType = BufferedMatrix
let inputA: MatrixType
let inputB: MatrixType
let output: MatrixType
}
| mit |
KennethTsang/NumberField | Example/Tests/Tests.swift | 1 | 761 | import UIKit
import XCTest
import NumberField
class Tests: 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 testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
ioswpf/CalendarKit | demo/AppDelegate.swift | 1 | 2157 | //
// AppDelegate.swift
// demo
//
// Created by wpf on 2017/3/20.
// Copyright © 2017年 wpf. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
CodeEagle/XcodeScriptsKit | build_number.swift | 1 | 1147 | #!/usr/bin/env xcrun -sdk macosx swift
import Foundation
func addBuildNumber() {
let buildKey = "CFBundleVersion"
let totalKey = "total"
var arguments: [String] = CommandLine.arguments
let dir = arguments.removeFirst() as NSString
let buildInfo = arguments.removeFirst()
let infoPlistpath = arguments.removeFirst()
var userInfo: [String : Any] = [:]
if let info = NSDictionary(contentsOfFile: buildInfo) as? [String : Any] { userInfo = info }
let array = dir.components(separatedBy: "/")
let userName = array[2]
let release = arguments.removeLast() == "1"
var count = userInfo[userName] as? Int ?? 0
count += 1
userInfo[userName] = count
var total = userInfo[totalKey] as? Int ?? 0
total += 1
userInfo[totalKey] = total
_ = (userInfo as NSDictionary).write(toFile: buildInfo, atomically: true)
if release {
guard let info = NSDictionary(contentsOfFile: infoPlistpath) as? [String : Any] else { return }
var f = info
f[buildKey] = "\(total)"
_ = (f as NSDictionary).write(toFile: infoPlistpath, atomically: true)
}
}
addBuildNumber()
| mit |
nakiostudio/EasyPeasy | Example/Tests/NodeTests.swift | 1 | 26391 | // The MIT License (MIT) - Copyright (c) 2016 Carlos Vidal
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import XCTest
@testable import EasyPeasy
class NodeTests: XCTestCase {
// MARK: Left node
func testThatLeftSubnodeIsSet() {
// given
let node = Node()
let leftAttribute = Left()
// when
_ = node.add(attribute: leftAttribute)
// then
XCTAssertNotNil(node.left)
XCTAssertTrue(node.activeAttributes.count == 1)
XCTAssertTrue(node.inactiveAttributes.count == 0)
}
func testThatLeftSubnodeIsNotSetIfAttributeConditionIsFalse() {
// given
let node = Node()
let leftAttribute = Left().when { false }
// when
_ = node.add(attribute: leftAttribute)
// then
XCTAssertNil(node.left)
XCTAssertTrue(node.activeAttributes.count == 0)
XCTAssertTrue(node.inactiveAttributes.count == 1)
XCTAssertNil(node.center)
XCTAssertNil(node.right)
XCTAssertNil(node.dimension)
}
func testThatLeftSubnodeIsUpdatedWhenReplacedWithAnotherLeft() {
// given
let node = Node()
let leftAttribute = Left()
let leadingAttribute = Leading()
_ = node.add(attribute: leftAttribute)
XCTAssertTrue(node.activeAttributes.count == 1)
XCTAssertTrue(node.inactiveAttributes.count == 0)
XCTAssertTrue(node.left === leftAttribute)
// when
_ = node.add(attribute: leadingAttribute)
// then
XCTAssertTrue(node.activeAttributes.count == 1)
XCTAssertTrue(node.inactiveAttributes.count == 0)
XCTAssertTrue(node.left === leadingAttribute)
XCTAssertNil(node.center)
XCTAssertNil(node.right)
XCTAssertNil(node.dimension)
}
func testThatLeftSubnodeIsUpdatedWhenReplacedWithCenterSubnode() {
// given
let node = Node()
let leftAttribute = Left()
let centerAttribute = CenterX()
_ = node.add(attribute: leftAttribute)
XCTAssertTrue(node.activeAttributes.count == 1)
XCTAssertTrue(node.inactiveAttributes.count == 0)
XCTAssertTrue(node.left === leftAttribute)
XCTAssertNil(node.center)
// when
_ = node.add(attribute: centerAttribute)
// then
XCTAssertTrue(node.activeAttributes.count == 1)
XCTAssertTrue(node.inactiveAttributes.count == 0)
XCTAssertTrue(node.center === centerAttribute)
XCTAssertNil(node.left)
XCTAssertNil(node.dimension)
XCTAssertNil(node.right)
}
func testThatLeftSubnodeIsNotUpdatedWhenOnlyDimensionSubnodeIsApplied() {
// given
let node = Node()
let leftAttribute = Left()
let dimensionAttribute = Width()
_ = node.add(attribute: leftAttribute)
XCTAssertTrue(node.activeAttributes.count == 1)
XCTAssertTrue(node.inactiveAttributes.count == 0)
XCTAssertTrue(node.left === leftAttribute)
XCTAssertNil(node.center)
XCTAssertNil(node.dimension)
// when
_ = node.add(attribute: dimensionAttribute)
// then
XCTAssertTrue(node.activeAttributes.count == 2)
XCTAssertTrue(node.inactiveAttributes.count == 0)
XCTAssertTrue(node.dimension === dimensionAttribute)
XCTAssertNotNil(node.left)
XCTAssertNotNil(node.dimension)
XCTAssertNil(node.center)
XCTAssertNil(node.right)
}
func testThatThereIsNotLayoutConstraintToApplyWhenSameLeftAttributeIsAddedTwice() {
// given
let node = Node()
let superview = UIView()
let view = UIView()
superview.addSubview(view)
let leftAttribute = Left()
leftAttribute.createConstraints(for: view)
let constraints = node.add(attribute: leftAttribute)
XCTAssertTrue(constraints?.0.count == 1)
XCTAssertTrue(constraints?.1.count == 0)
// when
let newConstraints = node.add(attribute: leftAttribute)
// then
XCTAssertNil(newConstraints)
}
// MARK: Right node
func testThatRightSubnodeIsSet() {
// given
let node = Node()
let rightAttribute = Right()
// when
_ = node.add(attribute: rightAttribute)
// then
XCTAssertNotNil(node.right)
XCTAssertTrue(node.activeAttributes.count == 1)
XCTAssertTrue(node.inactiveAttributes.count == 0)
}
func testThatRightSubnodeIsNotSetIfAttributeConditionIsFalse() {
// given
let node = Node()
let rightAttribute = Right().when { false }
// when
_ = node.add(attribute: rightAttribute)
// then
XCTAssertNil(node.right)
XCTAssertTrue(node.activeAttributes.count == 0)
XCTAssertTrue(node.inactiveAttributes.count == 1)
XCTAssertNil(node.center)
XCTAssertNil(node.left)
XCTAssertNil(node.dimension)
}
func testThatRightSubnodeIsUpdatedWhenReplacedWithAnotherRight() {
// given
let node = Node()
let rightAttribute = Right()
let trailingAttribute = Trailing()
_ = node.add(attribute: rightAttribute)
XCTAssertTrue(node.activeAttributes.count == 1)
XCTAssertTrue(node.inactiveAttributes.count == 0)
XCTAssertTrue(node.right === rightAttribute)
// when
_ = node.add(attribute: trailingAttribute)
// then
XCTAssertTrue(node.activeAttributes.count == 1)
XCTAssertTrue(node.inactiveAttributes.count == 0)
XCTAssertTrue(node.right === trailingAttribute)
XCTAssertNil(node.center)
XCTAssertNil(node.left)
XCTAssertNil(node.dimension)
}
func testThatRightSubnodeIsUpdatedWhenReplacedWithCenterSubnode() {
// given
let node = Node()
let rightAttribute = Right()
let centerAttribute = CenterX()
_ = node.add(attribute: rightAttribute)
XCTAssertTrue(node.activeAttributes.count == 1)
XCTAssertTrue(node.inactiveAttributes.count == 0)
XCTAssertTrue(node.right === rightAttribute)
XCTAssertNil(node.center)
// when
_ = node.add(attribute: centerAttribute)
// then
XCTAssertTrue(node.activeAttributes.count == 1)
XCTAssertTrue(node.inactiveAttributes.count == 0)
XCTAssertTrue(node.center === centerAttribute)
XCTAssertNil(node.left)
XCTAssertNil(node.dimension)
XCTAssertNil(node.right)
}
func testThatRightSubnodeIsNotUpdatedWhenOnlyDimensionSubnodeIsApplied() {
// given
let node = Node()
let rightAttribute = Right()
let dimensionAttribute = Width()
_ = node.add(attribute: rightAttribute)
XCTAssertTrue(node.activeAttributes.count == 1)
XCTAssertTrue(node.inactiveAttributes.count == 0)
XCTAssertTrue(node.right === rightAttribute)
XCTAssertNil(node.center)
XCTAssertNil(node.dimension)
// when
_ = node.add(attribute: dimensionAttribute)
// then
XCTAssertTrue(node.activeAttributes.count == 2)
XCTAssertTrue(node.inactiveAttributes.count == 0)
XCTAssertTrue(node.dimension === dimensionAttribute)
XCTAssertNotNil(node.right)
XCTAssertNotNil(node.dimension)
XCTAssertNil(node.center)
XCTAssertNil(node.left)
}
func testThatThereIsNotLayoutConstraintToApplyWhenSameRightAttributeIsAddedTwice() {
// given
let node = Node()
let superview = UIView()
let view = UIView()
superview.addSubview(view)
let rightAttribute = Right()
rightAttribute.createConstraints(for: view)
let constraints = node.add(attribute: rightAttribute)
XCTAssertTrue(constraints?.0.count == 1)
XCTAssertTrue(constraints?.1.count == 0)
// when
let newConstraints = node.add(attribute: rightAttribute)
// then
XCTAssertNil(newConstraints)
}
// MARK: Center node
func testThatCenterSubnodeIsSet() {
// given
let node = Node()
let centerAttribute = CenterX()
// when
_ = node.add(attribute: centerAttribute)
// then
XCTAssertNotNil(node.center)
XCTAssertTrue(node.activeAttributes.count == 1)
XCTAssertTrue(node.inactiveAttributes.count == 0)
}
func testThatCenterSubnodeIsNotSetIfAttributeConditionIsFalse() {
// given
let node = Node()
let centerAttribute = CenterX().when { false }
// when
_ = node.add(attribute: centerAttribute)
// then
XCTAssertNil(node.center)
XCTAssertTrue(node.activeAttributes.count == 0)
XCTAssertTrue(node.inactiveAttributes.count == 1)
XCTAssertNil(node.left)
XCTAssertNil(node.right)
XCTAssertNil(node.dimension)
}
func testThatCenterSubnodeIsUpdatedWhenReplacedWithAnotherCenter() {
// given
let node = Node()
let centerAttribute = CenterX()
let centerXWithinMarginsAttribute = CenterXWithinMargins()
_ = node.add(attribute: centerAttribute)
XCTAssertTrue(node.activeAttributes.count == 1)
XCTAssertTrue(node.inactiveAttributes.count == 0)
XCTAssertTrue(node.center === centerAttribute)
// when
_ = node.add(attribute: centerXWithinMarginsAttribute)
// then
XCTAssertTrue(node.activeAttributes.count == 1)
XCTAssertTrue(node.inactiveAttributes.count == 0)
XCTAssertTrue(node.center === centerXWithinMarginsAttribute)
XCTAssertNil(node.left)
XCTAssertNil(node.right)
XCTAssertNil(node.dimension)
}
func testThatCenterSubnodeIsUpdatedWhenReplacedWithLeftSubnode() {
// given
let node = Node()
let leftAttribute = FirstBaseline()
let centerAttribute = CenterY()
_ = node.add(attribute: centerAttribute)
XCTAssertTrue(node.activeAttributes.count == 1)
XCTAssertTrue(node.inactiveAttributes.count == 0)
XCTAssertTrue(node.center === centerAttribute)
XCTAssertNil(node.left)
// when
_ = node.add(attribute: leftAttribute)
// then
XCTAssertTrue(node.activeAttributes.count == 1)
XCTAssertTrue(node.inactiveAttributes.count == 0)
XCTAssertTrue(node.left === leftAttribute)
XCTAssertNil(node.center)
XCTAssertNil(node.dimension)
XCTAssertNil(node.right)
}
func testThatCenterSubnodeIsNotUpdatedWhenDimensionSubnodeIsApplied() {
// given
let node = Node()
let centerAttribute = CenterX()
let dimensionAttribute = Width()
_ = node.add(attribute: centerAttribute)
XCTAssertTrue(node.activeAttributes.count == 1)
XCTAssertTrue(node.inactiveAttributes.count == 0)
XCTAssertTrue(node.center === centerAttribute)
XCTAssertNil(node.left)
XCTAssertNil(node.right)
XCTAssertNil(node.dimension)
// when
_ = node.add(attribute: dimensionAttribute)
// then
XCTAssertTrue(node.activeAttributes.count == 2)
XCTAssertTrue(node.inactiveAttributes.count == 0)
XCTAssertTrue(node.dimension === dimensionAttribute)
XCTAssertNotNil(node.center)
XCTAssertNotNil(node.dimension)
XCTAssertNil(node.left)
XCTAssertNil(node.right)
}
func testThatThereIsNotLayoutConstraintToApplyWhenSameCenterAttributeIsAddedTwice() {
// given
let node = Node()
let superview = UIView()
let view = UIView()
superview.addSubview(view)
let centerAttribute = CenterX()
centerAttribute.createConstraints(for: view)
let constraints = node.add(attribute: centerAttribute)
XCTAssertTrue(constraints?.0.count == 1)
XCTAssertTrue(constraints?.1.count == 0)
// when
let newConstraints = node.add(attribute: centerAttribute)
// then
XCTAssertNil(newConstraints)
}
// MARK: Dimension node
func testThatDimensionSubnodeIsSet() {
// given
let node = Node()
let dimensionAttribute = Width()
// when
_ = node.add(attribute: dimensionAttribute)
// then
XCTAssertNotNil(node.dimension)
XCTAssertTrue(node.activeAttributes.count == 1)
XCTAssertTrue(node.inactiveAttributes.count == 0)
}
func testThatDimensionSubnodeIsNotSetIfAttributeConditionIsFalse() {
// given
let node = Node()
let dimensionAttribute = Width().when { false }
// when
_ = node.add(attribute: dimensionAttribute)
// then
XCTAssertNil(node.dimension)
XCTAssertTrue(node.activeAttributes.count == 0)
XCTAssertTrue(node.inactiveAttributes.count == 1)
XCTAssertNil(node.center)
XCTAssertNil(node.right)
XCTAssertNil(node.left)
}
func testThatDimensionSubnodeIsUpdatedWhenReplacedWithAnotherDimension() {
// given
let node = Node()
let widthAttributeA = Width()
let widthAttributeB = Width()
_ = node.add(attribute: widthAttributeA)
XCTAssertTrue(node.activeAttributes.count == 1)
XCTAssertTrue(node.inactiveAttributes.count == 0)
XCTAssertTrue(node.dimension === widthAttributeA)
// when
_ = node.add(attribute: widthAttributeB)
// then
XCTAssertTrue(node.activeAttributes.count == 1)
XCTAssertTrue(node.inactiveAttributes.count == 0)
XCTAssertTrue(node.dimension === widthAttributeB)
XCTAssertNotNil(node.dimension)
XCTAssertNil(node.center)
XCTAssertNil(node.right)
XCTAssertNil(node.left)
}
func testThatDimensionSubnodeIsNotUpdatedWhenCenterSubnodeIsApplied() {
// given
let node = Node()
let centerAttribute = CenterXWithinMargins()
let dimensionAttribute = Width()
_ = node.add(attribute: dimensionAttribute)
XCTAssertTrue(node.activeAttributes.count == 1)
XCTAssertTrue(node.inactiveAttributes.count == 0)
XCTAssertTrue(node.dimension === dimensionAttribute)
XCTAssertNil(node.center)
XCTAssertNil(node.left)
XCTAssertNil(node.right)
// when
_ = node.add(attribute: centerAttribute)
// then
XCTAssertTrue(node.activeAttributes.count == 2)
XCTAssertTrue(node.inactiveAttributes.count == 0)
XCTAssertTrue(node.dimension === dimensionAttribute)
XCTAssertTrue(node.center === centerAttribute)
XCTAssertNil(node.left)
XCTAssertNil(node.right)
}
func testThatThereIsNotLayoutConstraintToApplyWhenSameDimensionAttributeIsAddedTwice() {
// given
let node = Node()
let superview = UIView()
let view = UIView()
superview.addSubview(view)
let widthAttribute = Width()
widthAttribute.createConstraints(for: view)
let constraints = node.add(attribute: widthAttribute)
XCTAssertTrue(constraints?.0.count == 1)
XCTAssertTrue(constraints?.1.count == 0)
// when
let newConstraints = node.add(attribute: widthAttribute)
// then
XCTAssertNil(newConstraints)
}
func testThatReloadHandlesCorrectlyEachSubnode() {
// given
let superview = UIView()
let view = UIView()
superview.addSubview(view)
var value = true
let node = Node()
let leftAttributeA = LeftMargin().when { value }
leftAttributeA.createConstraints(for: view)
let leftAttributeB = Left().when { value == false }
leftAttributeB.createConstraints(for: view)
let rightAttribute = RightMargin()
rightAttribute.createConstraints(for: view)
let activationGroupA = node.add(attribute: leftAttributeA)
let activationGroupB = node.add(attribute: leftAttributeB)
let activationGroupC = node.add(attribute: rightAttribute)
let activeAttributes = node.activeAttributes
let inactiveAttributes = node.inactiveAttributes
XCTAssertTrue(activeAttributes.count == 2)
XCTAssertTrue(inactiveAttributes.count == 1)
XCTAssertTrue(node.left === leftAttributeA)
XCTAssertTrue(node.right === rightAttribute)
XCTAssertTrue(inactiveAttributes.first === leftAttributeB)
XCTAssertNil(node.center)
XCTAssertTrue(activationGroupA?.0.count == 1)
XCTAssertTrue(activationGroupA?.1.count == 0)
XCTAssertNil(activationGroupB)
XCTAssertTrue(activationGroupC?.0.count == 1)
XCTAssertTrue(activationGroupC?.1.count == 0)
// when
value = false
let reloadActivationGroup = node.reload()
// then
XCTAssertTrue(node.activeAttributes.count == 2)
XCTAssertTrue(node.inactiveAttributes.count == 1)
XCTAssertTrue(node.left === leftAttributeB)
XCTAssertTrue(node.right === rightAttribute)
XCTAssertTrue(inactiveAttributes.first === leftAttributeB)
XCTAssertNil(node.center)
XCTAssertTrue(reloadActivationGroup.0.count == 1)
XCTAssertTrue(reloadActivationGroup.1.count == 1)
// And again
// when
value = true
let reloadActivationGroupB = node.reload()
// then
XCTAssertTrue(node.activeAttributes.count == 2)
XCTAssertTrue(node.inactiveAttributes.count == 1)
XCTAssertTrue(node.left === leftAttributeA)
XCTAssertTrue(node.right === rightAttribute)
XCTAssertTrue(inactiveAttributes.first === leftAttributeB)
XCTAssertNil(node.center)
XCTAssertTrue(reloadActivationGroupB.0.count == 1)
XCTAssertTrue(reloadActivationGroupB.1.count == 1)
}
func testThatClearMethodRemovesEverySubnodeAndReturnsTheExpectedConstraints() {
// given
let superview = UIView()
let view = UIView()
superview.addSubview(view)
let node = Node()
let leftAttributeA = TopMargin().when { true }
leftAttributeA.createConstraints(for: view)
let leftAttributeB = Top().when { false }
leftAttributeB.createConstraints(for: view)
let rightAttribute = LastBaseline()
rightAttribute.createConstraints(for: view)
let dimension = Width()
dimension.createConstraints(for: view)
let center = CenterXWithinMargins().when { false }
center.createConstraints(for: view)
_ = node.add(attribute: leftAttributeA)
_ = node.add(attribute: leftAttributeB)
_ = node.add(attribute: rightAttribute)
_ = node.add(attribute: dimension)
_ = node.add(attribute: center)
XCTAssertTrue(node.left === leftAttributeA)
XCTAssertTrue(node.right === rightAttribute)
XCTAssertTrue(node.dimension === dimension)
XCTAssertTrue(node.activeAttributes.count == 3)
XCTAssertTrue(node.inactiveAttributes.count == 2)
XCTAssertNil(node.center)
// when
let constraints = node.clear()
// then
XCTAssertNil(node.left)
XCTAssertNil(node.right)
XCTAssertNil(node.dimension)
XCTAssertNil(node.center)
XCTAssertTrue(node.activeAttributes.count == 0)
XCTAssertTrue(node.inactiveAttributes.count == 0)
XCTAssertTrue(constraints.count == 3)
}
func testThatActivationGroupIsTheExpectedAddingAttributes() {
// given
let superview = UIView()
let view = UIView()
superview.addSubview(view)
let node = Node()
let leftAttributeA = Left(100)
leftAttributeA.createConstraints(for: view)
let rightAttributeA = Right(100)
rightAttributeA.createConstraints(for: view)
let activationGroupLeftA = node.add(attribute: leftAttributeA)
XCTAssertTrue(activationGroupLeftA!.0.count == 1)
XCTAssertTrue(activationGroupLeftA!.0.first === leftAttributeA.layoutConstraint)
XCTAssertTrue(activationGroupLeftA!.1.count == 0)
let activationGroupRightA = node.add(attribute: rightAttributeA)
XCTAssertTrue(activationGroupRightA!.0.count == 1)
XCTAssertTrue(activationGroupRightA!.0.first === rightAttributeA.layoutConstraint)
XCTAssertTrue(activationGroupRightA!.1.count == 0)
// when
let centerAttribute = CenterX(0.0)
centerAttribute.createConstraints(for: view)
let activationGroupCenter = node.add(attribute: centerAttribute)
// then
XCTAssertTrue(activationGroupCenter!.0.count == 1)
XCTAssertTrue(activationGroupCenter!.0.first === centerAttribute.layoutConstraint)
XCTAssertTrue(activationGroupCenter!.1.count == 2)
XCTAssertTrue(activationGroupCenter!.1[0] === leftAttributeA.layoutConstraint)
XCTAssertTrue(activationGroupCenter!.1[1] === rightAttributeA.layoutConstraint)
}
func testThatActivationGroupIsTheExpectedWhenSameAttributeIsAppliedTwice() {
// given
let superview = UIView()
let view = UIView()
superview.addSubview(view)
let node = Node()
let leftAttributeA = Left(100)
leftAttributeA.createConstraints(for: view)
let activationGroupLeftA = node.add(attribute: leftAttributeA)
XCTAssertTrue(activationGroupLeftA!.0.count == 1)
XCTAssertTrue(activationGroupLeftA!.0.first === leftAttributeA.layoutConstraint)
XCTAssertTrue(activationGroupLeftA!.1.count == 0)
// when
let activationGroupLeftB = node.add(attribute: leftAttributeA)
// then
XCTAssertNil(activationGroupLeftB)
}
func testThatActivationGroupIsTheExpectedWhenShouldInstallIsFalse() {
// given
let superview = UIView()
let view = UIView()
superview.addSubview(view)
let node = Node()
let leftAttributeA = Left(100).when { false }
leftAttributeA.createConstraints(for: view)
// when
let activationGroupLeftA = node.add(attribute: leftAttributeA)
// then
XCTAssertNil(activationGroupLeftA)
}
func testThatActivationGroupIsTheExpectedUponReloadWithNoChanges() {
// given
let superview = UIView()
let view = UIView()
superview.addSubview(view)
let node = Node()
let leftAttributeA = Left(100)
leftAttributeA.createConstraints(for: view)
let rightAttributeA = Right(100)
rightAttributeA.createConstraints(for: view)
let activationGroupLeftA = node.add(attribute: leftAttributeA)
XCTAssertTrue(activationGroupLeftA!.0.count == 1)
XCTAssertTrue(activationGroupLeftA!.0.first === leftAttributeA.layoutConstraint)
XCTAssertTrue(activationGroupLeftA!.1.count == 0)
let activationGroupRightA = node.add(attribute: rightAttributeA)
XCTAssertTrue(activationGroupRightA!.0.count == 1)
XCTAssertTrue(activationGroupRightA!.0.first === rightAttributeA.layoutConstraint)
XCTAssertTrue(activationGroupRightA!.1.count == 0)
// when
let activationGroupReload = node.reload()
// then
XCTAssertTrue(activationGroupReload.0.count == 0)
XCTAssertTrue(activationGroupReload.1.count == 0)
}
func testThatActivationGroupIsTheExpectedUponReloadWithChanges() {
// given
let superview = UIView()
let view = UIView()
superview.addSubview(view)
let node = Node()
var condition = true
let leftAttributeA = Left(100).when { condition }
leftAttributeA.createConstraints(for: view)
let leftAttributeB = Left(100).when { !condition }
leftAttributeB.createConstraints(for: view)
let rightAttributeA = Right(100)
rightAttributeA.createConstraints(for: view)
let activationGroupLeftA = node.add(attribute: leftAttributeA)
XCTAssertTrue(activationGroupLeftA!.0.count == 1)
XCTAssertTrue(activationGroupLeftA!.0.first === leftAttributeA.layoutConstraint)
XCTAssertTrue(activationGroupLeftA!.1.count == 0)
let activationGroupLeftB = node.add(attribute: leftAttributeB)
XCTAssertNil(activationGroupLeftB)
let activationGroupRightA = node.add(attribute: rightAttributeA)
XCTAssertTrue(activationGroupRightA!.0.count == 1)
XCTAssertTrue(activationGroupRightA!.0.first === rightAttributeA.layoutConstraint)
XCTAssertTrue(activationGroupRightA!.1.count == 0)
// when
condition = false
let activationGroupReload = node.reload()
// then
XCTAssertTrue(activationGroupReload.0.count == 1)
XCTAssertTrue(activationGroupReload.0.first === leftAttributeB.layoutConstraint)
XCTAssertTrue(activationGroupReload.1.count == 1)
XCTAssertTrue(activationGroupReload.1.first === leftAttributeA.layoutConstraint)
}
}
| mit |
Kinglioney/DouYuTV | DouYuTV/DouYuTV/Classes/Main/View/CollectionNormalCell.swift | 1 | 676 | //
// CollectionNormalCell.swift
// DouYuTV
//
// Created by apple on 2017/7/18.
// Copyright © 2017年 apple. All rights reserved.
//
import UIKit
class CollectionNormalCell: CollectionBaseCell {
//MARK:- 控件属性
@IBOutlet weak var roomNameLabel: UILabel!
//MARK:- 定义模型属性
override var anchor : AnchoModel?{
didSet{//监听属性发生变化
//1、将属性传递给父类
super.anchor = anchor
//2、房间名称显示
roomNameLabel.text = anchor?.room_name
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
| mit |
shaps80/Peek | Pod/Classes/GraphicsRenderer/PDFRenderer.swift | 1 | 8935 | /*
Copyright © 03/10/2016 Snippex Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import Foundation
/**
* Represents a PDF renderer format
*/
internal final class PDFRendererFormat: RendererFormat {
/**
Returns a default format, configured for this device
- returns: A new format
*/
internal static func `default`() -> PDFRendererFormat {
let bounds = CGRect(x: 0, y: 0, width: 612, height: 792)
return PDFRendererFormat(bounds: bounds, documentInfo: [:], flipped: false)
}
/// Returns the bounds for this format
internal let bounds: CGRect
/// Returns the associated document info
internal var documentInfo: [String: Any]
internal var isFlipped: Bool
/**
Creates a new format with the specified bounds and pageInfo
- parameter bounds: The bounds for each page in the PDF
- parameter documentInfo: The info associated with this PDF
- returns: A new PDF renderer format
*/
internal init(bounds: CGRect, documentInfo: [String: Any], flipped: Bool) {
self.bounds = bounds
self.documentInfo = documentInfo
self.isFlipped = flipped
}
/// Creates a new format with the specified document info and whether or not the context should be flipped
///
/// - Parameters:
/// - documentInfo: The associated PSD document info
/// - flipped: If true, the context drawing will be flipped
internal init(documentInfo: [String: Any], flipped: Bool) {
self.bounds = .zero
self.documentInfo = documentInfo
self.isFlipped = flipped
}
}
/// Represents a PDF renderer context
internal final class PDFRendererContext: RendererContext {
/// The underlying CGContext
internal let cgContext: CGContext
/// The format for this context
internal let format: PDFRendererFormat
/// The PDF context bounds
internal let pdfContextBounds: CGRect
// Internal variable for auto-closing pages
private var hasOpenPage: Bool = false
/// Creates a new context. If an existing page is open, this will also close it for you.
///
/// - Parameters:
/// - format: The format for this context
/// - cgContext: The underlying CGContext to associate with this context
/// - bounds: The bounds to use for this context
internal init(format: PDFRendererFormat, cgContext: CGContext, bounds: CGRect) {
self.format = format
self.cgContext = cgContext
self.pdfContextBounds = bounds
}
/// Creates a new PDF page. The bounds will be the same as specified by the document
internal func beginPage() {
beginPage(withBounds: format.bounds, pageInfo: [:])
}
/// Creates a new PDF page. If an existing page is open, this will also close it for you.
///
/// - Parameters:
/// - bounds: The bounds to use for this page
/// - pageInfo: The pageInfo associated to be associated with this page
internal func beginPage(withBounds bounds: CGRect, pageInfo: [String : Any]) {
var info = pageInfo
info[kCGPDFContextMediaBox as String] = bounds
let pageInfo = info as CFDictionary
endPageIfOpen()
cgContext.beginPDFPage(pageInfo)
hasOpenPage = true
if format.isFlipped {
let transform = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: format.bounds.height)
cgContext.concatenate(transform)
}
}
/// Set the URL associated with `rect' to `url' in the PDF context `context'.
///
/// - Parameters:
/// - url: The url to link to
/// - rect: The rect representing the link
internal func setURL(_ url: URL, for rect: CGRect) {
let url = url as CFURL
cgContext.setURL(url, for: rect)
}
/// Create a PDF destination named `name' at `point' in the current page of the PDF context `context'.
///
/// - Parameters:
/// - name: A destination name
/// - point: A location in the current page
internal func addDestination(withName name: String, at point: CGPoint) {
let name = name as CFString
cgContext.addDestination(name, at: point)
}
/// Specify a destination named `name' to jump to when clicking in `rect' of the current page of the PDF context `context'.
///
/// - Parameters:
/// - name: A destination name
/// - rect: A rect in the current page
internal func setDestinationWithName(_ name: String, for rect: CGRect) {
let name = name as CFString
cgContext.setDestination(name, for: rect)
}
// If a page is currently opened, this will close it. Otherwise it does nothing
fileprivate func endPageIfOpen() {
guard hasOpenPage else { return }
cgContext.endPDFPage()
}
}
extension PDFRenderer {
internal convenience init(bounds: CGRect) {
self.init(bounds: bounds, format: nil)
}
}
/// Represents a PDF renderer
internal final class PDFRenderer: Renderer {
/// The associated context type
internal typealias Context = PDFRendererContext
/// Returns the format for this renderer
internal let format: PDFRendererFormat
/// Creates a new PDF renderer with the specified bounds
///
/// - Parameters:
/// - bounds: The bounds of the PDF
/// - format: The format to use for this PDF
internal init(bounds: CGRect, format: PDFRendererFormat? = nil) {
guard bounds.size != .zero else { fatalError("size cannot be zero") }
let info = format?.documentInfo ?? [:]
self.format = PDFRendererFormat(bounds: bounds, documentInfo: info, flipped: format?.isFlipped ?? true)
}
/// Draws the PDF and writes is to the specified URL
///
/// - Parameters:
/// - url: The url to write tp
/// - actions: The drawing actions to perform
/// - Throws: May throw
internal func writePDF(to url: URL, withActions actions: (PDFRendererContext) -> Void) throws {
var rect = format.bounds
let consumer = CGDataConsumer(url: url as CFURL)!
let context = CGContext(consumer: consumer, mediaBox: &rect, format.documentInfo as CFDictionary?)!
try? runDrawingActions(forContext: context, drawingActions: actions, completionActions: nil)
}
/// Draws the PDF and returns the associated Data representation
///
/// - Parameter actions: The drawing actions to perform
/// - Returns: The PDF data
internal func pdfData(actions: (PDFRendererContext) -> Void) -> Data {
var rect = format.bounds
let data = NSMutableData()
let consumer = CGDataConsumer(data: data)!
let context = CGContext(consumer: consumer, mediaBox: &rect, format.documentInfo as CFDictionary?)!
try? runDrawingActions(forContext: context, drawingActions: actions, completionActions: nil)
return data as Data
}
private func runDrawingActions(forContext cgContext: CGContext, drawingActions: (Context) -> Void, completionActions: ((Context) -> Void)? = nil) throws {
let context = PDFRendererContext(format: format, cgContext: cgContext, bounds: format.bounds)
#if os(OSX)
let previousContext = NSGraphicsContext.current
NSGraphicsContext.current = NSGraphicsContext(cgContext: context.cgContext, flipped: format.isFlipped)
#else
UIGraphicsPushContext(context.cgContext)
#endif
drawingActions(context)
completionActions?(context)
context.endPageIfOpen()
context.cgContext.closePDF()
#if os(OSX)
NSGraphicsContext.current = previousContext
#else
UIGraphicsPopContext()
#endif
}
}
| mit |
yujinjcho/movie_recommendations | ios_ui/MovieRecTests/Common/MockNetworkManager.swift | 1 | 618 | //
// MockNetworkManager.swift
// MovieRecTests
//
// Created by Yujin Cho on 11/14/17.
// Copyright © 2017 Yujin Cho. All rights reserved.
//
import Foundation
@testable import MovieRec
class MockNetworkManager : NetworkManager {
var getRequestCalled : Bool = false
var postRequestCalled : Bool = false
override func getRequest(endPoint: String, completionHandler: @escaping (Data)->Void) {
getRequestCalled = true
}
override func postRequest(endPoint: String, postData: [String:Any], completionHandler: @escaping (Data)->Void) {
postRequestCalled = true
}
}
| mit |