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 |
---|---|---|---|---|---|
AlexeyGolovenkov/DocGenerator
|
GRMustache.swift/Tests/Public/ConfigurationTests/ConfigurationBaseContextTests.swift
|
1
|
6800
|
// The MIT License
//
// Copyright (c) 2015 Gwendal Roué
//
// 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 Mustache
class ConfigurationBaseContextTests: XCTestCase {
override func tearDown() {
super.tearDown()
DefaultConfiguration = Configuration()
}
func testDefaultConfigurationCustomBaseContext() {
DefaultConfiguration.baseContext = Context(Box(["foo": "success"]))
let template = try! Template(string: "{{foo}}")
let rendering = try! template.render()
XCTAssertEqual(rendering, "success")
}
func testTemplateBaseContextOverridesDefaultConfigurationBaseContext() {
DefaultConfiguration.baseContext = Context(Box(["foo": "failure"]))
let template = try! Template(string: "{{foo}}")
template.baseContext = Context(Box(["foo": "success"]))
let rendering = try! template.render()
XCTAssertEqual(rendering, "success")
}
func testDefaultRepositoryConfigurationHasDefaultConfigurationBaseContext() {
DefaultConfiguration.baseContext = Context(Box(["foo": "success"]))
let repository = TemplateRepository()
let template = try! repository.template(string: "{{foo}}")
let rendering = try! template.render()
XCTAssertEqual(rendering, "success")
}
func testRepositoryConfigurationBaseContextWhenSettingTheWholeConfiguration() {
var configuration = Configuration()
configuration.baseContext = Context(Box(["foo": "success"]))
let repository = TemplateRepository()
repository.configuration = configuration
let template = try! repository.template(string: "{{foo}}")
let rendering = try! template.render()
XCTAssertEqual(rendering, "success")
}
func testRepositoryConfigurationBaseContextWhenUpdatingRepositoryConfiguration() {
let repository = TemplateRepository()
repository.configuration.baseContext = Context(Box(["foo": "success"]))
let template = try! repository.template(string: "{{foo}}")
let rendering = try! template.render()
XCTAssertEqual(rendering, "success")
}
func testRepositoryConfigurationBaseContextOverridesDefaultConfigurationBaseContextWhenSettingTheWholeConfiguration() {
DefaultConfiguration.baseContext = Context(Box(["foo": "failure"]))
var configuration = Configuration()
configuration.baseContext = Context(Box(["foo": "success"]))
let repository = TemplateRepository()
repository.configuration = configuration
let template = try! repository.template(string: "{{foo}}")
let rendering = try! template.render()
XCTAssertEqual(rendering, "success")
}
func testRepositoryConfigurationBaseContextOverridesDefaultConfigurationBaseContextWhenUpdatingRepositoryConfiguration() {
DefaultConfiguration.baseContext = Context(Box(["foo": "failure"]))
let repository = TemplateRepository()
repository.configuration.baseContext = Context(Box(["foo": "success"]))
let template = try! repository.template(string: "{{foo}}")
let rendering = try! template.render()
XCTAssertEqual(rendering, "success")
}
func testTemplateBaseContextOverridesRepositoryConfigurationBaseContextWhenSettingTheWholeConfiguration() {
var configuration = Configuration()
configuration.baseContext = Context(Box(["foo": "failure"]))
let repository = TemplateRepository()
repository.configuration = configuration
let template = try! repository.template(string: "{{foo}}")
template.baseContext = Context(Box(["foo": "success"]))
let rendering = try! template.render()
XCTAssertEqual(rendering, "success")
}
func testTemplateBaseContextOverridesRepositoryConfigurationBaseContextWhenUpdatingRepositoryConfiguration() {
let repository = TemplateRepository()
repository.configuration.baseContext = Context(Box(["foo": "failure"]))
let template = try! repository.template(string: "{{foo}}")
template.baseContext = Context(Box(["foo": "success"]))
let rendering = try! template.render()
XCTAssertEqual(rendering, "success")
}
func testDefaultConfigurationMutationHasNoEffectAfterAnyTemplateHasBeenCompiled() {
let repository = TemplateRepository()
var rendering = try! repository.template(string: "{{^foo}}success{{/foo}}").render()
XCTAssertEqual(rendering, "success")
DefaultConfiguration.baseContext = Context(Box(["foo": "failure"]))
rendering = try! repository.template(string: "{{^foo}}success{{/foo}}").render()
XCTAssertEqual(rendering, "success")
}
func testRepositoryConfigurationMutationHasNoEffectAfterAnyTemplateHasBeenCompiled() {
let repository = TemplateRepository()
var rendering = try! repository.template(string: "{{^foo}}success{{/foo}}").render()
XCTAssertEqual(rendering, "success")
repository.configuration.baseContext = Context(Box(["foo": "failure"]))
rendering = try! repository.template(string: "{{^foo}}success{{/foo}}").render()
XCTAssertEqual(rendering, "success")
var configuration = Configuration()
configuration.baseContext = Context(Box(["foo": "failure"]))
repository.configuration = configuration
rendering = try! repository.template(string: "{{^foo}}success{{/foo}}").render()
XCTAssertEqual(rendering, "success")
}
}
|
mit
|
romainPellerin/SilverCalc
|
SilverCalc-iOS/RootViewController.swift
|
2
|
3914
|
import UIKit
@IBObject class RootViewController : UIViewController {
var buttons : [UIButton] = []
var calc : Calculator = Calculator()
var tf : UITextField!
@IBOutlet var tf_numb : UITextField!
var NUMBER_ACTION = 0
var OPERATOR_ACTION = 1
var DOT_ACTION = 2
var EQUAL_ACTION = 3
var lastAction = NUMBER_ACTION
public override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setupButtons()
}
func alert(s:String){
let alert = UIAlertView()
alert.title = "Calc alert"
alert.message = s
alert.addButtonWithTitle("Ok")
alert.show()
}
func setupButtons(){
// discover buttons from view in Main.storyboard
// instead of duplicate buttons declarations
for bt in self.view.subviews {
if bt is UIButton {
// set buttons style
bt.layer.cornerRadius = 5.0;
bt.layer.borderColor = UIColor(red: 191.0/255, green: 188.0/255, blue: 188.0/255, alpha: 1.0).CGColor
bt.layer.borderWidth = 0.5
// bind target methods to buttons
if bt.titleLabel.text == "x" {
bt.addTarget(self, action: "multiply:", forControlEvents: UIControlEvents.TouchUpInside)
}
else if bt.titleLabel.text == "/" {
bt.addTarget(self, action: "divide:", forControlEvents: UIControlEvents.TouchUpInside)
}
else if bt.titleLabel.text == "-" {
bt.addTarget(self, action: "minus:", forControlEvents: UIControlEvents.TouchUpInside)
}
else if bt.titleLabel.text == "+" {
bt.addTarget(self, action: "add:", forControlEvents: UIControlEvents.TouchUpInside)
}
else if bt.titleLabel.text == "C" {
bt.addTarget(self, action: "clear:", forControlEvents: UIControlEvents.TouchUpInside)
}
else if bt.titleLabel.text == "+/-" {
bt.addTarget(self, action: "invert:", forControlEvents: UIControlEvents.TouchUpInside)
}
else if bt.titleLabel.text == "=" {
bt.addTarget(self, action: "equal:", forControlEvents: UIControlEvents.TouchUpInside)
}
else if bt.titleLabel.text == "," {
bt.addTarget(self, action: "dot:", forControlEvents: UIControlEvents.TouchUpInside)
}
else {
bt.addTarget(self, action: "numberPressed:", forControlEvents: UIControlEvents.TouchUpInside)
}
}
else if bt is UITextField {
tf = bt
tf.text = "0.0"
tf.enabled = NO
tf.textAlignment = .Right
}
buttons.append(bt)
}
}
public override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning();
// Dispose of any resources that can be recreated.
}
func numberPressed(sender:UIButton!)
{
lastAction = NUMBER_ACTION
var nb:String = sender.titleLabel.text
var c : Int32 = nb[0]-48
// calc will compose number with new int part
calc.composeNumber(c)
tf.text = calc.getStringValue()
}
func multiply(sender:UIButton!)
{
lastAction = OPERATOR_ACTION
calc.multiply()
tf.text = calc.getStringValue()
}
func divide(sender:UIButton!)
{
lastAction = OPERATOR_ACTION
calc.divide()
tf.text = calc.getStringValue()
}
func minus(sender:UIButton!)
{
lastAction = OPERATOR_ACTION
calc.minus()
tf.text = calc.getStringValue()
}
func add(sender:UIButton!)
{
lastAction = OPERATOR_ACTION
calc.add()
tf.text = calc.getStringValue()
}
func equal(sender:UIButton!)
{
lastAction = EQUAL_ACTION
calc.process()
tf.text = calc.getStringValue()
}
func clear(sender:UIButton!)
{
lastAction = OPERATOR_ACTION
calc.clearNumber()
tf.text = calc.getStringValue()
}
func invert(sender:UIButton!)
{
lastAction = OPERATOR_ACTION
calc.invert()
tf.text = calc.getStringValue()
}
func dot(sender:UIButton!)
{
lastAction = OPERATOR_ACTION
calc.afterdot = true
}
}
|
apache-2.0
|
turekj/ReactiveTODO
|
ReactiveTODOTests/Classes/ViewModels/Factories/Impl/TODONoteListViewModelFactorySpec.swift
|
1
|
1166
|
@testable import ReactiveTODOFramework
import Nimble
import Quick
import RealmSwift
class TODONoteListViewModelFactorySpec: QuickSpec {
override func spec() {
describe("TODONoteListViewModelFactory") {
let dao = TODONoteDataAccessObjectMock()
let sut = TODONoteListViewModelFactory(todoNoteDAO: dao)
beforeEach {
let realm = try! Realm()
let firstTodo = TODONote()
firstTodo.guid = "1st"
let secondTodo = TODONote()
secondTodo.guid = "2nd"
try! realm.write {
realm.add(firstTodo)
realm.add(secondTodo)
}
}
context("When creating a view model") {
it("Should fetch all current notes from dao") {
dao.targetGuid = "1st"
let viewModel = sut.createViewModel()
let notes = viewModel.notes.collection
expect(notes.count).to(equal(1))
expect(notes[0].guid).to(equal("1st"))
}
}
}
}
}
|
mit
|
kukushi/SwipeTransition
|
Source/SwipeTransitionDelegate.swift
|
1
|
2330
|
//
// SwipeTransitionDelegate.swift
// SwipeTransitionExample
//
// Created by kukushi on 2/19/15.
// Copyright (c) 2015 kukushi. All rights reserved.
//
import UIKit
class SwipeTransitionDeleagte: NSObject, UINavigationControllerDelegate {
var transitionController = SwipeTransition()
var transitionAnimator = SwipeTransitionAnimator()
// used to pass the delegate
var delegate: UINavigationControllerDelegate?
func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
switch operation {
case .Push:
transitionController.intergate(navigationController)
return nil
default:
return transitionAnimator
}
}
func navigationController(navigationController: UINavigationController, interactionControllerForAnimationController animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return transitionController.interacting ? transitionController : nil
}
func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
delegate?.navigationController?(navigationController, willShowViewController: viewController, animated: animated)
}
func navigationController(navigationController: UINavigationController, didShowViewController viewController: UIViewController, animated: Bool) {
delegate?.navigationController?(navigationController, didShowViewController: viewController, animated: animated)
}
func navigationControllerSupportedInterfaceOrientations(navigationController: UINavigationController) -> Int {
return delegate?.navigationControllerSupportedInterfaceOrientations?(navigationController) ?? 0
}
func navigationControllerPreferredInterfaceOrientationForPresentation(navigationController: UINavigationController) -> UIInterfaceOrientation {
return delegate?.navigationControllerPreferredInterfaceOrientationForPresentation?(navigationController) ?? .Portrait
}
}
|
mit
|
iguchunhui/protobuf-swift
|
src/ProtocolBuffers/ProtocolBuffersTests/pbTests/ProtobufUnittest.UnittestEmbedOptimizeFor.proto.swift
|
3
|
15009
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// Source file unittest_embed_optimize_for.proto
import Foundation
import ProtocolBuffers
internal extension ProtobufUnittest{}
internal func == (lhs: ProtobufUnittest.TestEmbedOptimizedForSize, rhs: ProtobufUnittest.TestEmbedOptimizedForSize) -> Bool {
if (lhs === rhs) {
return true
}
var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue)
fieldCheck = fieldCheck && (lhs.hasOptionalMessage == rhs.hasOptionalMessage) && (!lhs.hasOptionalMessage || lhs.optionalMessage == rhs.optionalMessage)
fieldCheck = fieldCheck && (lhs.repeatedMessage == rhs.repeatedMessage)
fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields))
return fieldCheck
}
internal extension ProtobufUnittest {
internal struct UnittestEmbedOptimizeForRoot {
internal static var sharedInstance : UnittestEmbedOptimizeForRoot {
struct Static {
static let instance : UnittestEmbedOptimizeForRoot = UnittestEmbedOptimizeForRoot()
}
return Static.instance
}
internal var extensionRegistry:ExtensionRegistry
init() {
extensionRegistry = ExtensionRegistry()
registerAllExtensions(extensionRegistry)
ProtobufUnittest.UnittestOptimizeForRoot.sharedInstance.registerAllExtensions(extensionRegistry)
}
internal func registerAllExtensions(registry:ExtensionRegistry) {
}
}
final internal class TestEmbedOptimizedForSize : GeneratedMessage, GeneratedMessageProtocol {
private(set) var hasOptionalMessage:Bool = false
private(set) var optionalMessage:ProtobufUnittest.TestOptimizedForSize!
private(set) var repeatedMessage:Array<ProtobufUnittest.TestOptimizedForSize> = Array<ProtobufUnittest.TestOptimizedForSize>()
required internal init() {
super.init()
}
override internal func isInitialized() -> Bool {
if hasOptionalMessage {
if !optionalMessage.isInitialized() {
return false
}
}
var isInitrepeatedMessage:Bool = true
for oneElementrepeatedMessage in repeatedMessage {
if (!oneElementrepeatedMessage.isInitialized()) {
isInitrepeatedMessage = false
break
}
}
if !isInitrepeatedMessage {
return isInitrepeatedMessage
}
return true
}
override internal func writeToCodedOutputStream(output:CodedOutputStream) throws {
if hasOptionalMessage {
try output.writeMessage(1, value:optionalMessage)
}
for oneElementrepeatedMessage in repeatedMessage {
try output.writeMessage(2, value:oneElementrepeatedMessage)
}
try unknownFields.writeToCodedOutputStream(output)
}
override internal func serializedSize() -> Int32 {
var serialize_size:Int32 = memoizedSerializedSize
if serialize_size != -1 {
return serialize_size
}
serialize_size = 0
if hasOptionalMessage {
if let varSizeoptionalMessage = optionalMessage?.computeMessageSize(1) {
serialize_size += varSizeoptionalMessage
}
}
for oneElementrepeatedMessage in repeatedMessage {
serialize_size += oneElementrepeatedMessage.computeMessageSize(2)
}
serialize_size += unknownFields.serializedSize()
memoizedSerializedSize = serialize_size
return serialize_size
}
internal class func parseArrayDelimitedFromInputStream(input:NSInputStream) throws -> Array<ProtobufUnittest.TestEmbedOptimizedForSize> {
var mergedArray = Array<ProtobufUnittest.TestEmbedOptimizedForSize>()
while let value = try parseFromDelimitedFromInputStream(input) {
mergedArray += [value]
}
return mergedArray
}
internal class func parseFromDelimitedFromInputStream(input:NSInputStream) throws -> ProtobufUnittest.TestEmbedOptimizedForSize? {
return try ProtobufUnittest.TestEmbedOptimizedForSize.Builder().mergeDelimitedFromInputStream(input)?.build()
}
internal class func parseFromData(data:NSData) throws -> ProtobufUnittest.TestEmbedOptimizedForSize {
return try ProtobufUnittest.TestEmbedOptimizedForSize.Builder().mergeFromData(data, extensionRegistry:ProtobufUnittest.UnittestEmbedOptimizeForRoot.sharedInstance.extensionRegistry).build()
}
internal class func parseFromData(data:NSData, extensionRegistry:ExtensionRegistry) throws -> ProtobufUnittest.TestEmbedOptimizedForSize {
return try ProtobufUnittest.TestEmbedOptimizedForSize.Builder().mergeFromData(data, extensionRegistry:extensionRegistry).build()
}
internal class func parseFromInputStream(input:NSInputStream) throws -> ProtobufUnittest.TestEmbedOptimizedForSize {
return try ProtobufUnittest.TestEmbedOptimizedForSize.Builder().mergeFromInputStream(input).build()
}
internal class func parseFromInputStream(input:NSInputStream, extensionRegistry:ExtensionRegistry) throws -> ProtobufUnittest.TestEmbedOptimizedForSize {
return try ProtobufUnittest.TestEmbedOptimizedForSize.Builder().mergeFromInputStream(input, extensionRegistry:extensionRegistry).build()
}
internal class func parseFromCodedInputStream(input:CodedInputStream) throws -> ProtobufUnittest.TestEmbedOptimizedForSize {
return try ProtobufUnittest.TestEmbedOptimizedForSize.Builder().mergeFromCodedInputStream(input).build()
}
internal class func parseFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> ProtobufUnittest.TestEmbedOptimizedForSize {
return try ProtobufUnittest.TestEmbedOptimizedForSize.Builder().mergeFromCodedInputStream(input, extensionRegistry:extensionRegistry).build()
}
internal class func getBuilder() -> ProtobufUnittest.TestEmbedOptimizedForSize.Builder {
return ProtobufUnittest.TestEmbedOptimizedForSize.classBuilder() as! ProtobufUnittest.TestEmbedOptimizedForSize.Builder
}
internal func getBuilder() -> ProtobufUnittest.TestEmbedOptimizedForSize.Builder {
return classBuilder() as! ProtobufUnittest.TestEmbedOptimizedForSize.Builder
}
internal override class func classBuilder() -> MessageBuilder {
return ProtobufUnittest.TestEmbedOptimizedForSize.Builder()
}
internal override func classBuilder() -> MessageBuilder {
return ProtobufUnittest.TestEmbedOptimizedForSize.Builder()
}
internal func toBuilder() throws -> ProtobufUnittest.TestEmbedOptimizedForSize.Builder {
return try ProtobufUnittest.TestEmbedOptimizedForSize.builderWithPrototype(self)
}
internal class func builderWithPrototype(prototype:ProtobufUnittest.TestEmbedOptimizedForSize) throws -> ProtobufUnittest.TestEmbedOptimizedForSize.Builder {
return try ProtobufUnittest.TestEmbedOptimizedForSize.Builder().mergeFrom(prototype)
}
override internal func writeDescriptionTo(inout output:String, indent:String) throws {
if hasOptionalMessage {
output += "\(indent) optionalMessage {\n"
try optionalMessage?.writeDescriptionTo(&output, indent:"\(indent) ")
output += "\(indent) }\n"
}
var repeatedMessageElementIndex:Int = 0
for oneElementrepeatedMessage in repeatedMessage {
output += "\(indent) repeatedMessage[\(repeatedMessageElementIndex)] {\n"
try oneElementrepeatedMessage.writeDescriptionTo(&output, indent:"\(indent) ")
output += "\(indent)}\n"
repeatedMessageElementIndex++
}
unknownFields.writeDescriptionTo(&output, indent:indent)
}
override internal var hashValue:Int {
get {
var hashCode:Int = 7
if hasOptionalMessage {
if let hashValueoptionalMessage = optionalMessage?.hashValue {
hashCode = (hashCode &* 31) &+ hashValueoptionalMessage
}
}
for oneElementrepeatedMessage in repeatedMessage {
hashCode = (hashCode &* 31) &+ oneElementrepeatedMessage.hashValue
}
hashCode = (hashCode &* 31) &+ unknownFields.hashValue
return hashCode
}
}
//Meta information declaration start
override internal class func className() -> String {
return "ProtobufUnittest.TestEmbedOptimizedForSize"
}
override internal func className() -> String {
return "ProtobufUnittest.TestEmbedOptimizedForSize"
}
override internal func classMetaType() -> GeneratedMessage.Type {
return ProtobufUnittest.TestEmbedOptimizedForSize.self
}
//Meta information declaration end
final internal class Builder : GeneratedMessageBuilder {
private var builderResult:ProtobufUnittest.TestEmbedOptimizedForSize = ProtobufUnittest.TestEmbedOptimizedForSize()
internal func getMessage() -> ProtobufUnittest.TestEmbedOptimizedForSize {
return builderResult
}
required override internal init () {
super.init()
}
var hasOptionalMessage:Bool {
get {
return builderResult.hasOptionalMessage
}
}
var optionalMessage:ProtobufUnittest.TestOptimizedForSize! {
get {
if optionalMessageBuilder_ != nil {
builderResult.optionalMessage = optionalMessageBuilder_.getMessage()
}
return builderResult.optionalMessage
}
set (value) {
builderResult.hasOptionalMessage = true
builderResult.optionalMessage = value
}
}
private var optionalMessageBuilder_:ProtobufUnittest.TestOptimizedForSize.Builder! {
didSet {
builderResult.hasOptionalMessage = true
}
}
internal func getOptionalMessageBuilder() -> ProtobufUnittest.TestOptimizedForSize.Builder {
if optionalMessageBuilder_ == nil {
optionalMessageBuilder_ = ProtobufUnittest.TestOptimizedForSize.Builder()
builderResult.optionalMessage = optionalMessageBuilder_.getMessage()
if optionalMessage != nil {
try! optionalMessageBuilder_.mergeFrom(optionalMessage)
}
}
return optionalMessageBuilder_
}
func setOptionalMessage(value:ProtobufUnittest.TestOptimizedForSize!) -> ProtobufUnittest.TestEmbedOptimizedForSize.Builder {
self.optionalMessage = value
return self
}
internal func mergeOptionalMessage(value:ProtobufUnittest.TestOptimizedForSize) throws -> ProtobufUnittest.TestEmbedOptimizedForSize.Builder {
if builderResult.hasOptionalMessage {
builderResult.optionalMessage = try ProtobufUnittest.TestOptimizedForSize.builderWithPrototype(builderResult.optionalMessage).mergeFrom(value).buildPartial()
} else {
builderResult.optionalMessage = value
}
builderResult.hasOptionalMessage = true
return self
}
internal func clearOptionalMessage() -> ProtobufUnittest.TestEmbedOptimizedForSize.Builder {
optionalMessageBuilder_ = nil
builderResult.hasOptionalMessage = false
builderResult.optionalMessage = nil
return self
}
var repeatedMessage:Array<ProtobufUnittest.TestOptimizedForSize> {
get {
return builderResult.repeatedMessage
}
set (value) {
builderResult.repeatedMessage = value
}
}
func setRepeatedMessage(value:Array<ProtobufUnittest.TestOptimizedForSize>) -> ProtobufUnittest.TestEmbedOptimizedForSize.Builder {
self.repeatedMessage = value
return self
}
internal func clearRepeatedMessage() -> ProtobufUnittest.TestEmbedOptimizedForSize.Builder {
builderResult.repeatedMessage.removeAll(keepCapacity: false)
return self
}
override internal var internalGetResult:GeneratedMessage {
get {
return builderResult
}
}
internal override func clear() -> ProtobufUnittest.TestEmbedOptimizedForSize.Builder {
builderResult = ProtobufUnittest.TestEmbedOptimizedForSize()
return self
}
internal override func clone() throws -> ProtobufUnittest.TestEmbedOptimizedForSize.Builder {
return try ProtobufUnittest.TestEmbedOptimizedForSize.builderWithPrototype(builderResult)
}
internal override func build() throws -> ProtobufUnittest.TestEmbedOptimizedForSize {
try checkInitialized()
return buildPartial()
}
internal func buildPartial() -> ProtobufUnittest.TestEmbedOptimizedForSize {
let returnMe:ProtobufUnittest.TestEmbedOptimizedForSize = builderResult
return returnMe
}
internal func mergeFrom(other:ProtobufUnittest.TestEmbedOptimizedForSize) throws -> ProtobufUnittest.TestEmbedOptimizedForSize.Builder {
if other == ProtobufUnittest.TestEmbedOptimizedForSize() {
return self
}
if (other.hasOptionalMessage) {
try mergeOptionalMessage(other.optionalMessage)
}
if !other.repeatedMessage.isEmpty {
builderResult.repeatedMessage += other.repeatedMessage
}
try mergeUnknownFields(other.unknownFields)
return self
}
internal override func mergeFromCodedInputStream(input:CodedInputStream) throws -> ProtobufUnittest.TestEmbedOptimizedForSize.Builder {
return try mergeFromCodedInputStream(input, extensionRegistry:ExtensionRegistry())
}
internal override func mergeFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> ProtobufUnittest.TestEmbedOptimizedForSize.Builder {
let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(self.unknownFields)
while (true) {
let tag = try input.readTag()
switch tag {
case 0:
self.unknownFields = try unknownFieldsBuilder.build()
return self
case 10 :
let subBuilder:ProtobufUnittest.TestOptimizedForSize.Builder = ProtobufUnittest.TestOptimizedForSize.Builder()
if hasOptionalMessage {
try subBuilder.mergeFrom(optionalMessage)
}
try input.readMessage(subBuilder, extensionRegistry:extensionRegistry)
optionalMessage = subBuilder.buildPartial()
case 18 :
let subBuilder = ProtobufUnittest.TestOptimizedForSize.Builder()
try input.readMessage(subBuilder,extensionRegistry:extensionRegistry)
repeatedMessage += [subBuilder.buildPartial()]
default:
if (!(try parseUnknownField(input,unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:tag))) {
unknownFields = try unknownFieldsBuilder.build()
return self
}
}
}
}
}
}
}
// @@protoc_insertion_point(global_scope)
|
apache-2.0
|
frootloops/swift
|
test/NameBinding/Dependencies/private-typealias.swift
|
2
|
838
|
// RUN: %target-swift-frontend -emit-silgen -primary-file %s %S/Inputs/InterestingType.swift -DOLD -emit-reference-dependencies-path %t.swiftdeps -module-name main | %FileCheck %s -check-prefix=CHECK-OLD
// RUN: %FileCheck -check-prefix=CHECK-DEPS %s < %t.swiftdeps
// RUN: %target-swift-frontend -emit-silgen -primary-file %s %S/Inputs/InterestingType.swift -DNEW -emit-reference-dependencies-path %t.swiftdeps -module-name main | %FileCheck %s -check-prefix=CHECK-NEW
// RUN: %FileCheck -check-prefix=CHECK-DEPS %s < %t.swiftdeps
private struct Wrapper {
static func test() -> InterestingType { fatalError() }
}
// CHECK-OLD: sil_global @_T04main1x{{[^ ]+}} : $Int
// CHECK-NEW: sil_global @_T04main1x{{[^ ]+}} : $Double
public var x = Wrapper.test() + 0
// CHECK-DEPS-LABEL: depends-top-level:
// CHECK-DEPS: - "InterestingType"
|
apache-2.0
|
adrfer/swift
|
validation-test/compiler_crashers_fixed/26355-llvm-smallvectorimpl-swift-diagnosticargument-operator.swift
|
4
|
277
|
// 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 A}struct S<T where T:A{
struct B{var _=a<r
class a<T>:A
|
apache-2.0
|
Mindera/Alicerce
|
Sources/Network/Pinning/Data+SPKIHash.swift
|
1
|
1084
|
import Foundation
import CommonCrypto
// How to retrieve SPKI SHA256 Base64 encoded hashes:
//
// - OpenSSL:
// run ```
// openssl x509 -inform der -in <cert_name> -pubkey -noout |
// openssl pkey -pubin -outform der |
// openssl dgst -sha256 -binary |
// openssl enc -base64`
// ```
//
// - ssllabs.com
// enter the server's URL -> analyse -> go to Certification Paths -> look for "Pin SHA256" entries
extension Data {
typealias CertificateSPKIBase64EncodedSHA256Hash = ServerTrustEvaluator.CertificateSPKIBase64EncodedSHA256Hash
func spkiHash(for algorithm: PublicKeyAlgorithm) -> CertificateSPKIBase64EncodedSHA256Hash {
// add missing ASN1 header for public keys to re-create the subject public key info (SPKI)
let spkiData = algorithm.asn1HeaderData + self
var spkiHash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
spkiData.withUnsafeBytes {
_ = CC_SHA256($0.baseAddress, CC_LONG(spkiData.count), &spkiHash)
}
return Data(spkiHash).base64EncodedString()
}
}
|
mit
|
ta2yak/MaterialKit
|
Source/MKImageView.swift
|
1
|
3470
|
//
// MKImageView.swift
// MaterialKit
//
// Created by Le Van Nghia on 11/29/14.
// Copyright (c) 2014 Le Van Nghia. All rights reserved.
//
import UIKit
@IBDesignable
public class MKImageView: UIImageView
{
@IBInspectable public var maskEnabled: Bool = true {
didSet {
mkLayer.enableMask(enable: maskEnabled)
}
}
@IBInspectable public var rippleLocation: MKRippleLocation = .TapLocation {
didSet {
mkLayer.rippleLocation = rippleLocation
}
}
@IBInspectable public var rippleAniDuration: Float = 0.75
@IBInspectable public var backgroundAniDuration: Float = 1.0
@IBInspectable public var rippleAniTimingFunction: MKTimingFunction = .Linear
@IBInspectable public var backgroundAniTimingFunction: MKTimingFunction = .Linear
@IBInspectable public var backgroundAniEnabled: Bool = true {
didSet {
if !backgroundAniEnabled {
mkLayer.enableOnlyCircleLayer()
}
}
}
@IBInspectable public var ripplePercent: Float = 0.9 {
didSet {
mkLayer.ripplePercent = ripplePercent
}
}
@IBInspectable public var cornerRadius: CGFloat = 2.5 {
didSet {
layer.cornerRadius = cornerRadius
mkLayer.setMaskLayerCornerRadius(cornerRadius)
}
}
// color
@IBInspectable public var rippleLayerColor: UIColor = UIColor(white: 0.45, alpha: 0.5) {
didSet {
mkLayer.setCircleLayerColor(rippleLayerColor)
}
}
@IBInspectable public var backgroundLayerColor: UIColor = UIColor(white: 0.75, alpha: 0.25) {
didSet {
mkLayer.setBackgroundLayerColor(backgroundLayerColor)
}
}
override public var bounds: CGRect {
didSet {
mkLayer.superLayerDidResize()
}
}
private lazy var mkLayer: MKLayer = MKLayer(superLayer: self.layer)
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override public init(frame: CGRect) {
super.init(frame: frame)
setup()
}
override public init(image: UIImage!) {
super.init(image: image)
setup()
}
override public init(image: UIImage!, highlightedImage: UIImage?) {
super.init(image: image, highlightedImage: highlightedImage)
setup()
}
private func setup() {
mkLayer.setCircleLayerColor(rippleLayerColor)
mkLayer.setBackgroundLayerColor(backgroundLayerColor)
mkLayer.setMaskLayerCornerRadius(cornerRadius)
}
public func animateRipple(location: CGPoint? = nil) {
if let point = location {
mkLayer.didChangeTapLocation(point)
} else if rippleLocation == .TapLocation {
rippleLocation = .Center
}
mkLayer.animateScaleForCircleLayer(0.65, toScale: 1.0, timingFunction: rippleAniTimingFunction, duration: CFTimeInterval(self.rippleAniDuration))
mkLayer.animateAlphaForBackgroundLayer(backgroundAniTimingFunction, duration: CFTimeInterval(self.backgroundAniDuration))
}
override public func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
super.touchesBegan(touches, withEvent: event)
if let firstTouch = touches.anyObject() as? UITouch {
let location = firstTouch.locationInView(self)
animateRipple(location: location)
}
}
}
|
mit
|
insidegui/WWDC
|
Packages/Transcripts/TranscriptsTests/Sources/Bundle+LoadJSON.swift
|
1
|
545
|
//
// Bundle+LoadJSON.swift
// TranscriptsTests
//
// Created by Guilherme Rambo on 25/05/20.
// Copyright © 2020 Guilherme Rambo. All rights reserved.
//
import Foundation
extension Bundle {
func loadJSON<T: Decodable>(from resource: String) throws -> T {
guard let url = self.url(forResource: resource, withExtension: "json") else {
fatalError("Missing \(resource) from testing bundle")
}
let data = try Data(contentsOf: url)
return try JSONDecoder().decode(T.self, from: data)
}
}
|
bsd-2-clause
|
victorlin/ReactiveCocoa
|
ReactiveCocoa/Swift/Atomic.swift
|
1
|
4249
|
//
// Atomic.swift
// ReactiveCocoa
//
// Created by Justin Spahr-Summers on 2014-06-10.
// Copyright (c) 2014 GitHub. All rights reserved.
//
import Foundation
final class PosixThreadMutex: NSLocking {
private var mutex = pthread_mutex_t()
init() {
let result = pthread_mutex_init(&mutex, nil)
precondition(result == 0, "Failed to initialize mutex with error \(result).")
}
deinit {
let result = pthread_mutex_destroy(&mutex)
precondition(result == 0, "Failed to destroy mutex with error \(result).")
}
func lock() {
let result = pthread_mutex_lock(&mutex)
precondition(result == 0, "Failed to lock \(self) with error \(result).")
}
func unlock() {
let result = pthread_mutex_unlock(&mutex)
precondition(result == 0, "Failed to unlock \(self) with error \(result).")
}
}
/// An atomic variable.
public final class Atomic<Value>: AtomicProtocol {
private let lock: PosixThreadMutex
private var _value: Value
/// Initialize the variable with the given initial value.
///
/// - parameters:
/// - value: Initial value for `self`.
public init(_ value: Value) {
_value = value
lock = PosixThreadMutex()
}
/// Atomically modifies the variable.
///
/// - parameters:
/// - action: A closure that takes the current value.
///
/// - returns: The result of the action.
@discardableResult
public func modify<Result>(_ action: (inout Value) throws -> Result) rethrows -> Result {
lock.lock()
defer { lock.unlock() }
return try action(&_value)
}
/// Atomically perform an arbitrary action using the current value of the
/// variable.
///
/// - parameters:
/// - action: A closure that takes the current value.
///
/// - returns: The result of the action.
@discardableResult
public func withValue<Result>(_ action: (Value) throws -> Result) rethrows -> Result {
lock.lock()
defer { lock.unlock() }
return try action(_value)
}
}
/// An atomic variable which uses a recursive lock.
internal final class RecursiveAtomic<Value>: AtomicProtocol {
private let lock: NSRecursiveLock
private var _value: Value
private let didSetObserver: ((Value) -> Void)?
/// Initialize the variable with the given initial value.
///
/// - parameters:
/// - value: Initial value for `self`.
/// - name: An optional name used to create the recursive lock.
/// - action: An optional closure which would be invoked every time the
/// value of `self` is mutated.
internal init(_ value: Value, name: StaticString? = nil, didSet action: ((Value) -> Void)? = nil) {
_value = value
lock = NSRecursiveLock()
lock.name = name.map(String.init(describing:))
didSetObserver = action
}
/// Atomically modifies the variable.
///
/// - parameters:
/// - action: A closure that takes the current value.
///
/// - returns: The result of the action.
@discardableResult
func modify<Result>(_ action: (inout Value) throws -> Result) rethrows -> Result {
lock.lock()
defer {
didSetObserver?(_value)
lock.unlock()
}
return try action(&_value)
}
/// Atomically perform an arbitrary action using the current value of the
/// variable.
///
/// - parameters:
/// - action: A closure that takes the current value.
///
/// - returns: The result of the action.
@discardableResult
func withValue<Result>(_ action: (Value) throws -> Result) rethrows -> Result {
lock.lock()
defer { lock.unlock() }
return try action(_value)
}
}
public protocol AtomicProtocol: class {
associatedtype Value
@discardableResult
func withValue<Result>(_ action: (Value) throws -> Result) rethrows -> Result
@discardableResult
func modify<Result>(_ action: (inout Value) throws -> Result) rethrows -> Result
}
extension AtomicProtocol {
/// Atomically get or set the value of the variable.
public var value: Value {
get {
return withValue { $0 }
}
set(newValue) {
swap(newValue)
}
}
/// Atomically replace the contents of the variable.
///
/// - parameters:
/// - newValue: A new value for the variable.
///
/// - returns: The old value.
@discardableResult
public func swap(_ newValue: Value) -> Value {
return modify { (value: inout Value) in
let oldValue = value
value = newValue
return oldValue
}
}
}
|
mit
|
Kijjakarn/Crease-Pattern-Analyzer
|
CreasePatternAnalyzer/Utilities/Axioms.swift
|
1
|
7914
|
//
// Axioms.swift
// CreasePatternAnalyzer
//
// Created by Kijjakarn Praditukrit on 11/22/16.
// Copyright © 2016-2017 Kijjakarn Praditukrit. All rights reserved.
//
import Darwin
/*----------------------------------------------------------------------------
Huzita-Justin Axioms Implementations
- All points and lines passed to these functions must be distinct
-----------------------------------------------------------------------------*/
// Axiom 1: Given two points p1 and p2, we can fold a line connecting them
func axiom1(_ p1: PointVector, _ p2: PointVector) -> Line? {
let fold = Line(p1, p2)
return main.paper.contains(line: fold) ? fold : nil
}
// Axiom 2: Given two points p1 and p2, we can fold p1 onto p2
func axiom2(_ p1: PointVector, _ p2: PointVector) -> Line? {
let unitNormal = ((p1 - p2)/2).normalized()
let midPoint = (p1 + p2)/2
let fold = Line(point: midPoint, unitNormal: unitNormal)
return main.paper.contains(line: fold) ? fold : nil
}
// Axiom 3: Given two lines line1 and line2, we can fold line1 onto line2
// - If lines are parallel, return one solution
// - Otherwise, return line(s) contained in main.paper
func axiom3(_ line1: Line, _ line2: Line) -> [Line] {
guard let p = intersection(line1, line2) else {
return [Line(distance: (line1.distance + line2.distance)/2,
unitNormal: line1.unitNormal)]
}
let direction = (line1.unitNormal + line2.unitNormal).normalized()
let fold1 = Line(point: p, unitNormal: direction)
let fold2 = Line(point: p, unitNormal: direction.rotatedBy90())
var folds = [Line]()
if main.paper.contains(line: fold1) { folds.append(fold1) }
if main.paper.contains(line: fold2) { folds.append(fold2) }
return folds
}
// Axiom 4: Given a point p and a line, we can make a fold perpendicular to the
// line passing through the point p
func axiom4(point: PointVector, line: Line) -> Line? {
if main.paper.encloses(point: line.projection(ofPoint: point)) {
let fold = Line(point: point, unitNormal: line.unitNormal.rotatedBy90())
return main.paper.contains(line: fold) ? fold : nil
}
return nil
}
// Axiom 5: Given two points p1 and p2 and a line, we can make a fold that
// places p1 onto the line and passes through p2
// - This is the same as finding lines that go through p2 and the intersection
// between the circle centered at p2 with radius |p2 - p1|
func axiom5(bring p1: PointVector, to line: Line, through p2: PointVector)
-> [Line] {
let radius = (p1 - p2).magnitude
let centerToLine = line.unitNormal*(line.distance - line.unitNormal.dot(p2))
// If the line does not intersect the circle
if radius < centerToLine.magnitude {
return []
}
let addVector = line.unitNormal.rotatedBy90()
* sqrt(radius*radius - centerToLine.magnitudeSquared())
let point1 = centerToLine + p2 + addVector
let point2 = centerToLine + p2 - addVector
var folds = [Line]()
if main.paper.encloses(point: point1) {
let p11 = (p1 + point1)/2
if p2 != p11 {
folds.append(Line(p2, p11))
}
}
if main.paper.encloses(point: point2) {
let p12 = (p1 + point2)/2
if p2 != p12 {
folds.append(Line(p2, p12))
}
}
return folds
}
// Axiom 6: Given two points p1 and p2 and two lines line1 and line2, we can
// make a fold that places p1 onto line1 and places p2 onto line2
// - First transform the coordinate system by aligning line1 with the x-axis by
// - shifting and rotating, then put p1 on the y-axis by shifting
func axiom6(bring p1: PointVector, to line1: Line,
and p2: PointVector, on line2: Line) -> [Line] {
let u1 = line1.unitNormal
let u2 = line2.unitNormal
let u1P = u1.rotatedBy90()*(-1)
let v1 = p1 - u1*line1.distance
let v2 = p2 - u1*line1.distance
let x1 = v1.dot(u1P)
let x2 = v2.dot(u1P) - x1
let y1 = v1.dot(u1)
let y2 = v2.dot(u1)
let u2x = u2.dot(u1P)
let u2y = u2.dot(u1)
let d2 = line2.distance - u2.dot(u1*line1.distance) - u2x*x1
let yy = 2*y2 - y1
let z = d2 - u2x*x2 - u2y*y2
// Coefficients of the cubic equation
let a = u2x
let b = -(2*u2x*x2 + u2y*y1 + z)
let c = y1*(2*u2y*x2 + u2x*yy)
let d = -y1*y1*(u2y*yy + z)
// Solve the equation and get the folded line
let roots = solveCubic(a, b, c, d)
var folds = [Line]()
for root in roots {
let p1Folded = u1*line1.distance + u1P*(root + x1)
// If fold goes through p1 or main.paper doesn't enclose reflected point
if p1 == p1Folded || !main.paper.encloses(point: p1Folded) {
continue
}
let fold = Line(point: (p1 + p1Folded)/2, normal: (p1 - p1Folded))
// If main.paper doesn't contain the fold or p1 and p2 aren't on the
// same side of main.paper
if !main.paper.contains(line: fold)
|| (line1.distance - p1.dot(u1))*(line1.distance - p1.dot(u2)) < 0 {
continue
}
let p2Folded = fold.reflection(ofPoint: p2)
// If fold doesn't enclose the reflected p2
if !main.paper.encloses(point: p2Folded) {
continue
}
folds.append(fold)
}
return folds
}
// Solve cubic equation of the form ax^3 + bx^2 + cx + d = 0
// - Use Cardano's formula
// - Return real solutions only
// - See https://proofwiki.org/wiki/Cardano%27s_Formula/Real_Coefficients
func solveCubic(_ a: Double , _ b: Double, _ c: Double, _ d: Double) -> [Double]
{
// The equation is not cubic
if abs(a) < main.ε {
if abs(b) < main.ε {
// The equation is wrong or trivial
if abs(c) < main.ε {
return []
}
// The equation is linear
return [-d/c]
}
// The equation is quadratic
let discriminant = c*c - 4*b*d
if discriminant < 0 { return [] }
if discriminant < main.ε { return [-c/(2*b)] }
let sqrtOfDiscriminant = sqrt(discriminant)
let x1 = (-c + sqrtOfDiscriminant)/(2*b)
let x2 = (-c - sqrtOfDiscriminant)/(2*b)
return [x1, x2]
}
// The equation is cubic
let q = (3*a*c - b*b)/(9*a*a)
let r = (9*a*b*c - 27*a*a*d - 2*b^^3)/(54*a^^3)
let discriminant = q^^3 + r^^2
// All roots are real and distinct
if discriminant < 0 {
let θ = acos(r/sqrt(-q^^3))/3
let e = 2*sqrt(-q)
let f = b/(3*a)
let x1 = e*cos(θ) - f
let x2 = e*cos(θ + 2*π/3) - f
let x3 = e*cos(θ + 4*π/3) - f
return [x1, x2, x3]
}
// All roots are real and at least two are equal
if discriminant < main.ε {
// There is only one real root
if r == 0 { return [-b/(3*a)] }
let e = cbrt(r)
let f = b/(3*a)
let x1 = 2*e - f
let x2 = -e - f
return [x1, x2]
}
// There is one real root and the other two are complex conjugates
let sqrtOfDiscriminant = sqrt(discriminant)
let x1 = cbrt(r + sqrtOfDiscriminant)
+ cbrt(r - sqrtOfDiscriminant) - b/(3*a)
return [x1]
}
// Axiom 7: Given a point p and two lines line1 and line2, we can make a fold
// perpendicular to line2 that places p onto line1
func axiom7(bring p: PointVector, to line1: Line, along line2: Line) -> Line? {
let u1 = line1.unitNormal
let u2 = line2.unitNormal
let u2P = u2.rotatedBy90()
let foldDistance = (line1.distance - p.dot(u1))
/ (2*u2P.dot(u1)) + p.dot(u2P)
let fold = Line(distance: foldDistance, unitNormal: u2P)
if (main.paper.encloses(point: fold.reflection(ofPoint: p))
&& main.paper.contains(line: fold)) {
return fold
}
return nil
}
|
gpl-3.0
|
bingoogolapple/SwiftNote-PartOne
|
swift2048/swift2048/MainViewController.swift
|
2
|
2451
|
//
// MainViewController.swift
// swift2048
//
// Created by bingoogol on 14-6-18.
// Copyright (c) 2014年 bingoogol. All rights reserved.
//
import UIKit
class MainViewController:UIViewController {
// 游戏方格维度
var dimension:Int = 4
// 游戏过关最大值
var maxNumber:Int = 2048
//数字格子的宽度
var width:CGFloat = 50
//格子与格子的间距
var padding:CGFloat = 6
var backgrounds:Array<UIView>
init() {
self.backgrounds = Array<UIView>()
super.init(nibName:nil,bundle:nil)
}
override func viewDidLoad() {
super.viewDidLoad()
setupBackground()
getNumber()
}
func setupBackground() {
var x:CGFloat = 30
var y:CGFloat = 150
for col in 0 .. dimension {
y = 150
for row in 0 .. dimension {
var background = UIView(frame:CGRectMake(x,y,width,width))
background.backgroundColor = UIColor.darkGrayColor()
self.view.addSubview(background)
backgrounds += background
y += padding + width
}
x += padding + width
}
}
func getNumber() {
let randv = Int(arc4random_uniform(10))
println(randv)
var seed:Int = 2
if(randv == 1) {
seed = 4
}
let col = Int(arc4random_uniform(UInt32(dimension)))
let row = Int(arc4random_uniform(UInt32(dimension)))
insertTitle((row,col),value:seed);
}
func insertTitle(pos:(Int,Int),value:Int) {
let (row,col) = pos
let x = 30 + CGFloat(col) * (width + padding)
let y = 150 + CGFloat(row) * (width + padding)
let tile = TileView(pos:CGPointMake(x,y),width:width,value:value)
self.view.addSubview(tile)
self.view.bringSubviewToFront(tile)
UIView.animateWithDuration(0.3,delay:0.1,options:
UIViewAnimationOptions.TransitionNone,animations:{
()->Void in
tile.layer.setAffineTransform(CGAffineTransformMakeScale(1,1))
},completion: {
(finished:Bool)->Void in
UIView.animateWithDuration(0.08,animations:{
()->Void in
tile.layer.setAffineTransform(CGAffineTransformIdentity)
})
})
}
}
|
apache-2.0
|
ahoppen/swift
|
test/Concurrency/Runtime/async_let_throw_completion_order.swift
|
7
|
840
|
// rdar://81481317
// RUN: %target-run-simple-swift(-Xfrontend -disable-availability-checking -parse-as-library) | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: concurrency
// rdar://82123254
// REQUIRES: concurrency_runtime
// UNSUPPORTED: back_deployment_runtime
struct Bad: Error {}
class Foo { init() async throws {}; deinit { print("Foo down") } }
class Bar { init() async throws { throw Bad() }; deinit { print("Bar down") } }
class Baz { init() async throws {}; deinit { print("Baz down") } }
func zim(y: Bar, x: Foo, z: Baz) { print("hooray") }
@main struct Butt {
static func main() async {
do {
async let x = Foo()
async let y = Bar()
async let z = Baz()
return try await zim(y: y, x: x, z: z)
} catch {
// CHECK: oopsie whoopsie
print("oopsie whoopsie")
}
}
}
|
apache-2.0
|
StanZabroda/Hydra
|
Hydra/HRFooterProgress.swift
|
1
|
1650
|
//
// HRFooterProgress.swift
// Hydra
//
// Created by Evgeny Evgrafov on 9/22/15.
// Copyright © 2015 Evgeny Evgrafov. All rights reserved.
//
import UIKit
class HRFooterProgress: UIView {
var progressActivity : UIActivityIndicatorView!
var infoTitle : UILabel!
override init(frame: CGRect) {
let customFrame = CGRectMake(0, 0, screenSizeWidth, 80)
super.init(frame: customFrame)
self.progressActivity = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
self.progressActivity.frame = CGRectMake(screenSizeWidth/2-5, 60, 10, 10)
self.infoTitle = UILabel()
self.infoTitle.frame = CGRectMake(0, 5, screenSizeWidth, 50)
self.infoTitle.textColor = UIColor.grayColor()
self.infoTitle.font = UIFont(name: "HelveticaNeue-Thin", size: 11)
self.infoTitle.textAlignment = NSTextAlignment.Center
self.infoTitle.numberOfLines = 0
self.addSubview(self.progressActivity)
self.addSubview(self.infoTitle)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func startProgress() {
self.progressActivity.startAnimating()
}
func stopProgress() {
self.progressActivity.stopAnimating()
self.hideTitle()
}
func titleText(text:String) {
self.infoTitle.text = text
self.showTitle()
}
func showTitle() {
self.infoTitle.hidden = false
}
func hideTitle() {
self.infoTitle.hidden = true
}
}
|
mit
|
danthorpe/DNTFeatures
|
Tests/FeatureKit/StorageTests.swift
|
3
|
4358
|
//
// FeatureKit
//
// Copyright © 2016 FeatureKit. All rights reserved.
//
import XCTest
@testable import FeatureKit
class TestableUserDefaults: UserDefaultsProtocol {
var objects: [String: Any] = [:]
var didReadObjectForKey: String? = .none
var didSetObjectForKey: String? = .none
var didRemoveObjectForKey: String? = .none
var didGetDictionaryRepresentation = false
func object(forKey defaultName: String) -> Any? {
didReadObjectForKey = defaultName
return objects[defaultName]
}
func set(_ value: Any?, forKey defaultName: String) {
didSetObjectForKey = defaultName
objects[defaultName] = value
}
func removeObject(forKey defaultName: String) {
didRemoveObjectForKey = defaultName
objects.removeValue(forKey: defaultName)
}
func dictionaryRepresentation() -> [String: Any] {
didGetDictionaryRepresentation = true
return objects
}
}
class ArchivableTestFeature: NSObject, NSCoding, FeatureProtocol {
typealias FeatureIdentifier = String
let id: String
var parent: String? = .none
var title: String
var isEditable: Bool = false
var isAvailable: Bool = false
init(id: String, parent: String? = .none, title: String, available: Bool = false) {
self.id = id
self.parent = parent
self.title = title
self.isAvailable = available
super.init()
}
required init?(coder aDecoder: NSCoder) {
guard let
identifier = aDecoder.decodeObject(forKey: "id") as? String
else { return nil }
id = identifier
parent = aDecoder.decodeObject(forKey: "parent") as? String
title = aDecoder.decodeObject(forKey: "title") as! String
isEditable = aDecoder.decodeBool(forKey: "editable")
isAvailable = aDecoder.decodeBool(forKey: "available")
}
func encode(with aCoder: NSCoder) {
aCoder.encode(isAvailable, forKey: "available")
aCoder.encode(isEditable, forKey: "editable")
aCoder.encode(title, forKey: "title")
aCoder.encode(parent, forKey: "parent")
aCoder.encode(id, forKey: "id")
}
}
class UserDefaultsStorageTests: XCTestCase {
typealias UserDefaultsAdaptor = UserDefaultsStorage<String, ArchivableTestFeature>
typealias Storage = AnyStorage<String, ArchivableTestFeature>
var testableUserDefaults: TestableUserDefaults!
var adaptor: UserDefaultsAdaptor!
var storage: Storage!
override func setUp() {
super.setUp()
testableUserDefaults = TestableUserDefaults()
adaptor = UserDefaultsStorage()
adaptor.userDefaults = testableUserDefaults as UserDefaultsProtocol
storage = AnyStorage(adaptor)
}
override func tearDown() {
storage = nil
adaptor = nil
testableUserDefaults = nil
super.tearDown()
}
func test__empty_prefix() {
adaptor = UserDefaultsStorage(prefix: "")
adaptor.userDefaults = testableUserDefaults as UserDefaultsProtocol
storage = AnyStorage(adaptor)
let _ = storage["hello"]
XCTAssertEqual(testableUserDefaults.didReadObjectForKey, "\(adaptor.prefix).hello")
}
func test__read_when_no_items_exit() {
let result = storage["hello"]
XCTAssertEqual(testableUserDefaults.didReadObjectForKey, "\(adaptor.prefix).hello")
XCTAssertNil(result)
XCTAssertEqual(storage.values.count, 0)
}
func test__write_then_read() {
storage["Foo"] = ArchivableTestFeature(id: "Foo", title: "foo")
XCTAssertEqual(storage.values.count, 1)
let result = storage["Foo"]
XCTAssertNotNil(result)
XCTAssertEqual(result?.id ?? "Wrong", "Foo")
}
func test__write_then_remove() {
storage["Foo"] = ArchivableTestFeature(id: "Foo", title: "foo")
XCTAssertEqual(storage.values.count, 1)
storage["Foo"] = nil
let result = storage["Foo"]
XCTAssertNil(result)
XCTAssertEqual(storage.values.count, 0)
}
func test__remove_all_items() {
storage["Foo"] = ArchivableTestFeature(id: "Foo", title: "foo")
storage["Bar"] = ArchivableTestFeature(id: "Bar", title: "bar")
storage.removeAll()
XCTAssertEqual(storage.values.count, 0)
}
}
|
mit
|
brennanMKE/StravaKit
|
Sources/StravaAthlete.swift
|
2
|
7345
|
//
// StravaAthlete.swift
// StravaKit
//
// Created by Brennan Stehling on 8/21/16.
// Copyright © 2016 SmallSharpTools LLC. All rights reserved.
//
import Foundation
public enum AthleteResourcePath: String {
case Athlete = "/api/v3/athlete"
case Athletes = "/api/v3/athletes/:id"
case Friends = "/api/v3/athlete/friends"
case Zones = "/api/v3/athlete/zones"
case Stats = "/api/v3/athletes/:id/stats"
}
public extension Strava {
/**
Gets profile for current athlete.
```swift
Strava.getAthlete { (athlete, error) in }
```
Docs: http://strava.github.io/api/v3/athlete/#get-details
*/
@discardableResult
public static func getAthlete(_ completionHandler: ((_ athlete: Athlete?, _ error: NSError?) -> ())?) -> URLSessionTask? {
let path = AthleteResourcePath.Athlete.rawValue
return request(.GET, authenticated: true, path: path, params: nil) { (response, error) in
if let error = error {
DispatchQueue.main.async {
completionHandler?(nil, error)
}
return
}
handleAthleteResponse(response, completionHandler: completionHandler)
}
}
/**
Gets profile for athlete by ID.
```swift
Strava.getAthlete(athleteId) { (athlete, error) in }
```
Docs: http://strava.github.io/api/v3/athlete/#get-another-details
*/
@discardableResult
public static func getAthlete(_ athleteId: Int, completionHandler: ((_ athlete: Athlete?, _ error: NSError?) -> ())?) -> URLSessionTask? {
let path = replaceId(id: athleteId, in: AthleteResourcePath.Athletes.rawValue)
return request(.GET, authenticated: true, path: path, params: nil) { (response, error) in
if let error = error {
DispatchQueue.main.async {
completionHandler?(nil, error)
}
return
}
handleAthleteResponse(response, completionHandler: completionHandler)
}
}
/**
Gets friends of current athlete.
```swift
Strava.getAthleteFriends { (athletes, error) in }
```
Docs: http://strava.github.io/api/v3/follow/#friends
*/
@discardableResult
public static func getAthleteFriends(_ page: Page? = nil, completionHandler: ((_ athletes: [Athlete]?, _ error: NSError?) -> ())?) -> URLSessionTask? {
let path = AthleteResourcePath.Friends.rawValue
var params: ParamsDictionary? = nil
if let page = page {
params = [
PageKey: page.page,
PerPageKey: page.perPage
]
}
return request(.GET, authenticated: true, path: path, params: params) { (response, error) in
if let error = error {
DispatchQueue.main.async {
completionHandler?(nil, error)
}
return
}
handleAthleteFriendsResponse(response, completionHandler: completionHandler)
}
}
/**
Gets zones of current athlete.
```swift
Strava.getAthleteZones { (zones, error) in }
```
Docs: http://strava.github.io/api/v3/athlete/#zones
*/
@discardableResult
public static func getAthleteZones(_ page: Page? = nil, completionHandler: ((_ zones: Zones?, _ error: NSError?) -> ())?) -> URLSessionTask? {
let path = AthleteResourcePath.Zones.rawValue
var params: ParamsDictionary? = nil
if let page = page {
params = [
PageKey: page.page,
PerPageKey: page.perPage
]
}
return request(.GET, authenticated: true, path: path, params: params) { (response, error) in
if let error = error {
DispatchQueue.main.async {
completionHandler?(nil, error)
}
return
}
handleAthleteZonesResponse(response, completionHandler: completionHandler)
}
}
/**
Gets stats for athlete by ID.
```swift
Strava.getStats(athleteId, completionHandler: { (stats, error) in }
```
Docs: http://strava.github.io/api/v3/athlete/#stats
*/
@discardableResult
public static func getStats(_ athleteId: Int, completionHandler: ((_ stats: Stats?, _ error: NSError?) -> ())?) -> URLSessionTask? {
let path = replaceId(id: athleteId, in: AthleteResourcePath.Stats.rawValue)
return request(.GET, authenticated: true, path: path, params: nil) { (response, error) in
if let error = error {
DispatchQueue.main.async {
completionHandler?(nil, error)
}
return
}
handleStatsResponse(athleteId, response: response, completionHandler: completionHandler)
}
}
// MARK: - Internal Functions -
internal static func handleAthleteResponse(_ response: Any?, completionHandler: ((_ athlete: Athlete?, _ error: NSError?) -> ())?) {
if let dictionary = response as? JSONDictionary,
let athlete = Athlete(dictionary: dictionary) {
DispatchQueue.main.async {
completionHandler?(athlete, nil)
}
}
else {
let error = Strava.error(.invalidResponse, reason: "Invalid Response")
DispatchQueue.main.async {
completionHandler?(nil, error)
}
}
}
internal static func handleAthleteFriendsResponse(_ response: Any?, completionHandler: ((_ athletes: [Athlete]?, _ error: NSError?) -> ())?) {
if let dictionaries = response as? JSONArray {
let athletes = Athlete.athletes(dictionaries)
DispatchQueue.main.async {
completionHandler?(athletes, nil)
}
}
else {
let error = Strava.error(.invalidResponse, reason: "Invalid Response")
DispatchQueue.main.async {
completionHandler?(nil, error)
}
}
}
internal static func handleAthleteZonesResponse(_ response: Any?, completionHandler: ((_ zones: Zones?, _ error: NSError?) -> ())?) {
if let dictionary = response as? JSONDictionary,
let zones = Zones(dictionary: dictionary) {
DispatchQueue.main.async {
completionHandler?(zones, nil)
}
}
else {
let error = Strava.error(.invalidResponse, reason: "Invalid Response")
DispatchQueue.main.async {
completionHandler?(nil, error)
}
}
}
internal static func handleStatsResponse(_ athleteId: Int, response: Any?, completionHandler: ((_ stats: Stats?, _ error: NSError?) -> ())?) {
if let dictionary = response as? JSONDictionary,
let stats = Stats(athleteId: athleteId, dictionary: dictionary) {
DispatchQueue.main.async {
completionHandler?(stats, nil)
}
}
else {
let error = Strava.error(.invalidResponse, reason: "Invalid Response")
DispatchQueue.main.async {
completionHandler?(nil, error)
}
}
}
}
|
mit
|
justindarc/firefox-ios
|
Client/Frontend/Browser/NoImageModeHelper.swift
|
1
|
1390
|
/* 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 NoImageModePrefsKey {
static let NoImageModeStatus = PrefsKeys.KeyNoImageModeStatus
}
class NoImageModeHelper: TabContentScript {
fileprivate weak var tab: Tab?
required init(tab: Tab) {
self.tab = tab
}
static func name() -> String {
return "NoImageMode"
}
func scriptMessageHandlerName() -> String? {
return "NoImageMode"
}
func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
// Do nothing.
}
static func isActivated(_ prefs: Prefs) -> Bool {
return prefs.boolForKey(NoImageModePrefsKey.NoImageModeStatus) ?? false
}
static func toggle(isEnabled: Bool, profile: Profile, tabManager: TabManager) {
if let appDelegate = UIApplication.shared.delegate as? AppDelegate, let bvc = appDelegate.browserViewController {
bvc.navigationToolbar.hideImagesBadge(visible: isEnabled)
}
profile.prefs.setBool(isEnabled, forKey: PrefsKeys.KeyNoImageModeStatus)
tabManager.tabs.forEach { $0.noImageMode = isEnabled }
}
}
|
mpl-2.0
|
safx/IIJMioKit
|
IIJMioKitSample/PacketLogCell.swift
|
1
|
1229
|
//
// PacketLogCell.swift
// IIJMioKit
//
// Created by Safx Developer on 2015/05/16.
// Copyright (c) 2015年 Safx Developers. All rights reserved.
//
import UIKit
import IIJMioKit
class PacketLogCell: UITableViewCell {
@IBOutlet weak var date: UILabel!
@IBOutlet weak var withCoupon: UILabel!
@IBOutlet weak var withoutCoupon: UILabel!
private let dateFormatter = NSDateFormatter()
var model: MIOPacketLog? {
didSet { modelDidSet() }
}
private func modelDidSet() {
dateFormatter.dateFormat = "YYYY-MM-dd"
date!.text = dateFormatter.stringFromDate(model!.date)
let f = NSByteCountFormatter()
f.allowsNonnumericFormatting = false
f.allowedUnits = [.UseMB, .UseGB]
withCoupon!.text = f.stringFromByteCount(Int64(model!.withCoupon * 1000 * 1000))
withoutCoupon!.text = f.stringFromByteCount(Int64(model!.withoutCoupon * 1000 * 1000))
}
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
}
}
|
mit
|
tkester/swift-algorithm-club
|
Ordered Set/AppleOrderedSet.swift
|
2
|
1965
|
public class AppleOrderedSet<T: Hashable> {
private var objects: [T] = []
private var indexOfKey: [T: Int] = [:]
public init() {}
// O(1)
public func add(_ object: T) {
guard indexOfKey[object] == nil else {
return
}
objects.append(object)
indexOfKey[object] = objects.count - 1
}
// O(n)
public func insert(_ object: T, at index: Int) {
assert(index < objects.count, "Index should be smaller than object count")
assert(index >= 0, "Index should be bigger than 0")
guard indexOfKey[object] == nil else {
return
}
objects.insert(object, at: index)
indexOfKey[object] = index
for i in index+1..<objects.count {
indexOfKey[objects[i]] = i
}
}
// O(1)
public func object(at index: Int) -> T {
assert(index < objects.count, "Index should be smaller than object count")
assert(index >= 0, "Index should be bigger than 0")
return objects[index]
}
// O(1)
public func set(_ object: T, at index: Int) {
assert(index < objects.count, "Index should be smaller than object count")
assert(index >= 0, "Index should be bigger than 0")
guard indexOfKey[object] == nil else {
return
}
indexOfKey.removeValue(forKey: objects[index])
indexOfKey[object] = index
objects[index] = object
}
// O(1)
public func indexOf(_ object: T) -> Int {
return indexOfKey[object] ?? -1
}
// O(n)
public func remove(_ object: T) {
guard let index = indexOfKey[object] else {
return
}
indexOfKey.removeValue(forKey: object)
objects.remove(at: index)
for i in index..<objects.count {
indexOfKey[objects[i]] = i
}
}
}
|
mit
|
DerekYuYi/Ant
|
MyPlayground.playground/Pages/Collection Types.xcplaygroundpage/Contents.swift
|
1
|
1529
|
//: [Previous](@previous)
import Foundation
var str = "Hello, playground"
//: [Next](@next)
/// 使用 stride 进行周期性的运算
//: 从 from 开始,以间距 by 为单位到 to 但小于 to
for tickMark in stride(from: 0, to: 60, by: 5) {
print(tickMark)
}
let hours = 12
let hourInterval = 3
//: 从 from 开始,以间距 by 为单位到 through 但不超过
for tickMark in stride(from: 3, through: hours, by: hourInterval) {
print("----\(tickMark)")
}
// Tuples
let somePoint = (1, 1)
switch somePoint {
case (0, 0):
print("\(somePoint) is at the origin")
case (_, 0):
print("\(somePoint) is on the x-axis")
case (0, _):
print("\(somePoint) is on the y-axis")
case (-2...2, -2...2):
print("\(somePoint) is inside the box")
default:
print("\(somePoint) is outside of the box")
}
// Value Bindings
let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
print("on the x-axis with an x value of \(x)")
case (0, let y):
print("on the y-axis with a y value of \(y)")
case let (x, y):
print("somewhere else at (\(x), \(y)")
}
// Where
let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y:
print("(\(x), \(y)) is on the line x == y")
case let (x, y) where x == -y:
print("(\(x), \(y)) is on the line x == -y")
case let (x, y):
print("(\(x), \(y)) is just some arbitrary point")
}
///: 使用 `fallthrough` 来实现 switch 中 case 的贯穿
///: Checking API Availability
if #available(iOS 11, macOS 10.12, *) {
}
|
mit
|
mightydeveloper/swift
|
validation-test/compiler_crashers_fixed/0984-swift-constraints-constraintsystem-simplifyconstraint.swift
|
13
|
260
|
// 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
let c : String = nil
struct A {
func a<h : a
|
apache-2.0
|
mightydeveloper/swift
|
validation-test/compiler_crashers_fixed/0983-a.swift
|
13
|
288
|
// 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
class A<T {
var b: a {
d) -> {
}
}
let b = 1
protocol c : c {
func c<T,
|
apache-2.0
|
Maaimusic/BTree
|
Tests/BTreeTests/BTreeBuilderTests.swift
|
3
|
9388
|
//
// BTreeBuilderTests.swift
// BTree
//
// Created by Károly Lőrentey on 2016-02-29.
// Copyright © 2016–2017 Károly Lőrentey.
//
import XCTest
@testable import BTree
class BTreeBuilderTests: XCTestCase {
typealias Builder = BTreeBuilder<Int, String>
typealias Node = BTreeNode<Int, String>
typealias Tree = BTree<Int, String>
typealias Element = (Int, String)
func elements<S: Sequence>(_ range: S) -> [Element] where S.Element == Int {
return range.map { ($0, String($0)) }
}
func testBTreeInitDropDuplicatesEmpty() {
let tree = Tree(sortedElements: [], dropDuplicates: true, order: 5)
tree.assertValid()
assert(tree.order == 5)
assertEqualElements(tree, [])
}
func testBTreeInitDropDuplicates() {
let tree = Tree(sortedElements: [(0, "0"), (0, "1"), (0, "2"), (1, "3"), (1, "4")], dropDuplicates: true, order: 5)
tree.assertValid()
assert(tree.order == 5)
assertEqualElements(tree, [(0, "2"), (1, "4")])
}
func testEmpty() {
var builder = Builder(order: 5, keysPerNode: 3)
let tree = builder.finish()
tree.assertValid()
assert(tree.order == 5)
assertEqualElements(tree, [])
}
func testSingleElement() {
var builder = Builder(order: 5, keysPerNode: 3)
builder.append((0, "0"))
let tree = builder.finish()
tree.assertValid()
assertEqualElements(tree, [(0, "0")])
}
func testFullNodeWithDepth0() {
var builder = Builder(order: 5, keysPerNode: 3)
builder.append((0, "0"))
builder.append((1, "1"))
builder.append((2, "2"))
let node = builder.finish()
node.assertValid()
node.forEachNode { XCTAssertEqual($0.elements.count, 3) }
assertEqualElements(node, [(0, "0"), (1, "1"), (2, "2")])
XCTAssertEqual(node.depth, 0)
}
func testFullNodeWithDepth1() {
var builder = Builder(order: 5, keysPerNode: 3)
for i in 0 ..< 15 {
builder.append((i, String(i)))
}
let node = builder.finish()
node.assertValid()
node.forEachNode { XCTAssertEqual($0.elements.count, 3) }
assertEqualElements(node, (0 ..< 15).map { ($0, String($0)) })
XCTAssertEqual(node.depth, 1)
}
func testFullNodeWithDepth2() {
var builder = Builder(order: 5, keysPerNode: 3)
for i in 0 ..< 63 {
builder.append((i, String(i)))
}
let node = builder.finish()
node.assertValid()
node.forEachNode { XCTAssertEqual($0.elements.count, 3) }
assertEqualElements(node, (0 ..< 63).map { ($0, String($0)) })
XCTAssertEqual(node.depth, 2)
}
func testPartialNodeWithDepth2() {
var builder = Builder(order: 5, keysPerNode: 3)
for i in 0 ..< 60 {
builder.append((i, String(i)))
}
let node = builder.finish()
node.assertValid()
assertEqualElements(node, (0 ..< 60).map { ($0, String($0)) })
XCTAssertEqual(node.depth, 2)
}
func testAppendingEmptyNodes() {
var builder = Builder(order: 5, keysPerNode: 3)
for i in 0 ..< 63 {
builder.append(Node(order: 5))
builder.append((i, String(i)))
}
builder.append(Node(order: 5))
let node = builder.finish()
node.assertValid()
node.forEachNode { XCTAssertEqual($0.elements.count, 3) }
assertEqualElements(node, (0 ..< 63).map { ($0, String($0)) })
XCTAssertEqual(node.depth, 2)
}
func testAppendingSingleElementNodes() {
var builder = Builder(order: 5, keysPerNode: 3)
for i in 0 ..< 63 {
let node = Node(order: 5, elements: [(i, String(i))], children: [], count: 1)
builder.append(node)
}
let node = builder.finish()
node.assertValid()
node.forEachNode { XCTAssertEqual($0.elements.count, 3) }
assertEqualElements(node, (0 ..< 63).map { ($0, String($0)) })
XCTAssertEqual(node.depth, 2)
}
func testAppendingTwoElementNodes() {
var builder = Builder(order: 5, keysPerNode: 3)
for i in 0 ..< 31 {
let node = Node(order: 5, elements: elements(2 * i ..< 2 * i + 2), children: [], count: 2)
builder.append(node)
}
builder.append((62, "62"))
let node = builder.finish()
node.assertValid()
node.forEachNode { XCTAssertEqual($0.elements.count, 3) }
assertEqualElements(node, (0 ..< 63).map { ($0, String($0)) })
XCTAssertEqual(node.depth, 2)
}
func testAppendingThreeElementNodes() {
var builder = Builder(order: 5, keysPerNode: 3)
for i in 0 ..< 21 {
let node = Node(order: 5, elements: elements(3 * i ..< 3 * i + 3), children: [], count: 3)
builder.append(node)
}
let node = builder.finish()
node.assertValid()
node.forEachNode { XCTAssertEqual($0.elements.count, 3) }
assertEqualElements(node, (0 ..< 63).map { ($0, String($0)) })
XCTAssertEqual(node.depth, 2)
}
func testAppendingFourElementNodes() {
var builder = Builder(order: 5, keysPerNode: 3)
for i in 0 ..< 15 {
let node = Node(order: 5, elements: elements(4 * i ..< 4 * i + 4), children: [], count: 4)
builder.append(node)
}
builder.append((60, "60"))
builder.append((61, "61"))
builder.append((62, "62"))
let node = builder.finish()
node.assertValid()
assertEqualElements(node, (0 ..< 63).map { ($0, String($0)) })
XCTAssertEqual(node.depth, 2)
}
func testAppendingNodesWithDepth1() {
var builder = Builder(order: 5, keysPerNode: 3)
var i = 0
for _ in 0 ..< 5 {
let node = maximalNode(depth: 1, order: 5, offset: i)
i += node.count
builder.append(node)
}
let node = builder.finish()
node.assertValid()
assertEqualElements(node.map { $0.0 }, 0 ..< i)
}
func testAppendingOneElementThenANodeWithDepth1() {
var builder = Builder(order: 5, keysPerNode: 3)
var i = 0
for _ in 0 ..< 4 {
builder.append((i, String(i)))
i += 1
let node = minimalNode(depth: 1, order: 5, offset: i)
i += node.count
builder.append(node)
}
let node = builder.finish()
node.assertValid()
assertEqualElements(node.map { $0.0 }, 0 ..< i)
}
func testAppendingTwoElementsThenANodeWithDepth1() {
var builder = Builder(order: 5, keysPerNode: 3)
var i = 0
for _ in 0 ..< 4 {
builder.append((i, String(i)))
builder.append((i + 1, String(i + 1)))
i += 2
let node = minimalNode(depth: 1, order: 5, offset: i)
i += node.count
builder.append(node)
}
let node = builder.finish()
node.assertValid()
assertEqualElements(node.map { $0.0 }, 0 ..< i)
}
func testAppendingTheSameNode() {
// First, create a node with uniform keys.
let nodeSize = 20
var b = Builder(order: 5, keysPerNode: 4)
for i in 0 ..< nodeSize {
b.append((0, "\(i)"))
}
let node = b.finish()
let values = (0 ..< nodeSize).map { "\($0)" }
// Next, append this node 10 times to a new builder.
var builder = Builder(order: 5, keysPerNode: 4)
let appendCount = 10
for _ in 0 ..< appendCount {
builder.append(node)
assertEqualElements(node.map { $0.1 }, values)
}
let large = builder.finish()
assertEqualElements(large.map { $0.1 }, (0 ..< appendCount).flatMap { _ in values })
// The result should have duplicate nodes.
var nodes: Set<Ref<Node>> = []
var nodeCount = 0
large.forEachNode { node in
nodes.insert(Ref(target: node))
nodeCount += 1
}
XCTAssertLessThan(nodes.count, nodeCount)
}
func testAppendingSubtrees() {
// First, create a node with uniform keys.
let nodeSize = 50
var b = Builder(order: 5, keysPerNode: 4)
for i in 0 ..< nodeSize {
b.append((0, "\(i)"))
}
let node = b.finish()
var values: [Node] = []
node.forEachNode { n in
values.append(n.clone())
}
// Next, append all subtrees of this node to a new builder.
var builder = Builder(order: 5, keysPerNode: 4)
node.forEachNode { n in
builder.append(n)
}
let large = builder.finish()
// Result should have the same elements as the previously extracted subtree array.
assertEqualElements(large.map { $0.1 }, values.flatMap { $0.map { $0.1 } })
// The node should have the exact same subnodes as before.
var i = 0
node.forEachNode { n in
let expected = values[i]
XCTAssertEqual(n.count, expected.count)
assertEqualElements(n.elements, expected.elements)
XCTAssertTrue(n.children.elementsEqual(expected.children, by: ===))
i += 1
}
}
}
|
mit
|
AvdLee/ALDataRequestView
|
Source/ALDataRequestView.swift
|
1
|
10541
|
//
// ALDataRequestView.swift
// Pods
//
// Created by Antoine van der Lee on 28/02/16.
//
//
import UIKit
import PureLayout
import ReachabilitySwift
public typealias RetryAction = (() -> Void)
public enum RequestState {
case possible
case loading
case failed
case success
case empty
}
public enum ReloadReason {
case generalError
case noInternetConnection
}
public struct ReloadType {
public var reason: ReloadReason
public var error: Error?
}
public protocol Emptyable {
var isEmpty:Bool { get }
}
public protocol ALDataReloadType {
var retryButton:UIButton? { get set }
func setup(for reloadType:ReloadType)
}
// Make methods optional with default implementations
public extension ALDataReloadType {
func setup(for reloadType:ReloadType){ }
}
public protocol ALDataRequestViewDataSource : class {
func loadingView(for dataRequestView: ALDataRequestView) -> UIView?
func reloadViewController(for dataRequestView: ALDataRequestView) -> ALDataReloadType?
func emptyView(for dataRequestView: ALDataRequestView) -> UIView?
func hideAnimationDuration(for dataRequestView: ALDataRequestView) -> Double
func showAnimationDuration(for dataRequestView: ALDataRequestView) -> Double
}
// Make methods optional with default implementations
public extension ALDataRequestViewDataSource {
func loadingView(for dataRequestView: ALDataRequestView) -> UIView? { return nil }
func reloadViewController(for dataRequestView: ALDataRequestView) -> ALDataReloadType? { return nil }
func emptyView(for dataRequestView: ALDataRequestView) -> UIView? { return nil }
func hideAnimationDuration(for dataRequestView: ALDataRequestView) -> Double { return 0 }
func showAnimationDuration(for dataRequestView: ALDataRequestView) -> Double { return 0 }
}
public class ALDataRequestView: UIView {
// Public properties
public weak var dataSource:ALDataRequestViewDataSource?
/// Action for retrying a failed situation
/// Will be triggered by the retry button, on foreground or when reachability changed to connected
public var retryAction:RetryAction?
/// If failed earlier, the retryAction will be triggered on foreground
public var automaticallyRetryOnForeground:Bool = true
/// If failed earlier, the retryAction will be triggered when reachability changed to reachable
public var automaticallyRetryWhenReachable:Bool = true
/// Set to true for debugging purposes
public var loggingEnabled:Bool = false
// Internal properties
internal var state:RequestState = .possible
// Private properties
private var loadingView:UIView?
private var reloadView:UIView?
private var emptyView:UIView?
fileprivate var reachability:Reachability?
override public func awakeFromNib() {
super.awakeFromNib()
setup()
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
internal func setup(){
// Hide by default
isHidden = true
// Background color is not needed
backgroundColor = UIColor.clear
// Setup for automatic retrying
initOnForegroundObserver()
initReachabilityMonitoring()
debugLog(logString: "Init DataRequestView")
}
deinit {
NotificationCenter.default.removeObserver(self)
debugLog(logString: "Deinit DataRequestView")
}
// MARK: Public Methods
public func changeRequestState(state:RequestState, error: Error? = nil){
guard state != self.state else { return }
layer.removeAllAnimations()
self.state = state
resetToPossibleState(completion: { [weak self] (completed) in ()
guard let state = self?.state else { return }
switch state {
case .loading:
self?.showLoadingView()
break
case .failed:
self?.showReloadView(error: error)
break
case .empty:
self?.showEmptyView()
break
default:
break
}
})
}
// MARK: Private Methods
/// This will remove all views added
private func resetToPossibleState(completion: ((Bool) -> Void)?){
UIView.animate(withDuration: dataSource?.hideAnimationDuration(for: self) ?? 0, animations: { [weak self] in ()
self?.loadingView?.alpha = 0
self?.emptyView?.alpha = 0
self?.reloadView?.alpha = 0
}) { [weak self] (completed) in
self?.resetViews(views: [self?.loadingView, self?.emptyView, self?.reloadView])
self?.isHidden = true
completion?(completed)
}
}
private func resetViews(views: [UIView?]) {
views.forEach { (view) in
view?.alpha = 1
view?.removeFromSuperview()
}
}
/// This will show the loading view
internal func showLoadingView(){
guard let dataSourceLoadingView = dataSource?.loadingView(for: self) else {
debugLog(logString: "No loading view provided!")
return
}
isHidden = false
loadingView = dataSourceLoadingView
// Only add if not yet added
if loadingView?.superview == nil {
addSubview(loadingView!)
loadingView?.autoPinEdgesToSuperviewEdges()
layoutIfNeeded()
}
dataSourceLoadingView.showWithDuration(duration: dataSource?.showAnimationDuration(for: self))
}
/// This will show the reload view
internal func showReloadView(error: Error? = nil){
guard let dataSourceReloadType = dataSource?.reloadViewController(for: self) else {
debugLog(logString: "No reload view provided!")
return
}
if let dataSourceReloadView = dataSourceReloadType as? UIView {
reloadView = dataSourceReloadView
} else if let dataSourceReloadViewController = dataSourceReloadType as? UIViewController {
reloadView = dataSourceReloadViewController.view
}
guard let reloadView = reloadView else {
debugLog(logString: "Could not determine reloadView")
return
}
var reloadReason: ReloadReason = .generalError
if let error = error as NSError?, error.isNetworkConnectionError() || reachability?.isReachable == false {
reloadReason = .noInternetConnection
}
isHidden = false
addSubview(reloadView)
reloadView.autoPinEdgesToSuperviewEdges()
dataSourceReloadType.setup(for: ReloadType(reason: reloadReason, error: error))
#if os(tvOS)
if #available(iOS 9.0, *) {
dataSourceReloadType.retryButton?.addTarget(self, action: #selector(ALDataRequestView.retryButtonTapped), for: UIControlEvents.primaryActionTriggered)
}
#else
dataSourceReloadType.retryButton?.addTarget(self, action: #selector(ALDataRequestView.retryButtonTapped), for: UIControlEvents.touchUpInside)
#endif
reloadView.showWithDuration(duration: dataSource?.showAnimationDuration(for: self))
}
/// This will show the empty view
internal func showEmptyView(){
guard let dataSourceEmptyView = dataSource?.emptyView(for: self) else {
debugLog(logString: "No empty view provided!")
// Hide as we don't have anything to show from the empty view
isHidden = true
return
}
isHidden = false
emptyView = dataSourceEmptyView
addSubview(emptyView!)
emptyView?.autoPinEdgesToSuperviewEdges()
dataSourceEmptyView.showWithDuration(duration: dataSource?.showAnimationDuration(for: self))
}
/// IBAction for the retry button
@objc private func retryButtonTapped(button:UIButton){
retryIfRetryable()
}
/// This will trigger the retryAction if current state is failed
fileprivate func retryIfRetryable(){
guard state == RequestState.failed else {
return
}
guard let retryAction = retryAction else {
debugLog(logString: "No retry action provided")
return
}
retryAction()
}
}
/// On foreground Observer methods.
private extension ALDataRequestView {
func initOnForegroundObserver(){
NotificationCenter.default.addObserver(self, selector: #selector(ALDataRequestView.onForeground), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
}
@objc private func onForeground(notification:NSNotification){
guard automaticallyRetryOnForeground == true else {
return
}
retryIfRetryable()
}
}
/// Reachability methods
private extension ALDataRequestView {
func initReachabilityMonitoring() {
reachability = Reachability()
reachability?.whenReachable = { [weak self] reachability in
guard self?.automaticallyRetryWhenReachable == true else {
return
}
self?.retryIfRetryable()
}
do {
try reachability?.startNotifier()
} catch {
debugLog(logString: "Unable to start notifier")
}
}
}
/// Logging purposes
private extension ALDataRequestView {
func debugLog(logString:String){
guard loggingEnabled else { return }
print("ALDataRequestView: \(logString)")
}
}
/// NSError extension
private extension NSError {
func isNetworkConnectionError() -> Bool {
let networkErrors = [NSURLErrorNetworkConnectionLost, NSURLErrorNotConnectedToInternet]
if domain == NSURLErrorDomain && networkErrors.contains(code) {
return true
}
return false
}
}
/// UIView extension
private extension UIView {
func showWithDuration(duration: Double?) {
guard let duration = duration else {
alpha = 1
return
}
alpha = 0
UIView.animate(withDuration: duration, animations: {
self.alpha = 1
})
}
}
|
mit
|
anilmanukonda/Watson
|
Watson/Watson/DeviceModel.swift
|
1
|
1968
|
//
// DeviceModel.swift
// Watson
//
// Created by Manukonda, Anil-CW on 3/2/17.
// Copyright © 2017 Anil. All rights reserved.
//
import Foundation
public enum DeviceModel: String {
static var deviceMap: [String:[String]] {
return [
"iPhone4S": ["iPhone4,1"],
"iPhone5": ["iPhone5,1", "iPhone5,2"],
"iPhone5C": ["iPhone5,3", "iPhone5,4"],
"iPhone5S": ["iPhone6,1", "iPhone6,2"],
"iPhone6": ["iPhone7,2"],
"iPhone6Plus": ["iPhone7,1"],
"iPhone6S": ["iPhone8,1"],
"iPhone6SPlus": ["iPhone8,2"],
"iPhone7": ["iPhone9,1", "iPhone9,3"],
"iPhone7Plus": ["iPhone9,2", "iPhone9,4"],
"iPad2": ["iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4"],
"iPad3": ["iPad3,1", "iPad3,2", "iPad3,3"],
"iPad4": ["iPad3,4", "iPad3,5", "iPad3,6"],
"iPadAir": ["iPad4,1", "iPad4,2", "iPad4,3"],
"iPadAir2": ["iPad5,3", "iPad5,4"],
"iPadMini": ["iPad2,5", "iPad2,6", "iPad2,7"],
"iPadMini2": ["iPad4,4", "iPad4,5", "iPad4,6"],
"iPadMini3": ["iPad4,7", "iPad4,8", "iPad4,9"],
"iPadMini4": ["iPad5,1", "iPad5,2"],
"iPadPro9": ["iPad6,3", "iPad6,4"],
"iPadPro12": ["iPad6,7", "iPad6,8"]
]
}
case iPhone4S
case iPhone5
case iPhone5C
case iPhone5S
case iPhoneSE
case iPhone6
case iPhone6Plus
case iPhone6S
case iPhone6SPlus
case iPhone7
case iPhone7Plus
case iPad2
case iPad3
case iPad4
case iPadAir
case iPadAir2
case iPadMini
case iPadMini2
case iPadMini3
case iPadMini4
case iPadPro9
case iPadPro12
case other
static func deviceModel(for identifier: String) -> DeviceModel {
guard let model = deviceMap.first(where: { $0.value.contains(identifier) }) else {
return DeviceModel.other
}
return DeviceModel(rawValue: model.key) ?? DeviceModel.other
}
}
|
mit
|
CPRTeam/CCIP-iOS
|
OPass/Class+addition/OPassAPI/EventScenario.swift
|
1
|
11297
|
//
// EventScenario.swift
// OPass
//
// Created by 腹黒い茶 on 2019/6/17.
// 2019 OPass.
//
import Foundation
import SwiftyJSON
struct ScenarioAttribute: OPassData {
var _data: JSON
init(_ data: JSON) {
self._data = data
}
subscript(_ member: String) -> Any {
return self._data[member].object
}
}
struct Scenario: OPassData, Equatable {
static func == (lhs: Scenario, rhs: Scenario) -> Bool {
return lhs.Id == rhs.Id
}
var _data: JSON
var Id: String
var Used: Int?
var Disabled: String?
var Attributes: ScenarioAttribute
var Countdown: Int?
var ExpireTime: Int?
var AvailableTime: Int?
var DisplayText: String? {
if let longLangUI = Constants.longLangUI {
return self._data["display_text"][longLangUI].string ?? ""
}
return ""
}
var Order: Int
var Message: String?
init(_ data: JSON) {
self._data = data
self.Id = self._data["id"].stringValue
self.Used = self._data["used"].int
self.Disabled = self._data["disabled"].string
self.Attributes = ScenarioAttribute(self._data["attr"])
self.Countdown = self._data["countdown"].int
self.ExpireTime = self._data["expire_time"].int
self.AvailableTime = self._data["available_time"].int
self.Order = self._data["order"].intValue
self.Message = self._data["message"].string
}
}
struct ScenarioStatus: OPassData {
var _data: JSON
var _id: String {
return self._data["_id"].dictionaryValue["$oid"]!.stringValue
}
var EventId: String
var Token: String
var UserId: String
var Attributes: ScenarioAttribute
var FirstUse: Int64
var Role: String
var Scenarios: [Scenario]
init(_ data: JSON) {
self._data = data
self.EventId = self._data["event_id"].stringValue
self.Token = self._data["token"].stringValue
self.UserId = self._data["user_id"].stringValue
self.Attributes = ScenarioAttribute(self._data["attr"])
self.FirstUse = self._data["first_use"].int64Value
self.Role = self._data["role"].stringValue
self.Scenarios = self._data["scenarios"].arrayValue.map { obj -> Scenario in
return Scenario(obj)
}
}
subscript(_ member: String) -> String {
return self._data[member].stringValue
}
}
extension OPassAPI {
static func RedeemCode(_ event: String, _ token: String, _ completion: OPassCompletionCallback) {
var event = event
if event == "" {
event = OPassAPI.currentEvent
}
let token = token.trim()
let allowedCharacters = NSMutableCharacterSet.init(charactersIn: "-_")
allowedCharacters.formUnion(with: NSCharacterSet.alphanumerics)
let nonAllowedCharacters = allowedCharacters.inverted
if (token.count != 0 && token.rangeOfCharacter(from: nonAllowedCharacters) == nil) {
OPassAPI.isLoginSession = false
Constants.accessToken = ""
OPassAPI.InitializeRequest(Constants.URL_STATUS(token: token)) { _, _, error, _ in
completion?(false, nil, error)
}.then { (obj: Any?) -> Void in
if let o = obj {
if obj != nil {
switch String(describing: type(of: o)) {
case OPassNonSuccessDataResponse.className:
OPassAPI.duringLoginFromLink = false
if let opec = UIApplication.getMostTopPresentedViewController() as? OPassEventsController {
opec.performSegue(withIdentifier: "OPassTabView", sender: OPassAPI.eventInfo)
}
if let sr = o as? OPassNonSuccessDataResponse {
if let response = sr.Response {
switch response.statusCode {
case 400:
completion?(false, sr, NSError(domain: "OPass Redeem Code Invalid", code: 4, userInfo: nil))
break
default:
completion?(false, sr, NSError(domain: "OPass Redeem Code Invalid", code: 4, userInfo: nil))
}
}
}
break
default:
let status = ScenarioStatus(JSON(o))
Constants.accessToken = token
OPassAPI.userInfo = status
OPassAPI.isLoginSession = true
if OPassAPI.duringLoginFromLink {
if let opec = UIApplication.getMostTopPresentedViewController() as? OPassEventsController {
opec.performSegue(withIdentifier: "OPassTabView", sender: OPassAPI.eventInfo)
}
if OPassAPI.isLoginSession {
AppDelegate.delegateInstance.displayGreetingsForLogin()
}
}
OPassAPI.duringLoginFromLink = false
AppDelegate.delegateInstance.checkinView?.reloadCard()
completion?(true, status, OPassSuccessError)
}
} else {
completion?(false, RawOPassData(o), NSError(domain: "OPass Redeem Code Invalid", code: 2, userInfo: nil))
}
}
}
} else {
completion?(false, nil, NSError(domain: "OPass Redeem Code Invalid", code: 1, userInfo: nil))
}
}
static func GetCurrentStatus(_ completion: OPassCompletionCallback) {
let event = OPassAPI.currentEvent
guard let token = Constants.accessToken else {
completion?(false, nil, NSError(domain: "Not a Valid Token", code: -1, userInfo: nil))
return
}
if event.count > 0 && token.count > 0 {
OPassAPI.InitializeRequest(Constants.URL_STATUS(token: token)) { _, _, error, _ in
completion?(false, nil, error)
}.then { (obj: Any?) -> Void in
if let o = obj {
if obj != nil {
switch String(describing: type(of: o)) {
case OPassNonSuccessDataResponse.className:
if let sr = obj as? OPassNonSuccessDataResponse {
if let response = sr.Response {
switch response.statusCode {
case 200:
completion?(false, sr, NSError(domain: "OPass Data not valid", code: 5, userInfo: nil))
default:
completion?(false, sr, NSError(domain: "OPass Current Not in Event or Not a Valid Token", code: 4, userInfo: nil))
}
}
}
default:
let status = ScenarioStatus(JSON(o))
completion?(true, status, OPassSuccessError)
}
} else {
completion?(false, RawOPassData(o), NSError(domain: "OPass Current Not in Event or Not a Valid Token", code: 2, userInfo: nil))
}
}
}
} else {
completion?(false, nil, NSError(domain: "OPass Current Not in Event or Not a Valid Token", code: 1, userInfo: nil))
}
}
static func UseScenario(_ event: String, _ token: String, _ scenario: String, _ completion: OPassCompletionCallback) {
if event.count > 0 {
OPassAPI.InitializeRequest(Constants.URL_USE(token: token, scenario: scenario)) { _, _, error, _ in
completion?(false, nil, error)
}.then { (obj: Any?) -> Void in
if let o = obj {
if obj != nil {
switch String(describing: type(of: o)) {
case OPassNonSuccessDataResponse.className:
if let sr = obj as? OPassNonSuccessDataResponse {
completion?(false, sr, NSError(domain: "OPass Scenario can not use because current is Not in Event or Not a Valid Token", code: 3, userInfo: nil))
}
default:
let used = ScenarioStatus(JSON(o))
completion?(true, used, OPassSuccessError)
}
} else {
completion?(false, RawOPassData(o), NSError(domain: "OPass Scenario can not use by return unexcepted response", code: 2, userInfo: nil))
}
}
}
} else {
completion?(false, nil, NSError(domain: "OPass Scenario can not use, because event was not set", code: 1, userInfo: nil))
}
}
static func ParseScenarioType(_ id: String) -> Dictionary<String, Any> {
let id_pattern = "^(day(\\d+))?(\\w+)$"
guard let id_regex = try? NSRegularExpression.init(pattern: id_pattern, options: .caseInsensitive) else { return [:] }
let id_matches = id_regex.matches(in: id, options: .withTransparentBounds, range: NSRangeFromString(id))
guard let did_range = id_matches.first?.range(at: 2) else {
return [
"scenarioType": id,
"did": ""
]
}
let did = String(id[String.Index(utf16Offset: did_range.location, in: id)..<String.Index(utf16Offset: did_range.length, in: id)])
guard let scenarioRange = id_matches.first?.range(at: 3) else {
return [
"scenarioType": id,
"did": did
]
}
let scenarioType = String(id[String.Index(utf16Offset: scenarioRange.location, in: id)..<String.Index(utf16Offset: scenarioRange.length, in: id)])
return [
"scenarioType": scenarioType,
"did": did
]
}
static func ParseScenarioRange(_ scenario: Scenario) -> Array<String> {
let formatter = DateFormatter.init()
formatter.dateFormat = Constants.appConfig.DisplayDateTimeFormat as? String
formatter.timeZone = NSTimeZone.default
let availDate = Date.init(timeIntervalSince1970: TimeInterval(scenario.AvailableTime ?? 0))
let expireDate = Date.init(timeIntervalSince1970: TimeInterval(scenario.ExpireTime ?? 0))
let availString = formatter.string(from: availDate)
let expireString = formatter.string(from: expireDate)
return [ availString, expireString ]
}
}
|
gpl-3.0
|
yoichitgy/SwinjectMVVMExample_ForBlog
|
SwinjectMVVMExampleTests/AppDelegateSpec.swift
|
1
|
1577
|
//
// AppDelegateSpec.swift
// SwinjectMVVMExample
//
// Created by Yoichi Tagaya on 9/1/15.
// Copyright © 2015 Swinject Contributors. All rights reserved.
//
import Quick
import Nimble
import Swinject
import ExampleModel
import ExampleViewModel
import ExampleView
@testable import SwinjectMVVMExample
class AppDelegateSpec: QuickSpec {
override func spec() {
var container: Container!
beforeEach {
container = AppDelegate().container
}
describe("Container") {
it("resolves every service type.") {
// Models
expect(container.resolve(Networking.self)).notTo(beNil())
expect(container.resolve(ImageSearching.self)).notTo(beNil())
// ViewModels
expect(container.resolve(ImageSearchTableViewModeling.self))
.notTo(beNil())
}
it("injects view models to views.") {
let bundle = NSBundle(forClass: ImageSearchTableViewController.self)
let storyboard = SwinjectStoryboard.create(
name: "Main",
bundle: bundle,
container: container)
let imageSearchTableViewController = storyboard
.instantiateViewControllerWithIdentifier("ImageSearchTableViewController")
as! ImageSearchTableViewController
expect(imageSearchTableViewController.viewModel).notTo(beNil())
}
}
}
}
|
mit
|
leizh007/HiPDA
|
HiPDA/HiPDA/General/Views/ImagePicker/ImagePickerCollectionViewCell.swift
|
1
|
5025
|
//
// ImagePickerCollectionViewCell.swift
// HiPDA
//
// Created by leizh007 on 2017/6/18.
// Copyright © 2017年 HiPDA. All rights reserved.
//
import UIKit
class ImagePickerCollectionViewCell: UICollectionViewCell {
var imageView: UIImageView!
var stateIndicator: ImageSelectorStateIndicator!
var asset: ImageAsset? {
didSet {
if let oldAsset = oldValue {
unsubscribeToDownloadProgressNotification(oldAsset)
}
guard let asset = self.asset else { return }
subscribeToDownloadProgressNotification(asset)
asset.getThumbImage(for: CGSize(width: contentView.bounds.size.width * C.UI.screenScale, height: contentView.bounds.size.height * C.UI.screenScale)) { [weak self] result in
switch result {
case let .success(image):
self?.imageView.image = image
default:
break
}
}
}
}
var assetsCollection: ImageAssetsCollection? {
didSet {
if let oldCollection = oldValue {
unsubscribeToAssetsCollectionDidChange(oldCollection)
}
guard let assetsCollection = assetsCollection else { return }
subscribeToAssetsCollectionDidChange(assetsCollection)
}
}
func updateState() {
guard let asset = asset, let assetsCollection = assetsCollection else {
stateIndicator.clearState()
return
}
stateIndicator.isDownloading = asset.isDownloading
stateIndicator.downloadProgress = asset.downloadPercent
if let index = assetsCollection.index(of: asset) {
stateIndicator.selectionNumber = index + 1
} else {
stateIndicator.selectionNumber = 0
}
}
override init(frame: CGRect) {
imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
stateIndicator = ImageSelectorStateIndicator(frame: .zero)
super.init(frame: frame)
contentView.addSubview(imageView)
contentView.addSubview(stateIndicator)
contentView.backgroundColor = .white
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
imageView.frame = contentView.bounds
stateIndicator.frame = contentView.bounds
}
override func prepareForReuse() {
super.prepareForReuse()
asset?.cancelDownloading()
if let asset = asset {
unsubscribeToDownloadProgressNotification(asset)
}
if let collection = assetsCollection {
unsubscribeToAssetsCollectionDidChange(collection)
}
stateIndicator.clearState()
}
deinit {
asset?.cancelDownloading()
if let asset = asset {
unsubscribeToDownloadProgressNotification(asset)
}
if let collection = assetsCollection {
unsubscribeToAssetsCollectionDidChange(collection)
}
}
fileprivate func subscribeToDownloadProgressNotification(_ asset: ImageAsset) {
NotificationCenter.default.addObserver(self, selector: #selector(didReceiveDownloadProgressNotification(_:)), name: .ImageAssetDownloadProgress, object: asset)
}
fileprivate func unsubscribeToDownloadProgressNotification(_ asset: ImageAsset) {
NotificationCenter.default.removeObserver(self, name: .ImageAssetDownloadProgress, object: asset)
}
func didReceiveDownloadProgressNotification(_ notification: Notification) {
guard let asset = asset else { return }
let isDownloading = asset.isDownloading
let progress = asset.downloadPercent
let isSelected = stateIndicator.isSelected
if (!isSelected) {
stateIndicator.downloadProgress = progress
stateIndicator.isDownloading = isDownloading
}
}
fileprivate func subscribeToAssetsCollectionDidChange(_ assetsCollection: ImageAssetsCollection) {
NotificationCenter.default.addObserver(self, selector: #selector(didReceivedAssetsCollectionChangedNotification(_:)), name: .ImageAssetsCollectionDidChange, object: assetsCollection)
}
fileprivate func unsubscribeToAssetsCollectionDidChange(_ assetsCollection: ImageAssetsCollection) {
NotificationCenter.default.removeObserver(self, name: .ImageAssetsCollectionDidChange, object: assetsCollection)
}
func didReceivedAssetsCollectionChangedNotification(_ notification: Notification) {
guard let asset = asset, !asset.isDownloading else { return }
if let index = assetsCollection?.index(of: asset) {
stateIndicator.selectionNumber = index + 1
} else {
stateIndicator.selectionNumber = 0
}
}
}
|
mit
|
quickthyme/PUTcat
|
PUTcat/Presentation/Service/ViewModel/ServiceViewDataBuilder.swift
|
1
|
1858
|
import UIKit
class ServiceViewDataBuilder {
typealias CellID = ServiceViewDataItem.CellID
typealias SegueID = ServiceViewDataItem.SegueID
typealias Icon = ServiceViewDataItem.Icon
typealias StaticRefID = ServiceViewDataItem.StaticRefID
static func update(viewData: ServiceViewData, withEnvironment environment: PCEnvironment?) -> ServiceViewData {
var viewData = viewData
viewData.section[0] = constructProjectSettingsSection(environment)
return viewData
}
static func constructProjectSettingsSection(_ environment: PCEnvironment?) -> ServiceViewDataSection {
return ServiceViewDataSection(
title: "Project Settings",
item: [
ServiceViewDataItem(
refID: StaticRefID.Environment,
cellID: CellID.TitleValueCell,
title: "Environment",
detail: environment?.name,
segue: nil,
icon: nil
)
]
)
}
static func constructViewData(serviceList: PCList<PCService>) -> ServiceViewData {
let services = serviceList.list
return ServiceViewData(
section: [
constructProjectSettingsSection(nil),
ServiceViewDataSection(
title: "Services",
item: services.map {
ServiceViewDataItem(
refID: $0.id,
cellID: CellID.BasicCell,
title: $0.name,
detail: nil,
segue: SegueID.Transaction,
icon: UIImage(named: Icon.Service)
)
}
)
]
)
}
}
|
apache-2.0
|
simorgh3196/GitHubSearchApp
|
Carthage/Checkouts/Himotoki/Sources/Operators.swift
|
1
|
1527
|
//
// Operators.swift
// Himotoki
//
// Created by Syo Ikeda on 5/2/15.
// Copyright (c) 2015 Syo Ikeda. All rights reserved.
//
infix operator <| { associativity left precedence 150 }
infix operator <|? { associativity left precedence 150 }
infix operator <|| { associativity left precedence 150 }
infix operator <||? { associativity left precedence 150 }
infix operator <|-| { associativity left precedence 150 }
infix operator <|-|? { associativity left precedence 150 }
/// - Throws: DecodeError or an arbitrary ErrorType
public func <| <T: Decodable>(e: Extractor, keyPath: KeyPath) throws -> T {
return try e.value(keyPath)
}
/// - Throws: DecodeError or an arbitrary ErrorType
public func <|? <T: Decodable>(e: Extractor, keyPath: KeyPath) throws -> T? {
return try e.valueOptional(keyPath)
}
/// - Throws: DecodeError or an arbitrary ErrorType
public func <|| <T: Decodable>(e: Extractor, keyPath: KeyPath) throws -> [T] {
return try e.array(keyPath)
}
/// - Throws: DecodeError or an arbitrary ErrorType
public func <||? <T: Decodable>(e: Extractor, keyPath: KeyPath) throws -> [T]? {
return try e.arrayOptional(keyPath)
}
/// - Throws: DecodeError or an arbitrary ErrorType
public func <|-| <T: Decodable>(e: Extractor, keyPath: KeyPath) throws -> [String: T] {
return try e.dictionary(keyPath)
}
/// - Throws: DecodeError or an arbitrary ErrorType
public func <|-|? <T: Decodable>(e: Extractor, keyPath: KeyPath) throws -> [String: T]? {
return try e.dictionaryOptional(keyPath)
}
|
mit
|
qiuncheng/study-for-swift
|
learn-rx-swift/Pods/RxSwift/RxSwift/Observables/Observable+Multiple.swift
|
31
|
17543
|
//
// Observable+Multiple.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/12/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
// MARK: combineLatest
extension Observable {
/**
Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element.
- seealso: [combinelatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html)
- parameter resultSelector: Function to invoke whenever any of the sources produces an element.
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func combineLatest<C: Collection>(_ collection: C, _ resultSelector: @escaping ([C.Iterator.Element.E]) throws -> Element) -> Observable<Element>
where C.Iterator.Element: ObservableType {
return CombineLatestCollectionType(sources: collection, resultSelector: resultSelector)
}
/**
Merges the specified observable sequences into one observable sequence whenever any of the observable sequences produces an element.
- seealso: [combinelatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html)
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func combineLatest<C: Collection>(_ collection: C) -> Observable<[Element]>
where C.Iterator.Element: ObservableType, C.Iterator.Element.E == Element {
return CombineLatestCollectionType(sources: collection, resultSelector: { $0 })
}
}
// MARK: zip
extension Observable {
/**
Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
- seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html)
- parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources.
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func zip<C: Collection>(_ collection: C, _ resultSelector: @escaping ([C.Iterator.Element.E]) throws -> Element) -> Observable<Element>
where C.Iterator.Element: ObservableType {
return ZipCollectionType(sources: collection, resultSelector: resultSelector)
}
/**
Merges the specified observable sequences into one observable sequence whenever all of the observable sequences have produced an element at a corresponding index.
- seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html)
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func zip<C: Collection>(_ collection: C) -> Observable<[Element]>
where C.Iterator.Element: ObservableType, C.Iterator.Element.E == Element {
return ZipCollectionType(sources: collection, resultSelector: { $0 })
}
}
// MARK: switch
extension ObservableType where E : ObservableConvertibleType {
/**
Transforms an observable sequence of observable sequences into an observable sequence
producing values only from the most recent observable sequence.
Each time a new inner observable sequence is received, unsubscribe from the
previous inner observable sequence.
- seealso: [switch operator on reactivex.io](http://reactivex.io/documentation/operators/switch.html)
- returns: The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
public func switchLatest() -> Observable<E.E> {
return Switch(source: asObservable())
}
}
// switchIfEmpty
extension ObservableType {
/**
Returns the elements of the specified sequence or `switchTo` sequence if the sequence is empty.
- seealso: [DefaultIfEmpty operator on reactivex.io](http://reactivex.io/documentation/operators/defaultifempty.html)
- parameter switchTo: Observable sequence being returned when source sequence is empty.
- returns: Observable sequence that contains elements from switchTo sequence if source is empty, otherwise returns source sequence elements.
*/
public func ifEmpty(switchTo other: Observable<E>) -> Observable<E> {
return SwitchIfEmpty(source: asObservable(), ifEmpty: other)
}
}
// MARK: concat
extension ObservableType {
/**
Concatenates the second observable sequence to `self` upon successful termination of `self`.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- parameter second: Second observable sequence.
- returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence.
*/
public func concat<O: ObservableConvertibleType>(_ second: O) -> Observable<E> where O.E == E {
return Observable.concat([self.asObservable(), second.asObservable()])
}
}
extension Observable {
/**
Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully.
This operator has tail recursive optimizations that will prevent stack overflow.
Optimizations will be performed in cases equivalent to following:
[1, [2, [3, .....].concat()].concat].concat()
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat<S: Sequence >(_ sequence: S) -> Observable<Element>
where S.Iterator.Element == Observable<Element> {
return Concat(sources: sequence, count: nil)
}
/**
Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully.
This operator has tail recursive optimizations that will prevent stack overflow.
Optimizations will be performed in cases equivalent to following:
[1, [2, [3, .....].concat()].concat].concat()
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat<S: Collection >(_ collection: S) -> Observable<Element>
where S.Iterator.Element == Observable<Element> {
return Concat(sources: collection, count: collection.count.toIntMax())
}
/**
Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully.
This operator has tail recursive optimizations that will prevent stack overflow.
Optimizations will be performed in cases equivalent to following:
[1, [2, [3, .....].concat()].concat].concat()
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat(_ sources: Observable<Element> ...) -> Observable<Element> {
return Concat(sources: sources, count: sources.count.toIntMax())
}
}
extension ObservableType where E : ObservableConvertibleType {
/**
Concatenates all inner observable sequences, as long as the previous observable sequence terminated successfully.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
public func concat() -> Observable<E.E> {
return merge(maxConcurrent: 1)
}
}
// MARK: merge
extension Observable {
/**
Merges elements from all observable sequences from collection into a single observable sequence.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Collection of observable sequences to merge.
- returns: The observable sequence that merges the elements of the observable sequences.
*/
public static func merge<C: Collection>(_ sources: C) -> Observable<E> where C.Iterator.Element == Observable<E> {
return MergeArray(sources: Array(sources))
}
/**
Merges elements from all observable sequences from array into a single observable sequence.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Array of observable sequences to merge.
- returns: The observable sequence that merges the elements of the observable sequences.
*/
public static func merge(_ sources: [Observable<E>]) -> Observable<E> {
return MergeArray(sources: sources)
}
/**
Merges elements from all observable sequences into a single observable sequence.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Collection of observable sequences to merge.
- returns: The observable sequence that merges the elements of the observable sequences.
*/
public static func merge(_ sources: Observable<E>...) -> Observable<E> {
return MergeArray(sources: sources)
}
}
extension ObservableType where E : ObservableConvertibleType {
/**
Merges elements from all observable sequences in the given enumerable sequence into a single observable sequence.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- returns: The observable sequence that merges the elements of the observable sequences.
*/
public func merge() -> Observable<E.E> {
return Merge(source: asObservable())
}
/**
Merges elements from all inner observable sequences into a single observable sequence, limiting the number of concurrent subscriptions to inner sequences.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter maxConcurrent: Maximum number of inner observable sequences being subscribed to concurrently.
- returns: The observable sequence that merges the elements of the inner sequences.
*/
public func merge(maxConcurrent: Int)
-> Observable<E.E> {
return MergeLimited(source: asObservable(), maxConcurrent: maxConcurrent)
}
}
// MARK: catch
extension ObservableType {
/**
Continues an observable sequence that is terminated by an error with the observable sequence produced by the handler.
- seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html)
- parameter handler: Error handler function, producing another observable sequence.
- returns: An observable sequence containing the source sequence's elements, followed by the elements produced by the handler's resulting observable sequence in case an error occurred.
*/
public func catchError(_ handler: @escaping (Swift.Error) throws -> Observable<E>)
-> Observable<E> {
return Catch(source: asObservable(), handler: handler)
}
/**
Continues an observable sequence that is terminated by an error with a single element.
- seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html)
- parameter element: Last element in an observable sequence in case error occurs.
- returns: An observable sequence containing the source sequence's elements, followed by the `element` in case an error occurred.
*/
public func catchErrorJustReturn(_ element: E)
-> Observable<E> {
return Catch(source: asObservable(), handler: { _ in Observable.just(element) })
}
}
extension Observable {
/**
Continues an observable sequence that is terminated by an error with the next observable sequence.
- seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html)
- returns: An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
*/
public static func catchError<S: Sequence>(_ sequence: S) -> Observable<Element>
where S.Iterator.Element == Observable<Element> {
return CatchSequence(sources: sequence)
}
}
// MARK: takeUntil
extension ObservableType {
/**
Returns the elements from the source observable sequence until the other observable sequence produces an element.
- seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html)
- parameter other: Observable sequence that terminates propagation of elements of the source sequence.
- returns: An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
public func takeUntil<O: ObservableType>(_ other: O)
-> Observable<E> {
return TakeUntil(source: asObservable(), other: other.asObservable())
}
}
// MARK: skipUntil
extension ObservableType {
/**
Returns the elements from the source observable sequence that are emitted after the other observable sequence produces an element.
- seealso: [skipUntil operator on reactivex.io](http://reactivex.io/documentation/operators/skipuntil.html)
- parameter other: Observable sequence that starts propagation of elements of the source sequence.
- returns: An observable sequence containing the elements of the source sequence that are emitted after the other sequence emits an item.
*/
public func skipUntil<O: ObservableType>(_ other: O)
-> Observable<E> {
return SkipUntil(source: asObservable(), other: other.asObservable())
}
}
// MARK: amb
extension ObservableType {
/**
Propagates the observable sequence that reacts first.
- seealso: [amb operator on reactivex.io](http://reactivex.io/documentation/operators/amb.html)
- parameter right: Second observable sequence.
- returns: An observable sequence that surfaces either of the given sequences, whichever reacted first.
*/
public func amb<O2: ObservableType>
(_ right: O2)
-> Observable<E> where O2.E == E {
return Amb(left: asObservable(), right: right.asObservable())
}
}
extension Observable {
/**
Propagates the observable sequence that reacts first.
- seealso: [amb operator on reactivex.io](http://reactivex.io/documentation/operators/amb.html)
- returns: An observable sequence that surfaces any of the given sequences, whichever reacted first.
*/
public static func amb<S: Sequence>(_ sequence: S) -> Observable<Element>
where S.Iterator.Element == Observable<Element> {
return sequence.reduce(Observable<S.Iterator.Element.E>.never()) { a, o in
return a.amb(o.asObservable())
}
}
}
// withLatestFrom
extension ObservableType {
/**
Merges two observable sequences into one observable sequence by combining each element from self with the latest element from the second source, if any.
- seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html)
- parameter second: Second observable source.
- parameter resultSelector: Function to invoke for each element from the self combined with the latest element from the second source, if any.
- returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function.
*/
public func withLatestFrom<SecondO: ObservableConvertibleType, ResultType>(_ second: SecondO, resultSelector: @escaping (E, SecondO.E) throws -> ResultType) -> Observable<ResultType> {
return WithLatestFrom(first: asObservable(), second: second.asObservable(), resultSelector: resultSelector)
}
/**
Merges two observable sequences into one observable sequence by using latest element from the second sequence every time when `self` emitts an element.
- seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html)
- parameter second: Second observable source.
- returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function.
*/
public func withLatestFrom<SecondO: ObservableConvertibleType>(_ second: SecondO) -> Observable<SecondO.E> {
return WithLatestFrom(first: asObservable(), second: second.asObservable(), resultSelector: { $1 })
}
}
|
mit
|
programus/this-month
|
src/This Month/Widget/TodayViewController.swift
|
1
|
1543
|
//
// TodayViewController.swift
// Widget
//
// Created by 王 元 on 15-02-01.
// Copyright (c) 2015年 programus. All rights reserved.
//
import Cocoa
import NotificationCenter
class TodayViewController: NSViewController, NCWidgetProviding {
@IBOutlet weak var datePickerCell: NSDatePickerCell!
override var nibName: String? {
return "TodayViewController"
}
func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)!) {
// Update your data and prepare for a snapshot. Call completion handler when you are done
// with NoData if nothing has changed or NewData if there is new data since the last
// time we called you
var now = NSDate()
var needRefresh = true
if let cal = NSCalendar(calendarIdentifier: NSGregorianCalendar) {
var nowComp = cal.components(NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitDay, fromDate: now)
var dispComp = cal.components(NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitDay, fromDate: self.datePickerCell.dateValue)
if nowComp == dispComp {
needRefresh = nowComp.year != dispComp.year || nowComp.month != dispComp.month || nowComp.day != dispComp.day
}
if needRefresh {
self.datePickerCell.dateValue = now
}
}
completionHandler(needRefresh ? .NewData : .NoData)
}
}
|
apache-2.0
|
k-thorat/Dotzu
|
Framework/Dotzu/Dotzu/LoggerFormat.swift
|
1
|
2167
|
//
// LoggerFormat.swift
// exampleWindow
//
// Created by Remi Robert on 23/01/2017.
// Copyright © 2017 Remi Robert. All rights reserved.
//
import UIKit
class LoggerFormat {
static func formatDate(date: Date) -> String {
let formatter = DateFormatter()
formatter.timeZone = TimeZone.current
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return formatter.string(from: date)
}
static func format(log: Log) -> (str: String, attr: NSMutableAttributedString) {
var startIndex = 0
var lenghtDate: Int?
let stringContent = NSMutableString()
stringContent.append("\(log.level.logColorConsole) ")
if let date = log.date, LogsSettings.shared.date {
stringContent.append("[\(formatDate(date: date))] ")
lenghtDate = stringContent.length
startIndex = stringContent.length
}
if let fileInfoString = log.fileInfo, LogsSettings.shared.fileInfo {
stringContent.append("\(fileInfoString) : \(log.content)")
} else {
stringContent.append("\(log.content)")
}
let attstr = NSMutableAttributedString(string: stringContent as String)
attstr.addAttribute(NSAttributedString.Key.foregroundColor,
value: UIColor.white,
range: NSMakeRange(0, stringContent.length))
if let dateLenght = lenghtDate {
let range = NSMakeRange(0, dateLenght)
attstr.addAttribute(NSAttributedString.Key.foregroundColor, value: Color.mainGreen, range: range)
attstr.addAttribute(NSAttributedString.Key.font, value: UIFont.boldSystemFont(ofSize: 12), range: range)
}
if let fileInfoString = log.fileInfo, LogsSettings.shared.fileInfo {
let range = NSMakeRange(startIndex, fileInfoString.count)
attstr.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.gray, range: range)
attstr.addAttribute(NSAttributedString.Key.font, value: UIFont.boldSystemFont(ofSize: 12), range: range)
}
return (stringContent as String, attstr)
}
}
|
mit
|
uasys/swift
|
test/refactoring/ExtractFunction/throw_errors.swift
|
5
|
1041
|
func foo1() throws -> Int { return 0 }
enum MyError : Error {
case E1
case E2
}
func foo2() throws {
try foo1()
try! foo1()
do {
try foo1()
} catch {}
do {
try foo1()
} catch MyError.E1 {
} catch MyError.E2 {
}
}
// RUN: rm -rf %t.result && mkdir -p %t.result
// RUN: %refactor -extract-function -source-filename %s -pos=8:1 -end-pos=8:13 >> %t.result/L8-8.swift
// RUN: diff -u %S/Outputs/throw_errors/L8-8.swift.expected %t.result/L8-8.swift
// RUN: %refactor -extract-function -source-filename %s -pos=9:1 -end-pos=9:14 >> %t.result/L9-9.swift
// RUN: diff -u %S/Outputs/throw_errors/L9-9.swift.expected %t.result/L9-9.swift
// RUN: %refactor -extract-function -source-filename %s -pos=10:1 -end-pos=12:13 >> %t.result/L10-12.swift
// RUN: diff -u %S/Outputs/throw_errors/L10-12.swift.expected %t.result/L10-12.swift
// RUN: %refactor -extract-function -source-filename %s -pos=13:1 -end-pos=17:4 >> %t.result/L13-17.swift
// RUN: diff -u %S/Outputs/throw_errors/L13-17.swift.expected %t.result/L13-17.swift
|
apache-2.0
|
tjw/swift
|
test/attr/attr_iboutlet.swift
|
2
|
8609
|
// RUN: %target-typecheck-verify-swift
// REQUIRES: objc_interop
import Foundation
@IBOutlet // expected-error {{only instance properties can be declared @IBOutlet}} {{1-11=}}
var iboutlet_global: Int
@IBOutlet // expected-error {{@IBOutlet may only be used on 'var' declarations}} {{1-11=}}
class IBOutletClassTy {}
@IBOutlet // expected-error {{@IBOutlet may only be used on 'var' declarations}} {{1-11=}}
struct IBStructTy {}
@IBOutlet // expected-error {{@IBOutlet may only be used on 'var' declarations}} {{1-11=}}
func IBFunction() -> () {}
@objc
class IBOutletWrapperTy {
@IBOutlet
var value : IBOutletWrapperTy! = IBOutletWrapperTy() // no-warning
@IBOutlet
class var staticValue: IBOutletWrapperTy = 52 // expected-error {{cannot convert value of type 'Int' to specified type 'IBOutletWrapperTy'}}
// expected-error@-2 {{only instance properties can be declared @IBOutlet}} {{3-12=}}
// expected-error@-2 {{class stored properties not supported}}
@IBOutlet // expected-error {{@IBOutlet may only be used on 'var' declarations}} {{3-13=}}
func click() -> () {}
@IBOutlet // expected-error {{@IBOutlet attribute requires property to be mutable}} {{3-13=}}
let immutable: IBOutletWrapperTy? = nil
@IBOutlet // expected-error {{@IBOutlet attribute requires property to be mutable}} {{3-13=}}
var computedImmutable: IBOutletWrapperTy? {
return nil
}
}
struct S { }
enum E { }
protocol P1 { }
protocol P2 { }
protocol CP1 : class { }
protocol CP2 : class { }
@objc protocol OP1 { }
@objc protocol OP2 { }
class NonObjC {}
// Check where @IBOutlet can occur
@objc class X {
// Class type
@IBOutlet var outlet2: X?
@IBOutlet var outlet3: X!
@IBOutlet var outlet1a: NonObjC // expected-error{{@IBOutlet property cannot have non-'@objc' class type 'NonObjC'}} {{3-13=}}
@IBOutlet var outlet2a: NonObjC? // expected-error{{@IBOutlet property cannot have non-'@objc' class type 'NonObjC'}} {{3-13=}}
@IBOutlet var outlet3a: NonObjC! // expected-error{{@IBOutlet property cannot have non-'@objc' class type 'NonObjC'}} {{3-13=}}
// AnyObject
@IBOutlet var outlet5: AnyObject?
@IBOutlet var outlet6: AnyObject!
// Any
@IBOutlet var outlet5a: Any?
@IBOutlet var outlet6a: Any!
// Protocol types
@IBOutlet var outlet7: P1 // expected-error{{@IBOutlet property cannot have non-'@objc' protocol type 'P1'}} {{3-13=}}
@IBOutlet var outlet8: CP1 // expected-error{{@IBOutlet property cannot have non-'@objc' protocol type 'CP1'}} {{3-13=}}
@IBOutlet var outlet10: P1? // expected-error{{@IBOutlet property cannot have non-'@objc' protocol type}} {{3-13=}}
@IBOutlet var outlet11: CP1? // expected-error{{@IBOutlet property cannot have non-'@objc' protocol type}} {{3-13=}}
@IBOutlet var outlet12: OP1?
@IBOutlet var outlet13: P1! // expected-error{{@IBOutlet property cannot have non-'@objc' protocol type}} {{3-13=}}
@IBOutlet var outlet14: CP1! // expected-error{{@IBOutlet property cannot have non-'@objc' protocol type}} {{3-13=}}
@IBOutlet var outlet15: OP1!
// Class metatype
@IBOutlet var outlet15b: X.Type // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}}
@IBOutlet var outlet16: X.Type? // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}}
@IBOutlet var outlet17: X.Type! // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}}
// AnyClass
@IBOutlet var outlet18: AnyClass // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}}
@IBOutlet var outlet19: AnyClass? // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}}
@IBOutlet var outlet20: AnyClass! // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}}
// Protocol types
@IBOutlet var outlet21: P1.Type // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}}
@IBOutlet var outlet22: CP1.Type // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}}
@IBOutlet var outlet23: OP1.Type // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}}
@IBOutlet var outlet24: P1.Type? // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}}
@IBOutlet var outlet25: CP1.Type? // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}}
@IBOutlet var outlet26: OP1.Type? // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}}
@IBOutlet var outlet27: P1.Type! // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}}
@IBOutlet var outlet28: CP1.Type! // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}}
@IBOutlet var outlet29: OP1.Type! // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}}
// weak/unowned
@IBOutlet weak var outlet30: X?
@IBOutlet weak var outlet31: X!
// String
@IBOutlet var outlet33: String?
@IBOutlet var outlet34: String!
// Other bad cases
@IBOutlet var outlet35: S // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}}
@IBOutlet var outlet36: E // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}}
@IBOutlet var outlet37: (X, X) // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}}
@IBOutlet var outlet38: Int // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}}
@IBOutlet var collection1b: [AnyObject]?
@IBOutlet var collection1c: [AnyObject]!
@IBOutlet var collection2b: [X]?
@IBOutlet var collection2c: [X]!
@IBOutlet var collection3b: [OP1]?
@IBOutlet var collection3c: [OP1]!
@IBOutlet var collection4a: [CP1] // expected-error{{@IBOutlet property cannot be an array of non-'@objc' protocol type}} {{3-13=}}
@IBOutlet var collection4b: ([CP1])? // expected-error{{@IBOutlet property cannot be an array of non-'@objc' protocol type}} {{3-13=}}
@IBOutlet var collection4c: ([CP1])! // expected-error{{@IBOutlet property cannot be an array of non-'@objc' protocol type}} {{3-13=}}
@IBOutlet var collection5b: ([String])?
@IBOutlet var collection5c: ([String])!
@IBOutlet var collection6a: [NonObjC] // expected-error{{@IBOutlet property cannot be an array of non-'@objc' class type}} {{3-13=}}
@IBOutlet var collection6b: ([NonObjC])? // expected-error{{@IBOutlet property cannot be an array of non-'@objc' class type}} {{3-13=}}
@IBOutlet var collection6c: ([NonObjC])! // expected-error{{@IBOutlet property cannot be an array of non-'@objc' class type}} {{3-13=}}
init() { }
}
@objc class Infer {
@IBOutlet var outlet1: Infer!
@IBOutlet weak var outlet2: Infer!
func testOptionalNess() {
_ = outlet1!
_ = outlet2!
}
func testUnchecked() {
_ = outlet1
_ = outlet2
}
// This outlet is strong and optional.
@IBOutlet var outlet4: AnyObject?
func testStrong() {
if outlet4 != nil {}
}
}
@objc class C {
}
@objc protocol Proto {
}
class SwiftGizmo {
@IBOutlet var a : C!
@IBOutlet var b1 : [C]
@IBOutlet var b2 : [C]!
@IBOutlet var c : String!
@IBOutlet var d : [String]!
@IBOutlet var e : Proto!
@IBOutlet var f : C?
@IBOutlet var g : C!
@IBOutlet weak var h : C?
@IBOutlet weak var i : C!
@IBOutlet unowned var j : C // expected-error{{@IBOutlet property has non-optional type 'C'}}
// expected-note @-1{{add '?' to form the optional type 'C?'}}{{30-30=?}}
// expected-note @-2{{add '!' to form an implicitly unwrapped optional}}{{30-30=!}}
@IBOutlet unowned(unsafe) var k : C // expected-error{{@IBOutlet property has non-optional type 'C'}}
// expected-note @-1{{add '?' to form the optional type 'C?'}}{{38-38=?}}
// expected-note @-2{{add '!' to form an implicitly unwrapped optional}}{{38-38=!}}
@IBOutlet var bad1 : Int // expected-error {{@IBOutlet property cannot have non-object type 'Int'}} {{3-13=}}
@IBOutlet var dup: C! // expected-note{{'dup' previously declared here}}
@IBOutlet var dup: C! // expected-error{{invalid redeclaration of 'dup'}}
init() {}
}
class MissingOptional {
@IBOutlet var a: C // expected-error{{@IBOutlet property has non-optional type 'C'}}
// expected-note @-1{{add '?' to form the optional type 'C?'}}{{21-21=?}}
// expected-note @-2{{add '!' to form an implicitly unwrapped optional}}{{21-21=!}}
@IBOutlet weak var b: C // expected-error{{@IBOutlet property has non-optional type 'C'}}
// expected-note @-1{{add '!' to form an implicitly unwrapped optional}} {{26-26=!}}
// expected-note @-2{{add '?' to form the optional type 'C?'}} {{26-26=?}}
init() {}
}
|
apache-2.0
|
smartystreets/smartystreets-ios-sdk
|
Sources/SmartyStreets/InternationalStreet/InternationalStreetChanges.swift
|
1
|
1667
|
import Foundation
@objcMembers public class InternationalStreetChanges: NSObject, Codable {
public var organization:String?
public var address1:String?
public var address2:String?
public var address3:String?
public var address4:String?
public var address5:String?
public var address6:String?
public var address7:String?
public var address8:String?
public var address9:String?
public var address10:String?
public var address11:String?
public var address12:String?
public var components:InternationalStreetComponents?
init(dictionary: NSDictionary) {
self.organization = dictionary["organization"] as? String
self.address1 = dictionary["address1"] as? String
self.address2 = dictionary["address2"] as? String
self.address3 = dictionary["address3"] as? String
self.address4 = dictionary["address4"] as? String
self.address5 = dictionary["address5"] as? String
self.address6 = dictionary["address6"] as? String
self.address7 = dictionary["address7"] as? String
self.address8 = dictionary["address8"] as? String
self.address9 = dictionary["address9"] as? String
self.address10 = dictionary["address10"] as? String
self.address11 = dictionary["address11"] as? String
self.address12 = dictionary["address12"] as? String
if let components = dictionary["components"] {
self.components = InternationalStreetComponents(dictionary: components as! NSDictionary)
} else {
self.components = InternationalStreetComponents(dictionary: NSDictionary())
}
}
}
|
apache-2.0
|
ashfurrow/Nimble
|
Tests/Nimble/AsynchronousTest.swift
|
22
|
7550
|
import Foundation
import XCTest
import Nimble
// These tests require the ObjC runtimes do not currently have the GCD and run loop facilities
// required for working with Nimble's async matchers
#if _runtime(_ObjC)
class AsyncTest: XCTestCase, XCTestCaseProvider {
var allTests: [(String, () throws -> Void)] {
return [
("testToEventuallyPositiveMatches", testToEventuallyPositiveMatches),
("testToEventuallyNegativeMatches", testToEventuallyNegativeMatches),
("testWaitUntilPositiveMatches", testWaitUntilPositiveMatches),
("testToEventuallyWithCustomDefaultTimeout", testToEventuallyWithCustomDefaultTimeout),
("testWaitUntilTimesOutIfNotCalled", testWaitUntilTimesOutIfNotCalled),
("testWaitUntilTimesOutWhenExceedingItsTime", testWaitUntilTimesOutWhenExceedingItsTime),
("testWaitUntilNegativeMatches", testWaitUntilNegativeMatches),
("testWaitUntilDetectsStalledMainThreadActivity", testWaitUntilDetectsStalledMainThreadActivity),
("testCombiningAsyncWaitUntilAndToEventuallyIsNotAllowed", testCombiningAsyncWaitUntilAndToEventuallyIsNotAllowed),
("testWaitUntilErrorsIfDoneIsCalledMultipleTimes", testWaitUntilErrorsIfDoneIsCalledMultipleTimes),
("testWaitUntilMustBeInMainThread", testWaitUntilMustBeInMainThread),
("testToEventuallyMustBeInMainThread", testToEventuallyMustBeInMainThread),
]
}
let errorToThrow = NSError(domain: NSInternalInconsistencyException, code: 42, userInfo: nil)
private func doThrowError() throws -> Int {
throw errorToThrow
}
func testToEventuallyPositiveMatches() {
var value = 0
deferToMainQueue { value = 1 }
expect { value }.toEventually(equal(1))
deferToMainQueue { value = 0 }
expect { value }.toEventuallyNot(equal(1))
}
func testToEventuallyNegativeMatches() {
let value = 0
failsWithErrorMessage("expected to eventually not equal <0>, got <0>") {
expect { value }.toEventuallyNot(equal(0))
}
failsWithErrorMessage("expected to eventually equal <1>, got <0>") {
expect { value }.toEventually(equal(1))
}
failsWithErrorMessage("expected to eventually equal <1>, got an unexpected error thrown: <\(errorToThrow)>") {
expect { try self.doThrowError() }.toEventually(equal(1))
}
failsWithErrorMessage("expected to eventually not equal <0>, got an unexpected error thrown: <\(errorToThrow)>") {
expect { try self.doThrowError() }.toEventuallyNot(equal(0))
}
}
func testToEventuallyWithCustomDefaultTimeout() {
AsyncDefaults.Timeout = 2
defer {
AsyncDefaults.Timeout = 1
}
var value = 0
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
NSThread.sleepForTimeInterval(1.1)
value = 1
}
expect { value }.toEventually(equal(1))
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
NSThread.sleepForTimeInterval(1.1)
value = 0
}
expect { value }.toEventuallyNot(equal(1))
}
func testWaitUntilPositiveMatches() {
waitUntil { done in
done()
}
waitUntil { done in
deferToMainQueue {
done()
}
}
}
func testWaitUntilTimesOutIfNotCalled() {
failsWithErrorMessage("Waited more than 1.0 second") {
waitUntil(timeout: 1) { done in return }
}
}
func testWaitUntilTimesOutWhenExceedingItsTime() {
var waiting = true
failsWithErrorMessage("Waited more than 0.01 seconds") {
waitUntil(timeout: 0.01) { done in
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
NSThread.sleepForTimeInterval(0.1)
done()
waiting = false
}
}
}
// "clear" runloop to ensure this test doesn't poison other tests
repeat {
NSRunLoop.mainRunLoop().runUntilDate(NSDate().dateByAddingTimeInterval(0.2))
} while(waiting)
}
func testWaitUntilNegativeMatches() {
failsWithErrorMessage("expected to equal <2>, got <1>") {
waitUntil { done in
NSThread.sleepForTimeInterval(0.1)
expect(1).to(equal(2))
done()
}
}
}
func testWaitUntilDetectsStalledMainThreadActivity() {
let msg = "-waitUntil() timed out but was unable to run the timeout handler because the main thread is unresponsive (0.5 seconds is allow after the wait times out). Conditions that may cause this include processing blocking IO on the main thread, calls to sleep(), deadlocks, and synchronous IPC. Nimble forcefully stopped run loop which may cause future failures in test run."
failsWithErrorMessage(msg) {
waitUntil(timeout: 1) { done in
NSThread.sleepForTimeInterval(5.0)
done()
}
}
}
func testCombiningAsyncWaitUntilAndToEventuallyIsNotAllowed() {
// Currently we are unable to catch Objective-C exceptions when built by the Swift Package Manager
#if !SWIFT_PACKAGE
let referenceLine = #line + 9
var msg = "Unexpected exception raised: Nested async expectations are not allowed "
msg += "to avoid creating flaky tests."
msg += "\n\n"
msg += "The call to\n\t"
msg += "expect(...).toEventually(...) at \(#file):\(referenceLine + 7)\n"
msg += "triggered this exception because\n\t"
msg += "waitUntil(...) at \(#file):\(referenceLine + 1)\n"
msg += "is currently managing the main run loop."
failsWithErrorMessage(msg) { // reference line
waitUntil(timeout: 2.0) { done in
var protected: Int = 0
dispatch_async(dispatch_get_main_queue()) {
protected = 1
}
expect(protected).toEventually(equal(1))
done()
}
}
#endif
}
func testWaitUntilErrorsIfDoneIsCalledMultipleTimes() {
#if !SWIFT_PACKAGE
waitUntil { done in
deferToMainQueue {
done()
expect {
done()
}.to(raiseException(named: "InvalidNimbleAPIUsage"))
}
}
#endif
}
func testWaitUntilMustBeInMainThread() {
#if !SWIFT_PACKAGE
var executedAsyncBlock: Bool = false
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
expect {
waitUntil { done in done() }
}.to(raiseException(named: "InvalidNimbleAPIUsage"))
executedAsyncBlock = true
}
expect(executedAsyncBlock).toEventually(beTruthy())
#endif
}
func testToEventuallyMustBeInMainThread() {
#if !SWIFT_PACKAGE
var executedAsyncBlock: Bool = false
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
expect {
expect(1).toEventually(equal(2))
}.to(raiseException(named: "InvalidNimbleAPIUsage"))
executedAsyncBlock = true
}
expect(executedAsyncBlock).toEventually(beTruthy())
#endif
}
}
#endif
|
apache-2.0
|
codestergit/swift
|
test/Constraints/closures.swift
|
4
|
18206
|
// RUN: %target-typecheck-verify-swift
func myMap<T1, T2>(_ array: [T1], _ fn: (T1) -> T2) -> [T2] {}
var intArray : [Int]
_ = myMap(intArray, { String($0) })
_ = myMap(intArray, { x -> String in String(x) } )
// Closures with too few parameters.
func foo(_ x: (Int, Int) -> Int) {}
foo({$0}) // expected-error{{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 1 was used in closure body}}
struct X {}
func mySort(_ array: [String], _ predicate: (String, String) -> Bool) -> [String] {}
func mySort(_ array: [X], _ predicate: (X, X) -> Bool) -> [X] {}
var strings : [String]
_ = mySort(strings, { x, y in x < y })
// Closures with inout arguments.
func f0<T, U>(_ t: T, _ f: (inout T) -> U) -> U {
var t2 = t
return f(&t2)
}
struct X2 {
func g() -> Float { return 0 }
}
_ = f0(X2(), {$0.g()})
// Autoclosure
func f1(f: @autoclosure () -> Int) { }
func f2() -> Int { }
f1(f: f2) // expected-error{{function produces expected type 'Int'; did you mean to call it with '()'?}}{{9-9=()}}
f1(f: 5)
// Ternary in closure
var evenOrOdd : (Int) -> String = {$0 % 2 == 0 ? "even" : "odd"}
// <rdar://problem/15367882>
func foo() {
not_declared({ $0 + 1 }) // expected-error{{use of unresolved identifier 'not_declared'}}
}
// <rdar://problem/15536725>
struct X3<T> {
init(_: (T) -> ()) {}
}
func testX3(_ x: Int) {
var x = x
_ = X3({ x = $0 })
_ = x
}
// <rdar://problem/13811882>
func test13811882() {
var _ : (Int) -> (Int, Int) = {($0, $0)}
var x = 1
var _ : (Int) -> (Int, Int) = {($0, x)}
x = 2
}
// <rdar://problem/21544303> QoI: "Unexpected trailing closure" should have a fixit to insert a 'do' statement
// <https://bugs.swift.org/browse/SR-3671>
func r21544303() {
var inSubcall = true
{
} // expected-error {{computed property must have accessors specified}}
inSubcall = false
// This is a problem, but isn't clear what was intended.
var somethingElse = true {
} // expected-error {{computed property must have accessors specified}}
inSubcall = false
var v2 : Bool = false
v2 = inSubcall
{ // expected-error {{cannot call value of non-function type 'Bool'}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }}
}
}
// <https://bugs.swift.org/browse/SR-3671>
func SR3671() {
let n = 42
func consume(_ x: Int) {}
{ consume($0) }(42)
;
({ $0(42) } { consume($0) }) // expected-note {{callee is here}}
{ print(42) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }} expected-error {{cannot call value of non-function type '()'}}
;
({ $0(42) } { consume($0) }) // expected-note {{callee is here}}
{ print($0) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}}
;
({ $0(42) } { consume($0) }) // expected-note {{callee is here}}
{ [n] in print(42) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}}
;
({ $0(42) } { consume($0) }) // expected-note {{callee is here}}
{ consume($0) }(42) // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}}
;
({ $0(42) } { consume($0) }) // expected-note {{callee is here}}
{ (x: Int) in consume(x) }(42) // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}}
;
// This is technically a valid call, so nothing goes wrong until (42)
{ $0(3) }
{ consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}}
;
({ $0(42) })
{ consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}}
;
{ $0(3) }
{ [n] in consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}}
;
({ $0(42) })
{ [n] in consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}}
;
// Equivalent but more obviously unintended.
{ $0(3) } // expected-note {{callee is here}}
{ consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}}
// expected-warning@-1 {{braces here form a trailing closure separated from its callee by multiple newlines}}
({ $0(3) }) // expected-note {{callee is here}}
{ consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}}
// expected-warning@-1 {{braces here form a trailing closure separated from its callee by multiple newlines}}
;
// Also a valid call (!!)
{ $0 { $0 } } { $0 { 1 } } // expected-error {{expression resolves to an unused function}}
consume(111)
}
// <rdar://problem/22162441> Crash from failing to diagnose nonexistent method access inside closure
func r22162441(_ lines: [String]) {
_ = lines.map { line in line.fooBar() } // expected-error {{value of type 'String' has no member 'fooBar'}}
_ = lines.map { $0.fooBar() } // expected-error {{value of type 'String' has no member 'fooBar'}}
}
func testMap() {
let a = 42
[1,a].map { $0 + 1.0 } // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (Double, Double), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}}
}
// <rdar://problem/22414757> "UnresolvedDot" "in wrong phase" assertion from verifier
[].reduce { $0 + $1 } // expected-error {{missing argument for parameter #1 in call}}
// <rdar://problem/22333281> QoI: improve diagnostic when contextual type of closure disagrees with arguments
var _: () -> Int = {0}
// expected-error @+1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{24-24=_ in }}
var _: (Int) -> Int = {0}
// expected-error @+1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{24-24= _ in}}
var _: (Int) -> Int = { 0 }
// expected-error @+1 {{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{29-29=_,_ in }}
var _: (Int, Int) -> Int = {0}
// expected-error @+1 {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 3 were used in closure body}}
var _: (Int,Int) -> Int = {$0+$1+$2}
// expected-error @+1 {{contextual closure type '(Int, Int, Int) -> Int' expects 3 arguments, but 2 were used in closure body}}
var _: (Int, Int, Int) -> Int = {$0+$1}
var _: () -> Int = {a in 0}
// expected-error @+1 {{contextual closure type '(Int) -> Int' expects 1 argument, but 2 were used in closure body}}
var _: (Int) -> Int = {a,b in 0}
// expected-error @+1 {{contextual closure type '(Int) -> Int' expects 1 argument, but 3 were used in closure body}}
var _: (Int) -> Int = {a,b,c in 0}
var _: (Int, Int) -> Int = {a in 0}
// expected-error @+1 {{contextual closure type '(Int, Int, Int) -> Int' expects 3 arguments, but 2 were used in closure body}}
var _: (Int, Int, Int) -> Int = {a, b in a+b}
// <rdar://problem/15998821> Fail to infer types for closure that takes an inout argument
func r15998821() {
func take_closure(_ x : (inout Int) -> ()) { }
func test1() {
take_closure { (a : inout Int) in
a = 42
}
}
func test2() {
take_closure { a in
a = 42
}
}
func withPtr(_ body: (inout Int) -> Int) {}
func f() { withPtr { p in return p } }
let g = { x in x = 3 }
take_closure(g)
}
// <rdar://problem/22602657> better diagnostics for closures w/o "in" clause
var _: (Int,Int) -> Int = {$0+$1+$2} // expected-error {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 3 were used in closure body}}
// Crash when re-typechecking bodies of non-single expression closures
struct CC {}
func callCC<U>(_ f: (CC) -> U) -> () {}
func typeCheckMultiStmtClosureCrash() {
callCC { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{11-11= () -> Int in }}
_ = $0
return 1
}
}
// SR-832 - both these should be ok
func someFunc(_ foo: ((String) -> String)?,
bar: @escaping (String) -> String) {
let _: (String) -> String = foo != nil ? foo! : bar
let _: (String) -> String = foo ?? bar
}
// SR-1069 - Error diagnostic refers to wrong argument
class SR1069_W<T> {
func append<Key: AnyObject>(value: T, forKey key: Key) where Key: Hashable {}
}
class SR1069_C<T> { let w: SR1069_W<(AnyObject, T) -> ()> = SR1069_W() }
struct S<T> {
let cs: [SR1069_C<T>] = []
func subscribe<Object: AnyObject>(object: Object?, method: (Object, T) -> ()) where Object: Hashable {
let wrappedMethod = { (object: AnyObject, value: T) in }
// expected-error @+1 {{value of optional type 'Object?' not unwrapped; did you mean to use '!' or '?'?}}
cs.forEach { $0.w.append(value: wrappedMethod, forKey: object) }
}
}
// Make sure we cannot infer an () argument from an empty parameter list.
func acceptNothingToInt (_: () -> Int) {}
func testAcceptNothingToInt(ac1: @autoclosure () -> Int) {
acceptNothingToInt({ac1($0)})
// expected-error@-1{{contextual closure type '() -> Int' expects 0 arguments, but 1 was used in closure body}}
}
// <rdar://problem/23570873> QoI: Poor error calling map without being able to infer "U" (closure result inference)
struct Thing {
init?() {}
}
// This throws a compiler error
let things = Thing().map { thing in // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{34-34=-> (Thing) }}
// Commenting out this makes it compile
_ = thing
return thing
}
// <rdar://problem/21675896> QoI: [Closure return type inference] Swift cannot find members for the result of inlined lambdas with branches
func r21675896(file : String) {
let x: String = { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{20-20= () -> String in }}
if true {
return "foo"
}
else {
return file
}
}().pathExtension
}
// <rdar://problem/19870975> Incorrect diagnostic for failed member lookups within closures passed as arguments ("(_) -> _")
func ident<T>(_ t: T) -> T {}
var c = ident({1.DOESNT_EXIST}) // error: expected-error {{value of type 'Int' has no member 'DOESNT_EXIST'}}
// <rdar://problem/20712541> QoI: Int/UInt mismatch produces useless error inside a block
var afterMessageCount : Int?
func uintFunc() -> UInt {}
func takeVoidVoidFn(_ a : () -> ()) {}
takeVoidVoidFn { () -> Void in
afterMessageCount = uintFunc() // expected-error {{cannot assign value of type 'UInt' to type 'Int?'}}
}
// <rdar://problem/19997471> Swift: Incorrect compile error when calling a function inside a closure
func f19997471(_ x: String) {}
func f19997471(_ x: Int) {}
func someGeneric19997471<T>(_ x: T) {
takeVoidVoidFn {
f19997471(x) // expected-error {{cannot invoke 'f19997471' with an argument list of type '(T)'}}
// expected-note @-1 {{overloads for 'f19997471' exist with these partially matching parameter lists: (String), (Int)}}
}
}
// <rdar://problem/20371273> Type errors inside anonymous functions don't provide enough information
func f20371273() {
let x: [Int] = [1, 2, 3, 4]
let y: UInt = 4
x.filter { $0 == y } // expected-error {{binary operator '==' cannot be applied to operands of type 'Int' and 'UInt'}}
// expected-note @-1 {{overloads for '==' exist with these partially matching parameter lists: (UInt, UInt), (Int, Int)}}
}
// <rdar://problem/20921068> Swift fails to compile: [0].map() { _ in let r = (1,2).0; return r }
[0].map { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{5-5=-> Int }}
_ in
let r = (1,2).0
return r
}
// <rdar://problem/21078316> Less than useful error message when using map on optional dictionary type
func rdar21078316() {
var foo : [String : String]?
var bar : [(String, String)]?
bar = foo.map { ($0, $1) } // expected-error {{contextual closure type '([String : String]) -> [(String, String)]' expects 1 argument, but 2 were used in closure body}}
}
// <rdar://problem/20978044> QoI: Poor diagnostic when using an incorrect tuple element in a closure
var numbers = [1, 2, 3]
zip(numbers, numbers).filter { $0.2 > 1 } // expected-error {{value of tuple type '(Int, Int)' has no member '2'}}
// <rdar://problem/20868864> QoI: Cannot invoke 'function' with an argument list of type 'type'
func foo20868864(_ callback: ([String]) -> ()) { }
func rdar20868864(_ s: String) {
var s = s
foo20868864 { (strings: [String]) in
s = strings // expected-error {{cannot assign value of type '[String]' to type 'String'}}
}
}
// <rdar://problem/22058555> crash in cs diags in withCString
func r22058555() {
var firstChar: UInt8 = 0
"abc".withCString { chars in
firstChar = chars[0] // expected-error {{cannot assign value of type 'Int8' to type 'UInt8'}}
}
}
// <rdar://problem/20789423> Unclear diagnostic for multi-statement closure with no return type
func r20789423() {
class C {
func f(_ value: Int) { }
}
let p: C
print(p.f(p)()) // expected-error {{cannot convert value of type 'C' to expected argument type 'Int'}}
let _f = { (v: Int) in // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{23-23=-> String }}
print("a")
return "hi"
}
}
// Make sure that behavior related to allowing trailing closures to match functions
// with Any as a final parameter is the same after the changes made by SR-2505, namely:
// that we continue to select function that does _not_ have Any as a final parameter in
// presence of other possibilities.
protocol SR_2505_Initable { init() }
struct SR_2505_II : SR_2505_Initable {}
protocol P_SR_2505 {
associatedtype T: SR_2505_Initable
}
extension P_SR_2505 {
func test(it o: (T) -> Bool) -> Bool {
return o(T.self())
}
}
class C_SR_2505 : P_SR_2505 {
typealias T = SR_2505_II
func test(_ o: Any) -> Bool {
return false
}
func call(_ c: C_SR_2505) -> Bool {
// Note: no diagnostic about capturing 'self', because this is a
// non-escaping closure -- that's how we know we have selected
// test(it:) and not test(_)
return c.test { o in test(o) }
}
}
let _ = C_SR_2505().call(C_SR_2505())
// <rdar://problem/28909024> Returning incorrect result type from method invocation can result in nonsense diagnostic
extension Collection {
func r28909024(_ predicate: (Iterator.Element)->Bool) -> Index {
return startIndex
}
}
func fn_r28909024(n: Int) {
return (0..<10).r28909024 { // expected-error {{unexpected non-void return value in void function}}
_ in true
}
}
// SR-2994: Unexpected ambiguous expression in closure with generics
struct S_2994 {
var dataOffset: Int
}
class C_2994<R> {
init(arg: (R) -> Void) {}
}
func f_2994(arg: String) {}
func g_2994(arg: Int) -> Double {
return 2
}
C_2994<S_2994>(arg: { (r: S_2994) in f_2994(arg: g_2994(arg: r.dataOffset)) }) // expected-error {{cannot convert value of type 'Double' to expected argument type 'String'}}
let _ = { $0[$1] }(1, 1) // expected-error {{cannot subscript a value of incorrect or ambiguous type}}
let _ = { $0 = ($0 = {}) } // expected-error {{assigning a variable to itself}}
let _ = { $0 = $0 = 42 } // expected-error {{assigning a variable to itself}}
// https://bugs.swift.org/browse/SR-403
// The () -> T => () -> () implicit conversion was kicking in anywhere
// inside a closure result, not just at the top-level.
let mismatchInClosureResultType : (String) -> ((Int) -> Void) = {
(String) -> ((Int) -> Void) in
return { }
// expected-error@-1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}}
}
// SR-3520: Generic function taking closure with inout parameter can result in a variety of compiler errors or EXC_BAD_ACCESS
func sr3520_1<T>(_ g: (inout T) -> Int) {}
sr3520_1 { $0 = 1 } // expected-error {{cannot convert value of type '()' to closure result type 'Int'}}
func sr3520_2<T>(_ item: T, _ update: (inout T) -> Void) {
var x = item
update(&x)
}
var sr3250_arg = 42
sr3520_2(sr3250_arg) { $0 += 3 } // ok
// This test makes sure that having closure with inout argument doesn't crash with member lookup
struct S_3520 {
var number1: Int
}
func sr3520_set_via_closure<S, T>(_ closure: (inout S, T) -> ()) {}
sr3520_set_via_closure({ $0.number1 = $1 }) // expected-error {{type of expression is ambiguous without more context}}
// SR-1976/SR-3073: Inference of inout
func sr1976<T>(_ closure: (inout T) -> Void) {}
sr1976({ $0 += 2 }) // ok
// SR-3073: UnresolvedDotExpr in single expression closure
struct SR3073Lense<Whole, Part> {
let set: (inout Whole, Part) -> ()
}
struct SR3073 {
var number1: Int
func lenses() {
let _: SR3073Lense<SR3073, Int> = SR3073Lense(
set: { $0.number1 = $1 } // ok
)
}
}
// SR-3479: Segmentation fault and other error for closure with inout parameter
func sr3497_unfold<A, B>(_ a0: A, next: (inout A) -> B) {}
func sr3497() {
let _ = sr3497_unfold((0, 0)) { s in 0 } // ok
}
// SR-3758: Swift 3.1 fails to compile 3.0 code involving closures and IUOs
let _: ((Any?) -> Void) = { (arg: Any!) in }
// This example was rejected in 3.0 as well, but accepting it is correct.
let _: ((Int?) -> Void) = { (arg: Int!) in }
// rdar://30429709 - We should not attempt an implicit conversion from
// () -> T to () -> Optional<()>.
func returnsArray() -> [Int] { return [] }
returnsArray().flatMap { $0 }.flatMap { }
// expected-warning@-1 {{expression of type 'Int' is unused}}
// expected-warning@-2 {{Please use map instead.}}
// expected-warning@-3 {{result of call to 'flatMap' is unused}}
// rdar://problem/30271695
_ = ["hi"].flatMap { $0.isEmpty ? nil : $0 }
|
apache-2.0
|
GlobusLTD/components-ios
|
Package.swift
|
1
|
76
|
import PackageDescription
let package = Package(
name: "GlobusSwifty"
)
|
mit
|
SuperAwesomeLTD/sa-mobile-sdk-ios
|
Example/SuperAwesomeExampleTests/Common/Components/VastParserTests.swift
|
1
|
20229
|
//
// NativeVastPasserTests.swift
// SuperAwesome-Unit-Full-Tests
//
// Created by Mark on 09/06/2021.
//
import XCTest
import Nimble
@testable import SuperAwesome
class VastParserTests: XCTestCase {
func test_merge_vastAds() throws {
// Given
let vastAd1 = VastAd(url: "url1", type: .inLine, redirect: nil, startEvents: ["", ""], media: [VastMedia(), VastMedia()])
let vastAd2 = VastAd(url: "url2", type: .wrapper, startEvents: [""], media: [VastMedia()])
// When
let merged = vastAd1.merge(from: vastAd2)
// Then
expect(merged.url).to(equal("url2"))
expect(merged.startEvents.count).to(equal(3))
expect(merged.media.count).to(equal(3))
}
func test_parse_response_sample() throws {
// Given
let parser = VastParser(connectionProvider: ConnectionProviderMock())
// When
let vast = parser.parse(xmlFile("sample"))
// Then
expect(vast?.url).to(equal("https://video-transcoded-api-main-awesomeads.sacdn.net/MB7k7pTym4lGaqt3wd167TLCOMg6Lh4P.mp4"))
expect(vast?.errorEvents).to(equal(["https://eu-west-1-ads.superawesome.tv/v2/video/error?placement=44262&creative=345867&line_item=74792&sdkVersion=ios_8.0.7&rnd=58472dfc-df49-4299-899a-ea004efe317f&dauid=326997549390609966&device=phone&bundle=tv.superawesome.awesomeads.sdk&ct=2&lang=en_US&country=GB®ion=ENG&flow=normal&ua=SuperAwesomeExample%2F1.0%20(tv.superawesome.awesomeads.sdk%3B%20build%3A2%3B%20iOS%2014.5.0)%20Alamofire%2F5.4.3&aua=eyJhbGciOiJIUzI1NiJ9.TW96aWxsYS81LjAgKGlQaG9uZTsgQ1BVIGlQaG9uZSBPUyAxM181XzEgbGlrZSBNYWMgT1MgWCkgQXBwbGVXZWJLaXQvNjA1LjEuMTUgKEtIVE1MLCBsaWtlIEdlY2tvKSBWZXJzaW9uLzEzLjEgTW9iaWxlLzE1RTE0OCBTYWZhcmkvNjA0LjE.4BfJdabo9HtuqgyAOcE3uqHJbhq4FDACJX-Fh1MQdJY&tip=eyJhbGciOiJIUzI1NiJ9.MTM0LjE5LjE5Mi4w.JajWr5M0WbD9_90UR8MzKE4sb4XP_kqk0rKhIwBRtxs&code=[ERRORCODE]"]))
expect(vast?.impressionEvents.first).to(equal("https://eu-west-1-ads.superawesome.tv/v2/video/impression?placement=44262&creative=345867&line_item=74792&sdkVersion=ios_8.0.7&rnd=58472dfc-df49-4299-899a-ea004efe317f&dauid=326997549390609966&device=phone&bundle=tv.superawesome.awesomeads.sdk&ct=2&lang=en_US&country=GB®ion=ENG&flow=normal&ua=SuperAwesomeExample%2F1.0%20(tv.superawesome.awesomeads.sdk%3B%20build%3A2%3B%20iOS%2014.5.0)%20Alamofire%2F5.4.3&aua=eyJhbGciOiJIUzI1NiJ9.TW96aWxsYS81LjAgKGlQaG9uZTsgQ1BVIGlQaG9uZSBPUyAxM181XzEgbGlrZSBNYWMgT1MgWCkgQXBwbGVXZWJLaXQvNjA1LjEuMTUgKEtIVE1MLCBsaWtlIEdlY2tvKSBWZXJzaW9uLzEzLjEgTW9iaWxlLzE1RTE0OCBTYWZhcmkvNjA0LjE.4BfJdabo9HtuqgyAOcE3uqHJbhq4FDACJX-Fh1MQdJY&tip=eyJhbGciOiJIUzI1NiJ9.MTM0LjE5LjE5Mi4w.JajWr5M0WbD9_90UR8MzKE4sb4XP_kqk0rKhIwBRtxs"))
expect(vast?.clickThroughUrl).to(equal("https://eu-west-1-ads.superawesome.tv/v2/video/click?placement=44262&creative=345867&line_item=74792&sdkVersion=ios_8.0.7&rnd=58472dfc-df49-4299-899a-ea004efe317f&dauid=326997549390609966&device=phone&bundle=tv.superawesome.awesomeads.sdk&ct=2&lang=en_US&country=GB®ion=ENG&flow=normal&ua=SuperAwesomeExample%2F1.0%20(tv.superawesome.awesomeads.sdk%3B%20build%3A2%3B%20iOS%2014.5.0)%20Alamofire%2F5.4.3&aua=eyJhbGciOiJIUzI1NiJ9.TW96aWxsYS81LjAgKGlQaG9uZTsgQ1BVIGlQaG9uZSBPUyAxM181XzEgbGlrZSBNYWMgT1MgWCkgQXBwbGVXZWJLaXQvNjA1LjEuMTUgKEtIVE1MLCBsaWtlIEdlY2tvKSBWZXJzaW9uLzEzLjEgTW9iaWxlLzE1RTE0OCBTYWZhcmkvNjA0LjE.4BfJdabo9HtuqgyAOcE3uqHJbhq4FDACJX-Fh1MQdJY&tip=eyJhbGciOiJIUzI1NiJ9.MTM0LjE5LjE5Mi4w.JajWr5M0WbD9_90UR8MzKE4sb4XP_kqk0rKhIwBRtxs"))
expect(vast?.redirect).to(beNil())
expect(vast?.type).to(equal(.inLine))
// expect(vast?.media.first).to(equal(
// VastMedia(type: "video/mp4", url: "https://video-transcoded-api-main-awesomeads.sacdn.net/MB7k7pTym4lGaqt3wd167TLCOMg6Lh4P-low.mp4", bitrate: 360, width: 600, height: 480)))
expect(vast?.media.count).to(equal(3))
expect(vast?.creativeViewEvents).to(equal(["https://eu-west-1-ads.superawesome.tv/v2/video/tracking?event=creativeView&placement=44262&creative=345867&line_item=74792&sdkVersion=ios_8.0.7&rnd=58472dfc-df49-4299-899a-ea004efe317f&dauid=326997549390609966&device=phone&bundle=tv.superawesome.awesomeads.sdk&ct=2&lang=en_US&country=GB®ion=ENG&flow=normal&ua=SuperAwesomeExample%2F1.0%20(tv.superawesome.awesomeads.sdk%3B%20build%3A2%3B%20iOS%2014.5.0)%20Alamofire%2F5.4.3&aua=eyJhbGciOiJIUzI1NiJ9.TW96aWxsYS81LjAgKGlQaG9uZTsgQ1BVIGlQaG9uZSBPUyAxM181XzEgbGlrZSBNYWMgT1MgWCkgQXBwbGVXZWJLaXQvNjA1LjEuMTUgKEtIVE1MLCBsaWtlIEdlY2tvKSBWZXJzaW9uLzEzLjEgTW9iaWxlLzE1RTE0OCBTYWZhcmkvNjA0LjE.4BfJdabo9HtuqgyAOcE3uqHJbhq4FDACJX-Fh1MQdJY&tip=eyJhbGciOiJIUzI1NiJ9.MTM0LjE5LjE5Mi4w.JajWr5M0WbD9_90UR8MzKE4sb4XP_kqk0rKhIwBRtxs"]))
expect(vast?.startEvents).to(equal(["https://eu-west-1-ads.superawesome.tv/v2/video/tracking?event=start&placement=44262&creative=345867&line_item=74792&sdkVersion=ios_8.0.7&rnd=58472dfc-df49-4299-899a-ea004efe317f&dauid=326997549390609966&device=phone&bundle=tv.superawesome.awesomeads.sdk&ct=2&lang=en_US&country=GB®ion=ENG&flow=normal&ua=SuperAwesomeExample%2F1.0%20(tv.superawesome.awesomeads.sdk%3B%20build%3A2%3B%20iOS%2014.5.0)%20Alamofire%2F5.4.3&aua=eyJhbGciOiJIUzI1NiJ9.TW96aWxsYS81LjAgKGlQaG9uZTsgQ1BVIGlQaG9uZSBPUyAxM181XzEgbGlrZSBNYWMgT1MgWCkgQXBwbGVXZWJLaXQvNjA1LjEuMTUgKEtIVE1MLCBsaWtlIEdlY2tvKSBWZXJzaW9uLzEzLjEgTW9iaWxlLzE1RTE0OCBTYWZhcmkvNjA0LjE.4BfJdabo9HtuqgyAOcE3uqHJbhq4FDACJX-Fh1MQdJY&tip=eyJhbGciOiJIUzI1NiJ9.MTM0LjE5LjE5Mi4w.JajWr5M0WbD9_90UR8MzKE4sb4XP_kqk0rKhIwBRtxs"]))
expect( vast?.firstQuartileEvents).to(equal([
"https://eu-west-1-ads.superawesome.tv/v2/video/tracking?event=firstQuartile&placement=44262&creative=345867&line_item=74792&sdkVersion=ios_8.0.7&rnd=58472dfc-df49-4299-899a-ea004efe317f&dauid=326997549390609966&device=phone&bundle=tv.superawesome.awesomeads.sdk&ct=2&lang=en_US&country=GB®ion=ENG&flow=normal&ua=SuperAwesomeExample%2F1.0%20(tv.superawesome.awesomeads.sdk%3B%20build%3A2%3B%20iOS%2014.5.0)%20Alamofire%2F5.4.3&aua=eyJhbGciOiJIUzI1NiJ9.TW96aWxsYS81LjAgKGlQaG9uZTsgQ1BVIGlQaG9uZSBPUyAxM181XzEgbGlrZSBNYWMgT1MgWCkgQXBwbGVXZWJLaXQvNjA1LjEuMTUgKEtIVE1MLCBsaWtlIEdlY2tvKSBWZXJzaW9uLzEzLjEgTW9iaWxlLzE1RTE0OCBTYWZhcmkvNjA0LjE.4BfJdabo9HtuqgyAOcE3uqHJbhq4FDACJX-Fh1MQdJY&tip=eyJhbGciOiJIUzI1NiJ9.MTM0LjE5LjE5Mi4w.JajWr5M0WbD9_90UR8MzKE4sb4XP_kqk0rKhIwBRtxs"
]))
expect( vast?.midPointEvents).to(equal([ "https://eu-west-1-ads.superawesome.tv/v2/video/tracking?event=midpoint&placement=44262&creative=345867&line_item=74792&sdkVersion=ios_8.0.7&rnd=58472dfc-df49-4299-899a-ea004efe317f&dauid=326997549390609966&device=phone&bundle=tv.superawesome.awesomeads.sdk&ct=2&lang=en_US&country=GB®ion=ENG&flow=normal&ua=SuperAwesomeExample%2F1.0%20(tv.superawesome.awesomeads.sdk%3B%20build%3A2%3B%20iOS%2014.5.0)%20Alamofire%2F5.4.3&aua=eyJhbGciOiJIUzI1NiJ9.TW96aWxsYS81LjAgKGlQaG9uZTsgQ1BVIGlQaG9uZSBPUyAxM181XzEgbGlrZSBNYWMgT1MgWCkgQXBwbGVXZWJLaXQvNjA1LjEuMTUgKEtIVE1MLCBsaWtlIEdlY2tvKSBWZXJzaW9uLzEzLjEgTW9iaWxlLzE1RTE0OCBTYWZhcmkvNjA0LjE.4BfJdabo9HtuqgyAOcE3uqHJbhq4FDACJX-Fh1MQdJY&tip=eyJhbGciOiJIUzI1NiJ9.MTM0LjE5LjE5Mi4w.JajWr5M0WbD9_90UR8MzKE4sb4XP_kqk0rKhIwBRtxs"]))
expect( vast?.thirdQuartileEvents).to(equal([ "https://eu-west-1-ads.superawesome.tv/v2/video/tracking?event=thirdQuartile&placement=44262&creative=345867&line_item=74792&sdkVersion=ios_8.0.7&rnd=58472dfc-df49-4299-899a-ea004efe317f&dauid=326997549390609966&device=phone&bundle=tv.superawesome.awesomeads.sdk&ct=2&lang=en_US&country=GB®ion=ENG&flow=normal&ua=SuperAwesomeExample%2F1.0%20(tv.superawesome.awesomeads.sdk%3B%20build%3A2%3B%20iOS%2014.5.0)%20Alamofire%2F5.4.3&aua=eyJhbGciOiJIUzI1NiJ9.TW96aWxsYS81LjAgKGlQaG9uZTsgQ1BVIGlQaG9uZSBPUyAxM181XzEgbGlrZSBNYWMgT1MgWCkgQXBwbGVXZWJLaXQvNjA1LjEuMTUgKEtIVE1MLCBsaWtlIEdlY2tvKSBWZXJzaW9uLzEzLjEgTW9iaWxlLzE1RTE0OCBTYWZhcmkvNjA0LjE.4BfJdabo9HtuqgyAOcE3uqHJbhq4FDACJX-Fh1MQdJY&tip=eyJhbGciOiJIUzI1NiJ9.MTM0LjE5LjE5Mi4w.JajWr5M0WbD9_90UR8MzKE4sb4XP_kqk0rKhIwBRtxs"]))
expect( vast?.completeEvents ).to(equal(["https://eu-west-1-ads.superawesome.tv/v2/video/tracking?event=complete&placement=44262&creative=345867&line_item=74792&sdkVersion=ios_8.0.7&rnd=58472dfc-df49-4299-899a-ea004efe317f&dauid=326997549390609966&device=phone&bundle=tv.superawesome.awesomeads.sdk&ct=2&lang=en_US&country=GB®ion=ENG&flow=normal&ua=SuperAwesomeExample%2F1.0%20(tv.superawesome.awesomeads.sdk%3B%20build%3A2%3B%20iOS%2014.5.0)%20Alamofire%2F5.4.3&aua=eyJhbGciOiJIUzI1NiJ9.TW96aWxsYS81LjAgKGlQaG9uZTsgQ1BVIGlQaG9uZSBPUyAxM181XzEgbGlrZSBNYWMgT1MgWCkgQXBwbGVXZWJLaXQvNjA1LjEuMTUgKEtIVE1MLCBsaWtlIEdlY2tvKSBWZXJzaW9uLzEzLjEgTW9iaWxlLzE1RTE0OCBTYWZhcmkvNjA0LjE.4BfJdabo9HtuqgyAOcE3uqHJbhq4FDACJX-Fh1MQdJY&tip=eyJhbGciOiJIUzI1NiJ9.MTM0LjE5LjE5Mi4w.JajWr5M0WbD9_90UR8MzKE4sb4XP_kqk0rKhIwBRtxs"]))
expect(vast?.clickTrackingEvents).to(equal([]))
}
func test_parse_response1() throws {
// Given
let parser = VastParser(connectionProvider: ConnectionProviderMock())
// When
let vast = parser.parse(xmlFile("mock_vast_response_2.1"))
// Then
expect(vast?.url).to(equal("https://ads.superawesome.tv/v2/demo_images/video.mp4"))
expect(vast?.errorEvents).to(equal(["https://pubads.g.doubleclick.net/pagead/conversion/?ai=B4fABspJ4WI7IIOfQxgLToLbAC_jXj-sGAAAAEAEgqN27JjgAWPDXgsbXAWC7vq6D0Aq6AQo3Mjh4OTBfeG1syAEFwAIC4AIA6gIjLzEyNDMxOTA5Ni9leHRlcm5hbC91dGlsaXR5X3NhbXBsZXP4AvfRHoADAZAD0AWYA_ABqAMB4AQB0gUGEKCr9NICkAYBoAYj2AcB4AcK&sigh=US9RxyYaTkY&label=videoplayfailed"]))
expect(vast?.impressionEvents.first).to(equal("https://securepubads.g.doubleclick.net/pcs/view?xai=AKAOjsvu_KHi7FozgcUQ_KvpFfESzUfUOI0AMJfAs8hGlPO7fYz7ABNEy2ZPY4yqxPbz-xQUIgQsi3DBAP0rXWP6SR8bbrwP6hYHWzhMJwFnyb76dMwn4-K_USe_6yhy9CXJeJcEvl0t3bdJi5veWgiE-gJ4JSBl4fidhOC9VjIT09aCaptXTdUWE0P5JRAFVdJBccg11lB5T7X3OyROZPF0AUSQyjoEQ5jb6Orhuu_MlyI&sig=Cg0ArKJSzD8mjjRQaKzgEAE&adurl="))
expect(vast?.clickThroughUrl).to(equal("https://pubads.g.doubleclick.net/pcs/click?xai=AKAOjsspolSuXa7AwEbPP7AZ-GxS21aUHa9uiCLztqPfZWzuDeBfP6YjdyprsdOp9BCHCEQDZh-gcCZA79vQnFj_eY7nSvD1ARORC5Ve2bofK1CxuU66k0XPX5mrHChaKn7VQi-iXxuiIuxa_-su7JuWpij9jBopE8WvoPTNgIl6HzfKpqSL7gsWXyCBy_j34zeywTjbPByh4Zp43QMKohRxs-sXRgPi7zoJZIoT&sig=Cg0ArKJSzEfYCW3PG__E&adurl=https://developers.google.com/interactive-media-ads/docs/vastinspector_dual"))
expect(vast?.redirect).to(beNil())
expect(vast?.type).to(equal(.inLine))
// expect(vast?.media.first).to(equal(
// VastMedia(type: "video/mp4", url: "https://ads.superawesome.tv/v2/demo_images/video.mp4", bitrate: 524, width: 1280, height: 720)))
expect(vast?.media.count).to(equal(3))
// expect(vast?.creativeViewEvents).to(equal(["https://pubads.g.doubleclick.net/pagead/conversion/?ai=B4fABspJ4WI7IIOfQxgLToLbAC_jXj-sGAAAAEAEgqN27JjgAWPDXgsbXAWC7vq6D0Aq6AQo3Mjh4OTBfeG1syAEFwAIC4AIA6gIjLzEyNDMxOTA5Ni9leHRlcm5hbC91dGlsaXR5X3NhbXBsZXP4AvfRHoADAZAD0AWYA_ABqAMB4AQB0gUGEKCr9NICkAYBoAYj2AcB4AcK&sigh=US9RxyYaTkY&label=vast_creativeview&ad_mt=[AD_MT]", "https://securepubads.g.doubleclick.net/pcs/view?xai=AKAOjsvTB5ol1x1lM64QbnRzVlRm8G-60S9J1iykgL1YRmHbJjk9tkdYmRnShkkIGB5DtIIssHpa-xjKLlbJZY0I3MkiOzgPejGl49WUU7xgIEKLgk5dvaTI2fbTGGvJ_NpRkgceoTp6Q34-xD6jGr9WZDBfjLcagVtOMKoTaPScsPqp9BEjCEfV9Eu5cKStGMfpATC095nf4eYfSVToJKJ7JQCwMA-DfBnbeHeqwNbP5mA&sig=Cg0ArKJSzNlAgX3qZliFEAE&adurl="]))
expect(vast?.startEvents).to(equal(["https://pubads.g.doubleclick.net/pagead/conversion/?ai=B4fABspJ4WI7IIOfQxgLToLbAC_jXj-sGAAAAEAEgqN27JjgAWPDXgsbXAWC7vq6D0Aq6AQo3Mjh4OTBfeG1syAEFwAIC4AIA6gIjLzEyNDMxOTA5Ni9leHRlcm5hbC91dGlsaXR5X3NhbXBsZXP4AvfRHoADAZAD0AWYA_ABqAMB4AQB0gUGEKCr9NICkAYBoAYj2AcB4AcK&sigh=US9RxyYaTkY&label=part2viewed&ad_mt=[AD_MT]", "https://video-ad-stats.googlesyndication.com/video/client_events?event=2&web_property=ca-pub-3279133228669082&cpn=[CPN]&break_type=[BREAK_TYPE]&slot_pos=[SLOT_POS]&ad_id=[AD_ID]&ad_sys=[AD_SYS]&ad_len=[AD_LEN]&p_w=[P_W]&p_h=[P_H]&mt=[MT]&rwt=[RWT]&wt=[WT]&sdkv=[SDKV]&vol=[VOL]&content_v=[CONTENT_V]&conn=[CONN]&format=[FORMAT_NAMESPACE]_[FORMAT_TYPE]_[FORMAT_SUBTYPE]"]))
expect( vast?.firstQuartileEvents).to(equal([
"https://pubads.g.doubleclick.net/pagead/conversion/?ai=B4fABspJ4WI7IIOfQxgLToLbAC_jXj-sGAAAAEAEgqN27JjgAWPDXgsbXAWC7vq6D0Aq6AQo3Mjh4OTBfeG1syAEFwAIC4AIA6gIjLzEyNDMxOTA5Ni9leHRlcm5hbC91dGlsaXR5X3NhbXBsZXP4AvfRHoADAZAD0AWYA_ABqAMB4AQB0gUGEKCr9NICkAYBoAYj2AcB4AcK&sigh=US9RxyYaTkY&label=videoplaytime25&ad_mt=[AD_MT]"
]))
expect( vast?.midPointEvents).to(equal([ "https://pubads.g.doubleclick.net/pagead/conversion/?ai=B4fABspJ4WI7IIOfQxgLToLbAC_jXj-sGAAAAEAEgqN27JjgAWPDXgsbXAWC7vq6D0Aq6AQo3Mjh4OTBfeG1syAEFwAIC4AIA6gIjLzEyNDMxOTA5Ni9leHRlcm5hbC91dGlsaXR5X3NhbXBsZXP4AvfRHoADAZAD0AWYA_ABqAMB4AQB0gUGEKCr9NICkAYBoAYj2AcB4AcK&sigh=US9RxyYaTkY&label=videoplaytime50&ad_mt=[AD_MT]"]))
expect( vast?.thirdQuartileEvents).to(equal([ "https://pubads.g.doubleclick.net/pagead/conversion/?ai=B4fABspJ4WI7IIOfQxgLToLbAC_jXj-sGAAAAEAEgqN27JjgAWPDXgsbXAWC7vq6D0Aq6AQo3Mjh4OTBfeG1syAEFwAIC4AIA6gIjLzEyNDMxOTA5Ni9leHRlcm5hbC91dGlsaXR5X3NhbXBsZXP4AvfRHoADAZAD0AWYA_ABqAMB4AQB0gUGEKCr9NICkAYBoAYj2AcB4AcK&sigh=US9RxyYaTkY&label=videoplaytime75&ad_mt=[AD_MT]"]))
expect( vast?.completeEvents ).to(equal(["https://pubads.g.doubleclick.net/pagead/conversion/?ai=B4fABspJ4WI7IIOfQxgLToLbAC_jXj-sGAAAAEAEgqN27JjgAWPDXgsbXAWC7vq6D0Aq6AQo3Mjh4OTBfeG1syAEFwAIC4AIA6gIjLzEyNDMxOTA5Ni9leHRlcm5hbC91dGlsaXR5X3NhbXBsZXP4AvfRHoADAZAD0AWYA_ABqAMB4AQB0gUGEKCr9NICkAYBoAYj2AcB4AcK&sigh=US9RxyYaTkY&label=videoplaytime100&ad_mt=[AD_MT]", "https://video-ad-stats.googlesyndication.com/video/client_events?event=3&web_property=ca-pub-3279133228669082&cpn=[CPN]&break_type=[BREAK_TYPE]&slot_pos=[SLOT_POS]&ad_id=[AD_ID]&ad_sys=[AD_SYS]&ad_len=[AD_LEN]&p_w=[P_W]&p_h=[P_H]&mt=[MT]&rwt=[RWT]&wt=[WT]&sdkv=[SDKV]&vol=[VOL]&content_v=[CONTENT_V]&conn=[CONN]&format=[FORMAT_NAMESPACE]_[FORMAT_TYPE]_[FORMAT_SUBTYPE]"]))
expect(vast?.clickTrackingEvents).to(equal(["https://video-ad-stats.googlesyndication.com/video/client_events?event=6&web_property=ca-pub-3279133228669082&cpn=[CPN]&break_type=[BREAK_TYPE]&slot_pos=[SLOT_POS]&ad_id=[AD_ID]&ad_sys=[AD_SYS]&ad_len=[AD_LEN]&p_w=[P_W]&p_h=[P_H]&mt=[MT]&rwt=[RWT]&wt=[WT]&sdkv=[SDKV]&vol=[VOL]&content_v=[CONTENT_V]&conn=[CONN]&format=[FORMAT_NAMESPACE]_[FORMAT_TYPE]_[FORMAT_SUBTYPE]"]))
}
func test_parse_response2() throws {
// Given
let parser = VastParser(connectionProvider: ConnectionProviderMock())
// When
let vast = parser.parse(xmlFile("mock_vast_response_2.0"))
// Then
expect(vast?.errorEvents.count).to(equal(1))
expect(vast?.impressionEvents.count).to(equal(1))
expect(vast?.clickTrackingEvents.count).to(equal(2))
expect(vast?.redirect).to(equal("https://my.mock.api/vast/vast2.1.xml"))
expect(vast?.type).to(equal(.wrapper))
expect(vast?.media.count).to(equal(0))
expect(vast?.creativeViewEvents).to(equal(["https://pubads.g.doubleclick.net/pagead/conversion/?ai=BLY-QpZJ4WL-oDcOLbcvpodAOoK2Q6wYAAAAQASCo3bsmOABYiKrYxtcBYLu-roPQCrIBFWRldmVsb3BlcnMuZ29vZ2xlLmNvbboBCjcyOHg5MF94bWzIAQXaAUhodHRwczovL2RldmVsb3BlcnMuZ29vZ2xlLmNvbS9pbnRlcmFjdGl2ZS1tZWRpYS1hZHMvZG9jcy9zZGtzL2h0bWw1L3RhZ3PAAgLgAgDqAiUvMTI0MzE5MDk2L2V4dGVybmFsL3NpbmdsZV9hZF9zYW1wbGVz-AL30R6AAwGQA9AFmAPwAagDAeAEAdIFBhCIrvTSApAGAaAGJNgHAOAHCg&sigh=ClmLNunom9E&label=vast_creativeview&ad_mt=[AD_MT]"]))
expect(vast?.startEvents).to(equal(["https://pubads.g.doubleclick.net/pagead/conversion/?ai=BLY-QpZJ4WL-oDcOLbcvpodAOoK2Q6wYAAAAQASCo3bsmOABYiKrYxtcBYLu-roPQCrIBFWRldmVsb3BlcnMuZ29vZ2xlLmNvbboBCjcyOHg5MF94bWzIAQXaAUhodHRwczovL2RldmVsb3BlcnMuZ29vZ2xlLmNvbS9pbnRlcmFjdGl2ZS1tZWRpYS1hZHMvZG9jcy9zZGtzL2h0bWw1L3RhZ3PAAgLgAgDqAiUvMTI0MzE5MDk2L2V4dGVybmFsL3NpbmdsZV9hZF9zYW1wbGVz-AL30R6AAwGQA9AFmAPwAagDAeAEAdIFBhCIrvTSApAGAaAGJNgHAOAHCg&sigh=ClmLNunom9E&label=part2viewed&ad_mt=[AD_MT]", "https://video-ad-stats.googlesyndication.com/video/client_events?event=2&web_property=ca-pub-3279133228669082&cpn=[CPN]&break_type=[BREAK_TYPE]&slot_pos=[SLOT_POS]&ad_id=[AD_ID]&ad_sys=[AD_SYS]&ad_len=[AD_LEN]&p_w=[P_W]&p_h=[P_H]&mt=[MT]&rwt=[RWT]&wt=[WT]&sdkv=[SDKV]&vol=[VOL]&content_v=[CONTENT_V]&conn=[CONN]&format=[FORMAT_NAMESPACE]_[FORMAT_TYPE]_[FORMAT_SUBTYPE]"]))
expect( vast?.firstQuartileEvents).to(equal([
"https://pubads.g.doubleclick.net/pagead/conversion/?ai=BLY-QpZJ4WL-oDcOLbcvpodAOoK2Q6wYAAAAQASCo3bsmOABYiKrYxtcBYLu-roPQCrIBFWRldmVsb3BlcnMuZ29vZ2xlLmNvbboBCjcyOHg5MF94bWzIAQXaAUhodHRwczovL2RldmVsb3BlcnMuZ29vZ2xlLmNvbS9pbnRlcmFjdGl2ZS1tZWRpYS1hZHMvZG9jcy9zZGtzL2h0bWw1L3RhZ3PAAgLgAgDqAiUvMTI0MzE5MDk2L2V4dGVybmFsL3NpbmdsZV9hZF9zYW1wbGVz-AL30R6AAwGQA9AFmAPwAagDAeAEAdIFBhCIrvTSApAGAaAGJNgHAOAHCg&sigh=ClmLNunom9E&label=videoplaytime25&ad_mt=[AD_MT]"
]))
expect( vast?.midPointEvents).to(equal([ "https://pubads.g.doubleclick.net/pagead/conversion/?ai=BLY-QpZJ4WL-oDcOLbcvpodAOoK2Q6wYAAAAQASCo3bsmOABYiKrYxtcBYLu-roPQCrIBFWRldmVsb3BlcnMuZ29vZ2xlLmNvbboBCjcyOHg5MF94bWzIAQXaAUhodHRwczovL2RldmVsb3BlcnMuZ29vZ2xlLmNvbS9pbnRlcmFjdGl2ZS1tZWRpYS1hZHMvZG9jcy9zZGtzL2h0bWw1L3RhZ3PAAgLgAgDqAiUvMTI0MzE5MDk2L2V4dGVybmFsL3NpbmdsZV9hZF9zYW1wbGVz-AL30R6AAwGQA9AFmAPwAagDAeAEAdIFBhCIrvTSApAGAaAGJNgHAOAHCg&sigh=ClmLNunom9E&label=videoplaytime50&ad_mt=[AD_MT]"]))
expect( vast?.thirdQuartileEvents).to(equal([ "https://pubads.g.doubleclick.net/pagead/conversion/?ai=BLY-QpZJ4WL-oDcOLbcvpodAOoK2Q6wYAAAAQASCo3bsmOABYiKrYxtcBYLu-roPQCrIBFWRldmVsb3BlcnMuZ29vZ2xlLmNvbboBCjcyOHg5MF94bWzIAQXaAUhodHRwczovL2RldmVsb3BlcnMuZ29vZ2xlLmNvbS9pbnRlcmFjdGl2ZS1tZWRpYS1hZHMvZG9jcy9zZGtzL2h0bWw1L3RhZ3PAAgLgAgDqAiUvMTI0MzE5MDk2L2V4dGVybmFsL3NpbmdsZV9hZF9zYW1wbGVz-AL30R6AAwGQA9AFmAPwAagDAeAEAdIFBhCIrvTSApAGAaAGJNgHAOAHCg&sigh=ClmLNunom9E&label=videoplaytime75&ad_mt=[AD_MT]"]))
expect( vast?.completeEvents).to(equal([ "https://pubads.g.doubleclick.net/pagead/conversion/?ai=BLY-QpZJ4WL-oDcOLbcvpodAOoK2Q6wYAAAAQASCo3bsmOABYiKrYxtcBYLu-roPQCrIBFWRldmVsb3BlcnMuZ29vZ2xlLmNvbboBCjcyOHg5MF94bWzIAQXaAUhodHRwczovL2RldmVsb3BlcnMuZ29vZ2xlLmNvbS9pbnRlcmFjdGl2ZS1tZWRpYS1hZHMvZG9jcy9zZGtzL2h0bWw1L3RhZ3PAAgLgAgDqAiUvMTI0MzE5MDk2L2V4dGVybmFsL3NpbmdsZV9hZF9zYW1wbGVz-AL30R6AAwGQA9AFmAPwAagDAeAEAdIFBhCIrvTSApAGAaAGJNgHAOAHCg&sigh=ClmLNunom9E&label=videoplaytime100&ad_mt=[AD_MT]", "https://video-ad-stats.googlesyndication.com/video/client_events?event=3&web_property=ca-pub-3279133228669082&cpn=[CPN]&break_type=[BREAK_TYPE]&slot_pos=[SLOT_POS]&ad_id=[AD_ID]&ad_sys=[AD_SYS]&ad_len=[AD_LEN]&p_w=[P_W]&p_h=[P_H]&mt=[MT]&rwt=[RWT]&wt=[WT]&sdkv=[SDKV]&vol=[VOL]&content_v=[CONTENT_V]&conn=[CONN]&format=[FORMAT_NAMESPACE]_[FORMAT_TYPE]_[FORMAT_SUBTYPE]"]))
expect(vast?.clickTrackingEvents).to(equal(["https://video-ad-stats.googlesyndication.com/video/client_events?event=6&web_property=ca-pub-3279133228669082&cpn=[CPN]&break_type=[BREAK_TYPE]&slot_pos=[SLOT_POS]&ad_id=[AD_ID]&ad_sys=[AD_SYS]&ad_len=[AD_LEN]&p_w=[P_W]&p_h=[P_H]&mt=[MT]&rwt=[RWT]&wt=[WT]&sdkv=[SDKV]&vol=[VOL]&content_v=[CONTENT_V]&conn=[CONN]&format=[FORMAT_NAMESPACE]_[FORMAT_TYPE]_[FORMAT_SUBTYPE]", "https://pubads.g.doubleclick.net/pcs/click?xai=AKAOjsuyjdNJZ1zHVE5WfaJrEvrP7eK0VqSdNyGBRoMjMXd90VYE3xZVr3l5Kn0h166VefqEYqeNX_z_zObIjytcV-YGYRDvmnzU93x3Kplly4YHIdlHtXRrAE3AbaZAjN9HEjoTs4g6GZM7lc4KX_5OdCRwaEq-DuVxs0QZNkyJ5b8nCA3nkya8WzKLmAf_4sjx3e3aAanzjuaYc1__5LMi7hXLuYk_Bubh7HNPofn4y8PKVmnaOZGfaycMkFIr4pTd1DdQJ6Ma&sig=Cg0ArKJSzOdaV5VR9GxbEAE&urlfix=1"]))
}
}
|
lgpl-3.0
|
lorentey/swift
|
test/SourceKit/CursorInfo/use-swift-source-info.swift
|
3
|
1524
|
import Foo
func bar() {
foo()
}
// RUN: %empty-directory(%t)
// RUN: echo "/// Some doc" >> %t/Foo.swift
// RUN: echo "public func foo() { }" >> %t/Foo.swift
// RUN: %target-swift-frontend -enable-batch-mode -emit-module -emit-module-doc -emit-module-path %t/Foo.swiftmodule %t/Foo.swift -module-name Foo -emit-module-source-info-path %t/Foo.swiftsourceinfo -emit-module-doc-path %t/Foo.swiftdoc
//
// Test setting optimize for ide to false
// RUN: %sourcekitd-test -req=global-config -for-ide=0 == -req=cursor -pos=3:3 %s -- -I %t -target %target-triple %s | %FileCheck --check-prefixes=BOTH,WITH %s
//
// Test setting optimize for ide to true
// RUN: %sourcekitd-test -req=global-config -for-ide=1 == -req=cursor -pos=3:3 %s -- -I %t -target %target-triple %s | %FileCheck --check-prefixes=BOTH,WITHOUT %s
//
// Test sourcekitd-test's default global configuration request (optimize for ide is true)
// RUN: %sourcekitd-test -req=cursor -pos=3:3 %s -- -I %t -target %target-triple %s | %FileCheck --check-prefixes=BOTH,WITHOUT %s
//
// Test without sending any global configuration request to check the sevice's default settings (optimize for ide is false)
// RUN: %sourcekitd-test -suppress-config-request -req=cursor -pos=3:3 %s -- -I %t -target %target-triple %s | %FileCheck --check-prefixes=BOTH,WITH %s
// WITH: source.lang.swift.ref.function.free ({{.*}}/Foo.swift:2:13-2:16)
// WITHOUT: source.lang.swift.ref.function.free ()
// BOTH: foo()
// BOTH: s:3Foo3fooyyF
// BOTH: () -> ()
// BOTH: $syycD
// BOTH: Foo
|
apache-2.0
|
ChoingHyun/iPhone2015
|
21551197姚文豪/work1_ywh/work1_ywh/AppDelegate.swift
|
5
|
2132
|
//
// AppDelegate.swift
// work1_ywh
//
// Created by ywh on 15/10/24.
// Copyright © 2015年 ywh. 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
|
aleph7/BrainCore
|
Source/Snapshot.swift
|
1
|
5228
|
// Copyright © 2016 Venture Media Labs. All rights reserved.
//
// This file is part of BrainCore. The full BrainCore copyright notice,
// including terms governing use, modification, and redistribution, is
// contained in the file LICENSE at the root of the source code distribution
// tree.
import Foundation
import Metal
/// A data snapshot of a forward-backward pass.
open class Snapshot {
/// The network definition.
open let net: Net
var forwardBuffers: [UUID: MTLBuffer]
var backwardBuffers: [UUID: MTLBuffer]
init(net: Net, forwardBuffers: [UUID: MTLBuffer], backwardBuffers: [UUID: MTLBuffer] = [UUID: MTLBuffer]()) {
self.net = net
self.forwardBuffers = forwardBuffers
self.backwardBuffers = backwardBuffers
}
func contentsOfForwardBuffer(_ buffer: NetBuffer) -> UnsafeMutableBufferPointer<Float>? {
guard let mtlBuffer = forwardBuffers[buffer.id as UUID] else {
return nil
}
return unsafeBufferPointerFromBuffer(mtlBuffer)
}
func contentsOfBackwardBuffer(_ buffer: NetBuffer) -> UnsafeMutableBufferPointer<Float>? {
guard let mtlBuffer = backwardBuffers[buffer.id as UUID] else {
return nil
}
return unsafeBufferPointerFromBuffer(mtlBuffer)
}
/// Returns a pointer to the forward-pass contents of a network buffer.
///
/// - Note: The pointer is short-lived, you should copy any contents that you want preserve.
open func contentsOfForwardBuffer(_ ref: Net.BufferID) -> UnsafeMutableBufferPointer<Float>? {
guard let buffer = net.buffers[ref] else {
return nil
}
return contentsOfForwardBuffer(buffer)
}
/// Returns a pointer to the backward-pass contents of a network buffer.
///
/// - Note: The pointer is short-lived, you should copy any contents that you want preserve.
open func contentsOfBackwardBuffer(_ ref: Net.BufferID) -> UnsafeMutableBufferPointer<Float>? {
guard let buffer = net.buffers[ref] else {
return nil
}
return contentsOfBackwardBuffer(buffer)
}
/// Returns a pointer to the forward-pass output of a layer.
///
/// - Note: The pointer is short-lived, you should copy any contents that you want preserve.
open func outputOfLayer(_ layer: Layer) -> UnsafeMutableBufferPointer<Float>? {
guard let node = net.nodeForLayer(layer),
let bufferId = node.outputBuffer?.id,
let buffer = forwardBuffers[bufferId] else {
return nil
}
let pointer = buffer.contents().bindMemory(to: Float.self, capacity: buffer.length / MemoryLayout<Float>.size)
let count = buffer.length / MemoryLayout<Float>.size - node.outputRange.lowerBound
return UnsafeMutableBufferPointer(start: pointer + node.outputRange.lowerBound, count: count)
}
/// Returns a pointer to the forward-pass input of a layer.
///
/// - Note: The pointer is short-lived, you should copy any contents that you want preserve.
open func inputOfLayer(_ layer: Layer) -> UnsafeMutableBufferPointer<Float>? {
guard let node = net.nodeForLayer(layer),
let bufferId = node.inputBuffer?.id,
let buffer = forwardBuffers[bufferId] else {
return nil
}
let pointer = buffer.contents().bindMemory(to: Float.self, capacity: buffer.length / MemoryLayout<Float>.size)
let count = buffer.length / MemoryLayout<Float>.size - node.inputRange.lowerBound
return UnsafeMutableBufferPointer(start: pointer + node.inputRange.lowerBound, count: count)
}
/// Returns a pointer to the backward-pass input deltas of a layer.
///
/// - Note: The pointer is short-lived, you should copy any contents that you want preserve.
open func inputDeltasOfLayer(_ layer: Layer) -> UnsafeMutableBufferPointer<Float>? {
guard let node = net.nodeForLayer(layer),
let bufferId = node.inputBuffer?.id,
let buffer = backwardBuffers[bufferId] else {
return nil
}
let pointer = buffer.contents().bindMemory(to: Float.self, capacity: buffer.length / MemoryLayout<Float>.size)
let count = buffer.length / MemoryLayout<Float>.size - node.inputRange.lowerBound
return UnsafeMutableBufferPointer(start: pointer + node.inputRange.lowerBound, count: count)
}
/// Returns a pointer to the backward-pass output deltas of a layer.
///
/// - Note: The pointer is short-lived, you should copy any contents that you want preserve.
open func outputDeltasOfLayer(_ layer: Layer) -> UnsafeMutableBufferPointer<Float>? {
guard let node = net.nodeForLayer(layer),
let bufferId = node.outputBuffer?.id,
let buffer = backwardBuffers[bufferId] else {
return nil
}
let pointer = buffer.contents().bindMemory(to: Float.self, capacity: buffer.length / MemoryLayout<Float>.size)
let count = buffer.length / MemoryLayout<Float>.size - node.outputRange.lowerBound
return UnsafeMutableBufferPointer(start: pointer + node.outputRange.lowerBound, count: count)
}
}
|
mit
|
aerogear/aerogear-ios-http
|
AeroGearHttp/Utils.swift
|
2
|
1247
|
/*
* JBoss, Home of Professional Open Source.
* Copyright Red Hat, Inc., and individual contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
/**
Handy extensions and utilities.
*/
extension String {
public func urlEncode() -> String {
let str = self
return str.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
}
}
public func merge(_ one: [String: String]?, _ two: [String:String]?) -> [String: String]? {
var dict: [String: String]?
if let one = one {
dict = one
if let two = two {
for (key, value) in two {
dict![key] = value
}
}
} else {
dict = two
}
return dict
}
|
apache-2.0
|
ztolley/VideoStationViewer
|
VideoStationViewer/CoreDataHelper.swift
|
1
|
3513
|
//
// CoreDataHelper.swift
// Frazzle
//
// Created by Zac Tolley on 23/09/2014.
// Copyright (c) 2014 Zac Tolley. All rights reserved.
//
import Foundation
import CoreData
class CoreDataHelper {
static let sharedInstance = CoreDataHelper()
let modelName = "Model"
let sqlLiteFileName = "VideoStationViewer.sqlite"
lazy var applicationDocumentsDirectory: NSURL = {
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource(self.modelName, withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
// This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator!.addPersistentStoreWithType(NSInMemoryStoreType, configuration: nil, URL: nil, options: nil); } catch var error as NSError {
coordinator = nil
NSLog("Unresolved error \(error), \(error)")
abort()
} catch {
fatalError()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext.init(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data stack
lazy var applicationCachesDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.scropt.dhfghg" in the application's caches Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
func saveContext () {
if let moc = managedObjectContext {
var error: NSError? = nil
if moc.hasChanges {
do {
try moc.save()
} catch let error1 as NSError {
error = error1
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
func resetContext() {
self.managedObjectContext?.reset()
}
}
|
gpl-3.0
|
zmeyc/GRDB.swift
|
Tests/GRDBTests/DataMemoryTests.swift
|
1
|
2869
|
import XCTest
#if SWIFT_PACKAGE
import CSQLite
#endif
#if USING_SQLCIPHER
@testable import GRDBCipher
#elseif USING_CUSTOMSQLITE
@testable import GRDBCustomSQLite
#else
@testable import GRDB
#endif
class DataMemoryTests: GRDBTestCase {
func testMemoryBehavior() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE datas (data BLOB)")
let data = "foo".data(using: .utf8)
try db.execute("INSERT INTO datas (data) VALUES (?)", arguments: [data])
let rows = try Row.fetchCursor(db, "SELECT * FROM datas")
while let row = try rows.next() {
let sqliteStatement = row.sqliteStatement
let sqliteBytes = sqlite3_column_blob(sqliteStatement, 0)
do {
// This data should be copied:
let copiedData: Data = row.value(atIndex: 0)
copiedData.withUnsafeBytes { copiedBytes in
XCTAssertNotEqual(copiedBytes, sqliteBytes)
}
XCTAssertEqual(copiedData, data)
}
do {
// This data should not be copied
let nonCopiedData = row.dataNoCopy(atIndex: 0)!
nonCopiedData.withUnsafeBytes { nonCopiedBytes in
XCTAssertEqual(nonCopiedBytes, sqliteBytes)
}
XCTAssertEqual(nonCopiedData, data)
}
}
let row = try Row.fetchOne(db, "SELECT * FROM datas")!
let databaseValue = row.first!.1
switch databaseValue.storage {
case .blob(let data):
data.withUnsafeBytes { (dataBytes: UnsafePointer<UInt8>) -> Void in
do {
// This data should not be copied:
let nonCopiedData: Data = row.value(atIndex: 0)
nonCopiedData.withUnsafeBytes { nonCopiedBytes in
XCTAssertEqual(nonCopiedBytes, dataBytes)
}
XCTAssertEqual(nonCopiedData, data)
}
do {
// This data should not be copied:
let nonCopiedData = row.dataNoCopy(atIndex: 0)!
nonCopiedData.withUnsafeBytes { nonCopiedBytes in
XCTAssertEqual(nonCopiedBytes, dataBytes)
}
XCTAssertEqual(nonCopiedData, data)
}
}
default:
XCTFail("Not a blob")
}
}
}
}
|
mit
|
mitolog/JINSMEMESampler
|
JINSMEMESampler/EyeBlink.swift
|
1
|
6593
|
//
// EyeBlink.swift
// JINSMEMESampler
//
// Created by Yuhei Miyazato on 12/3/15.
// Copyright © 2015 mitolab. All rights reserved.
//
import Foundation
import UIKit
class EyeBlinkViewController: UIViewController {
var rtmData :MEMERealTimeData?
var eyeLid: CAShapeLayer?
var lowerEyeLid: CAShapeLayer?
var centerEye: CAShapeLayer?
var centerEyeInside: CAShapeLayer?
var isBlinking: Bool = false
var blinkSpeed: CGFloat = 0
var isMovingLeft :Bool = false
var isMovingRight :Bool = false
override func viewDidLoad() {
super.viewDidLoad()
let titleViewRect = CGRectMake(0, 0, self.view.frame.width*0.5, 64)
let titleLabel = UILabel(frame: titleViewRect)
titleLabel.text = "Eye Blink"
titleLabel.font = UIFont(name: "NotoSansCJKjp-Bold", size: 14)
titleLabel.textAlignment = .Center
titleLabel.backgroundColor = UIColor.clearColor()
titleLabel.textColor = UIColor.blackColor()
self.navigationItem.titleView = titleLabel
MEMELibAccess.sharedInstance.changeDataMode(MEME_COM_REALTIME)
// debug
//NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: "timerFired", userInfo: nil, repeats: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
// Remove Observer
MEMELibAccess.sharedInstance.removeObserver(self, forKeyPath: AppConsts.MEMELibAccess.realtimeDataKey)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// Add Observer
MEMELibAccess.sharedInstance.addObserver(self, forKeyPath: AppConsts.MEMELibAccess.realtimeDataKey, options: .New, context: nil)
}
// MARK: - KVO
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
switch keyPath! {
case AppConsts.MEMELibAccess.realtimeDataKey:
self.rtmData = (object as! MEMELibAccess).realtimeData
if (self.rtmData != nil) {
blinkSpeed = CGFloat(self.rtmData!.blinkSpeed)
self.isBlinking = (blinkSpeed > 0) ? true : false
// Comment out if eye moving left/right needed
// self.isMovingLeft = (self.rtmData!.eyeMoveLeft > 0) ? true : false
// self.isMovingRight = (self.rtmData!.eyeMoveRight > 0) ? true : false
if self.isBlinking == true
// self.isMovingLeft || self.isMovingRight
{
self.view.setNeedsLayout()
}
}
default: break
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
//print("blinkSpeed \(self.rtmData?.blinkSpeed)")
let origEyeLidSize = CGSizeMake(80, 36)
let eyeLidWidth = self.view.frame.width - 20*2
let eyeLidSize = CGSizeMake(
eyeLidWidth,
(eyeLidWidth * origEyeLidSize.height) / origEyeLidSize.width
)
let eyeLidRect = CGRectMake(
20, (CGRectGetHeight(self.view.frame) - eyeLidSize.height)*0.5,
eyeLidSize.width, eyeLidSize.height)
// まばたき
if self.isBlinking {
AudioPlayer.sharedInstance.play("click")
if self.eyeLid != nil {
self.eyeLid?.removeFromSuperlayer()
}
self.eyeLid = CAShapeLayer.eyeBlinkWithFrame(eyeLidRect, blinkSpeed: (blinkSpeed/1000) * AppConsts.EyeBlink.blinkSpeedMulti)
self.view.layer.addSublayer(self.eyeLid!)
}
// 下まぶた(常時表示)
if self.lowerEyeLid == nil {
self.lowerEyeLid = CAShapeLayer.lowerEyeWithFrame(eyeLidRect)
self.view.layer.addSublayer(self.lowerEyeLid!)
}
// めんたま (デフォは中心にくるように)
if self.centerEye != nil {
self.centerEye?.removeFromSuperlayer()
self.centerEyeInside?.removeFromSuperlayer()
}
// // Comment out if needed eye move left/right
// if self.isMovingLeft {
// self.centerEye = CAShapeLayer.moveTo("left", withFrame: eyeLidRect, speed: 0.7, outside: true)
// self.centerEyeInside = CAShapeLayer.moveTo("left", withFrame: eyeLidRect, speed: 0.7, outside: false)
//
// } else if self.isMovingRight {
// self.centerEye = CAShapeLayer.moveTo("right", withFrame: eyeLidRect, speed: 0.7, outside: true)
// self.centerEyeInside = CAShapeLayer.moveTo("right", withFrame: eyeLidRect, speed: 0.7, outside: false)
//
// } else {
self.centerEye = CAShapeLayer.centerEyeWithFrame(eyeLidRect, outside: true)
self.centerEyeInside = CAShapeLayer.centerEyeWithFrame(eyeLidRect, outside: false)
// }
// let centerEyeInset:CGFloat = 36
// let centerEyeSize = CGSizeMake(
// eyeLidSize.height - centerEyeInset*2,
// eyeLidSize.height - centerEyeInset*2
// )
// let centerEyeRect = CGRectMake(
// CGRectGetMidX(self.view.frame) - centerEyeSize.width*0.5,
// CGRectGetMidY(eyeLidRect) - centerEyeSize.height*0.5,
// centerEyeSize.width, centerEyeSize.height)
//
// self.centerEye = CAShapeLayer()
// self.centerEye?.fillColor = UIColor.blackColor().CGColor
// self.centerEye?.path = UIBezierPath(ovalInRect: centerEyeRect).CGPath
//self.centerEyeInside?.zPosition = CGFloat(-Int.max + 1)
self.centerEye?.zPosition = CGFloat(-Int.max)
self.view.layer.addSublayer(self.centerEye!)
self.view.layer.addSublayer(self.centerEyeInside!)
}
func timerFired() {
// virtually blink
self.isBlinking = !self.isBlinking
self.isMovingLeft = !self.isMovingLeft
self.view.setNeedsLayout()
}
}
|
mit
|
kentya6/Fuwari
|
Fuwari/NSMenu+Extension.swift
|
1
|
644
|
//
// NSMenu+Extension.swift
// Fuwari
//
// Created by Kengo Yokoyama on 2018/07/14.
// Copyright © 2018年 AppKnop. All rights reserved.
//
import Cocoa
extension NSMenu {
func addItem(withTitle title: String, action: Selector? = nil, target: AnyObject? = nil, representedObject: AnyObject? = nil, state: NSControl.StateValue = .off, submenu: NSMenu? = nil) {
let menuItem = NSMenuItem(title: title, action: action, keyEquivalent: "")
menuItem.target = target
menuItem.representedObject = representedObject
menuItem.state = state
menuItem.submenu = submenu
addItem(menuItem)
}
}
|
mit
|
AnthonyMDev/Nimble
|
Sources/Nimble/Matchers/SatisfyAnyOf.swift
|
20
|
3747
|
import Foundation
/// A Nimble matcher that succeeds when the actual value matches with any of the matchers
/// provided in the variable list of matchers.
public func satisfyAnyOf<T>(_ predicates: Predicate<T>...) -> Predicate<T> {
return satisfyAnyOf(predicates)
}
/// A Nimble matcher that succeeds when the actual value matches with any of the matchers
/// provided in the variable list of matchers.
public func satisfyAnyOf<T, U>(_ matchers: U...) -> Predicate<T>
where U: Matcher, U.ValueType == T {
return satisfyAnyOf(matchers.map { $0.predicate })
}
internal func satisfyAnyOf<T>(_ predicates: [Predicate<T>]) -> Predicate<T> {
return Predicate.define { actualExpression in
var postfixMessages = [String]()
var matches = false
for predicate in predicates {
let result = try predicate.satisfies(actualExpression)
if result.toBoolean(expectation: .toMatch) {
matches = true
}
postfixMessages.append("{\(result.message.expectedMessage)}")
}
var msg: ExpectationMessage
if let actualValue = try actualExpression.evaluate() {
msg = .expectedCustomValueTo(
"match one of: " + postfixMessages.joined(separator: ", or "),
"\(actualValue)"
)
} else {
msg = .expectedActualValueTo(
"match one of: " + postfixMessages.joined(separator: ", or ")
)
}
return PredicateResult(bool: matches, message: msg)
}
}
public func || <T>(left: Predicate<T>, right: Predicate<T>) -> Predicate<T> {
return satisfyAnyOf(left, right)
}
public func || <T>(left: NonNilMatcherFunc<T>, right: NonNilMatcherFunc<T>) -> Predicate<T> {
return satisfyAnyOf(left, right)
}
public func || <T>(left: MatcherFunc<T>, right: MatcherFunc<T>) -> Predicate<T> {
return satisfyAnyOf(left, right)
}
#if canImport(Darwin)
extension NMBObjCMatcher {
@objc public class func satisfyAnyOfMatcher(_ matchers: [NMBMatcher]) -> NMBPredicate {
return NMBPredicate { actualExpression in
if matchers.isEmpty {
return NMBPredicateResult(
status: NMBPredicateStatus.fail,
message: NMBExpectationMessage(
fail: "satisfyAnyOf must be called with at least one matcher"
)
)
}
var elementEvaluators = [Predicate<NSObject>]()
for matcher in matchers {
let elementEvaluator = Predicate<NSObject> { expression in
if let predicate = matcher as? NMBPredicate {
// swiftlint:disable:next line_length
return predicate.satisfies({ try expression.evaluate() }, location: actualExpression.location).toSwift()
} else {
let failureMessage = FailureMessage()
let success = matcher.matches(
// swiftlint:disable:next force_try
{ try! expression.evaluate() },
failureMessage: failureMessage,
location: actualExpression.location
)
return PredicateResult(bool: success, message: failureMessage.toExpectationMessage())
}
}
elementEvaluators.append(elementEvaluator)
}
return try satisfyAnyOf(elementEvaluators).satisfies(actualExpression).toObjectiveC()
}
}
}
#endif
|
apache-2.0
|
acn001/SwiftJSONModel
|
SwiftJSONModel/SwiftJSONModelErrorCode.swift
|
1
|
2819
|
//
// SwiftJSONModel.swift
// SWiftJSONModel
//
// @version 0.1.1
// @author Zhu Yue([email protected])
//
// The MIT License (MIT)
//
// Copyright (c) 2016 Zhu Yue
//
// 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
enum SwiftJSONModelErrorCode: Int {
// etc.
case SwiftJSONModelTypeConvertionErrorOfStringFromCString = -51
// About SwiftJSONModelObjcReflection
case SwiftJSONModelObjcPropertyCannotBeReflected = -11
case SwiftJSONModelObjcPropertyNameCannotBeReflected = -12
case SwiftJSONModelObjcPropertyTypeCannotBeReflected = -13
case SwiftJSONModelObjcNotSupportedProperty = -14
// About SwiftJSONModelNetworkHelper
case SwiftJSONModelResponseDataStructureError = -101
var description: String {
switch self {
case .SwiftJSONModelObjcPropertyCannotBeReflected:
return "SwiftJSONModelObjcReflection error: some property cannot be reflected. "
case .SwiftJSONModelObjcPropertyNameCannotBeReflected:
return "SwiftJSONModelObjcReflection error: some property name cannot be reflected. "
case .SwiftJSONModelObjcPropertyTypeCannotBeReflected:
return "SwiftJSONModelObjcReflection error: some property type cannot be reflected. "
case .SwiftJSONModelObjcNotSupportedProperty:
return "SwiftJSONModelObjcReflection error: not supported property type found. "
case .SwiftJSONModelTypeConvertionErrorOfStringFromCString:
return "Convertion error: construct object of String from CSting failed. "
case .SwiftJSONModelResponseDataStructureError:
return "Response data structure error: "
default:
return "Current error code has no description with raw value: \(rawValue). "
}
}
}
|
mit
|
ashare80/ASTextInputAccessoryView
|
Pod/Source/Extensions/String.swift
|
1
|
657
|
//
// NSString.swift
// Pods
//
// Created by Adam J Share on 12/29/15.
//
//
import Foundation
import UIKit
// MARK: + Size
public extension String {
func sizeWithFont(font: UIFont, maxWidth: CGFloat = CGFloat.max, maxHeight: CGFloat = CGFloat.max) -> CGSize {
let constraint = CGSize(width: maxWidth, height: maxHeight)
let frame = self.boundingRectWithSize(
constraint,
options:[.UsesLineFragmentOrigin , .UsesFontLeading],
attributes:[NSFontAttributeName: font],
context:nil
)
return CGSizeMake(frame.size.width, frame.size.height);
}
}
|
mit
|
twittemb/Weavy
|
Weavy/HasDisposeBag.swift
|
1
|
1097
|
//
// HasDisposeBag.swift
// Weavy
//
// Created by Thibault Wittemberg on 17-07-25.
// Copyright © 2017 Warp Factor. All rights reserved.
//
// this code had been inspired by the project: https://github.com/RxSwiftCommunity/NSObject-Rx
// Its License can be found here: ../DependenciesLicenses/RxSwiftCommunity-NSObject-Rx-License
import RxSwift
private var disposeBagContext: UInt8 = 0
/// Each HasDisposeBag offers a unique Rx DisposeBag instance
public protocol HasDisposeBag: Synchronizable {
/// a unique Rx DisposeBag instance
var disposeBag: DisposeBag { get }
}
extension HasDisposeBag {
/// The concrete DisposeBag instance
public var disposeBag: DisposeBag {
return self.synchronized {
if let disposeObject = objc_getAssociatedObject(self, &disposeBagContext) as? DisposeBag {
return disposeObject
}
let disposeObject = DisposeBag()
objc_setAssociatedObject(self, &disposeBagContext, disposeObject, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return disposeObject
}
}
}
|
mit
|
cbrentharris/swift
|
test/SILGen/enum.swift
|
2
|
6397
|
// RUN: %target-swift-frontend -parse-as-library -parse-stdlib -emit-silgen %s | FileCheck %s
enum Boolish {
case falsy
case truthy
}
// CHECK-LABEL: sil hidden @_TF4enum13Boolish_casesFT_T_
func Boolish_cases() {
// CHECK: [[BOOLISH:%[0-9]+]] = metatype $@thin Boolish.Type
// CHECK-NEXT: [[FALSY:%[0-9]+]] = enum $Boolish, #Boolish.falsy!enumelt
_ = Boolish.falsy
// CHECK-NEXT: [[BOOLISH:%[0-9]+]] = metatype $@thin Boolish.Type
// CHECK-NEXT: [[TRUTHY:%[0-9]+]] = enum $Boolish, #Boolish.truthy!enumelt
_ = Boolish.truthy
}
struct Int {}
enum Optionable {
case nought
case mere(Int)
}
// CHECK-LABEL: sil hidden [transparent] @_TFO4enum10Optionable4merefMS0_FVS_3IntS0_
// CHECK: bb0([[ARG:%.*]] : $Int, {{%.*}} : $@thin Optionable.Type):
// CHECK-NEXT: [[RES:%.*]] = enum $Optionable, #Optionable.mere!enumelt.1, [[ARG]] : $Int
// CHECK-NEXT: return [[RES]] : $Optionable
// CHECK-NEXT: }
// CHECK-LABEL: sil hidden @_TF4enum16Optionable_casesFVS_3IntT_
func Optionable_cases(x: Int) {
// CHECK: [[FN:%.*]] = function_ref @_TFO4enum10Optionable4mereFMS0_FVS_3IntS0_
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin Optionable.Type
// CHECK-NEXT: [[CTOR:%.*]] = apply [[FN]]([[METATYPE]])
// CHECK-NEXT: strong_release [[CTOR]]
_ = Optionable.mere
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin Optionable.Type
// CHECK-NEXT: [[RES:%.*]] = enum $Optionable, #Optionable.mere!enumelt.1, %0 : $Int
_ = Optionable.mere(x)
}
protocol P {}
struct S : P {}
enum AddressOnly {
case nought
case mere(P)
case phantom(S)
}
// CHECK-LABEL: sil hidden [transparent] @_TFO4enum11AddressOnly4merefMS0_FPS_1P_S0_ : $@convention(thin) (@out AddressOnly, @in P, @thin AddressOnly.Type) -> () {
// CHECK: bb0([[RET:%.*]] : $*AddressOnly, [[DATA:%.*]] : $*P, {{%.*}} : $@thin AddressOnly.Type):
// CHECK-NEXT: [[RET_DATA:%.*]] = init_enum_data_addr [[RET]] : $*AddressOnly, #AddressOnly.mere!enumelt.1 // user: %4
// CHECK-NEXT: copy_addr [take] [[DATA]] to [initialization] [[RET_DATA]] : $*P
// CHECK-NEXT: inject_enum_addr [[RET]] : $*AddressOnly, #AddressOnly.mere!enumelt.1
// CHECK: return
// CHECK-NEXT: }
// CHECK-LABEL: sil hidden @_TF4enum17AddressOnly_casesFVS_1ST_ : $@convention(thin) (S) -> ()
func AddressOnly_cases(s: S) {
// CHECK: [[FN:%.*]] = function_ref @_TFO4enum11AddressOnly4mereFMS0_FPS_1P_S0_
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin AddressOnly.Type
// CHECK-NEXT: [[CTOR:%.*]] = apply [[FN]]([[METATYPE]])
// CHECK-NEXT: strong_release [[CTOR]]
_ = AddressOnly.mere
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin AddressOnly.Type
// CHECK-NEXT: [[NOUGHT:%.*]] = alloc_stack $AddressOnly
// CHECK-NEXT: inject_enum_addr [[NOUGHT]]#1
// CHECK-NEXT: destroy_addr [[NOUGHT]]#1
// CHECK-NEXT: dealloc_stack [[NOUGHT]]#0
_ = AddressOnly.nought
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin AddressOnly.Type
// CHECK-NEXT: [[MERE:%.*]] = alloc_stack $AddressOnly
// CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[MERE]]#1
// CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = init_existential_addr [[PAYLOAD]]
// CHECK-NEXT: store %0 to [[PAYLOAD_ADDR]]
// CHECK-NEXT: inject_enum_addr [[MERE]]#1
// CHECK-NEXT: destroy_addr [[MERE]]#1
// CHECK-NEXT: dealloc_stack [[MERE]]#0
_ = AddressOnly.mere(s)
// Address-only enum vs loadable payload
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin AddressOnly.Type
// CHECK-NEXT: [[PHANTOM:%.*]] = alloc_stack $AddressOnly
// CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr %20#1 : $*AddressOnly, #AddressOnly.phantom!enumelt.1
// CHECK-NEXT: store %0 to [[PAYLOAD]]
// CHECK-NEXT: inject_enum_addr [[PHANTOM]]#1 : $*AddressOnly, #AddressOnly.phantom!enumelt.1
// CHECK-NEXT: destroy_addr [[PHANTOM]]#1
// CHECK-NEXT: dealloc_stack [[PHANTOM]]#0
_ = AddressOnly.phantom(s)
// CHECK: return
}
enum PolyOptionable<T> {
case nought
case mere(T)
}
// CHECK-LABEL: sil hidden @_TF4enum20PolyOptionable_casesurFxT_
func PolyOptionable_cases<T>(t: T) {
// CHECK: [[METATYPE:%.*]] = metatype $@thin PolyOptionable<T>.Type
// CHECK-NEXT: [[NOUGHT:%.*]] = alloc_stack $PolyOptionable<T>
// CHECK-NEXT: inject_enum_addr [[NOUGHT]]#1
// CHECK-NEXT: destroy_addr [[NOUGHT]]#1
// CHECK-NEXT: dealloc_stack [[NOUGHT]]#0
_ = PolyOptionable<T>.nought
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin PolyOptionable<T>.Type
// CHECK-NEXT: [[MERE:%.*]] = alloc_stack $PolyOptionable<T>
// CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[MERE]]#1
// CHECK-NEXT: copy_addr %0 to [initialization] [[PAYLOAD]]
// CHECK-NEXT: inject_enum_addr [[MERE]]#1
// CHECK-NEXT: destroy_addr [[MERE]]#1
// CHECK-NEXT: dealloc_stack [[MERE]]#0
_ = PolyOptionable<T>.mere(t)
// CHECK-NEXT: destroy_addr %0
// CHECK: return
}
// The substituted type is loadable and trivial here
// CHECK-LABEL: sil hidden @_TF4enum32PolyOptionable_specialized_casesFVS_3IntT_
func PolyOptionable_specialized_cases(t: Int) {
// CHECK: [[METATYPE:%.*]] = metatype $@thin PolyOptionable<Int>.Type
// CHECK-NEXT: [[NOUGHT:%.*]] = enum $PolyOptionable<Int>, #PolyOptionable.nought!enumelt
_ = PolyOptionable<Int>.nought
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin PolyOptionable<Int>.Type
// CHECK-NEXT: [[NOUGHT:%.*]] = enum $PolyOptionable<Int>, #PolyOptionable.mere!enumelt.1, %0
_ = PolyOptionable<Int>.mere(t)
// CHECK: return
}
// Regression test for a bug where temporary allocations created as a result of
// tuple implosion were not deallocated in enum constructors.
struct String { var ptr: Builtin.NativeObject }
enum Foo { case A(P, String) }
// CHECK-LABEL: sil hidden [transparent] @_TFO4enum3Foo1AfMS0_FTPS_1P_VS_6String_S0_ : $@convention(thin) (@out Foo, @in P, @owned String, @thin Foo.Type) -> () {
// CHECK: [[PAYLOAD:%.*]] = init_enum_data_addr %0 : $*Foo, #Foo.A!enumelt.1
// CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[PAYLOAD]] : $*(P, String), 0
// CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[PAYLOAD]] : $*(P, String), 1
// CHECK-NEXT: copy_addr [take] %1 to [initialization] [[LEFT]] : $*P
// CHECK-NEXT: store %2 to [[RIGHT]]
// CHECK-NEXT: inject_enum_addr %0 : $*Foo, #Foo.A!enumelt.1
// CHECK: return
// CHECK-NEXT: }
|
apache-2.0
|
liuweihaocool/iOS_06_liuwei
|
新浪微博_swift/新浪微博_swift/class/Main/Compare/View/LWPlaceholdView.swift
|
1
|
2159
|
//
// LWPlaceholdView.swift
// 新浪微博_swift
//
// Created by LiuWei on 15/12/5.
// Copyright © 2015年 liuwei. All rights reserved.
//
import UIKit
/// 自定义TextView 里面有一个站位文本,当没有内容的时候会显示出来
class LWPlaceholdView: UITextView {
/// 提供属性,让别人来设置文本
var placeholder: String? {
didSet {
placeHolderLabel.text = placeholder
placeHolderLabel.font = font
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// 实现通知方法
func textDidChange() {
placeHolderLabel.hidden = hasText()
}
override init(frame: CGRect, textContainer: NSTextContainer?) {
// 调用父类的init
super.init(frame: frame, textContainer: textContainer)
// 设置代理
NSNotificationCenter.defaultCenter().addObserver(self, selector: "textDidChange", name: UITextViewTextDidChangeNotification, object: self)
}
/// 移除通知 相当于dealloc
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
/// 懒加载 站位文本 提供label给别人访问,别人可能会做非法操作
private lazy var placeHolderLabel:UILabel = {
/// 创建label 设置属性
let label = UILabel()
label.textColor = UIColor.lightGrayColor()
label.font = self.font
/// 添加约束
self.addSubview(label)
/// 取消系统的自动约束
label.translatesAutoresizingMaskIntoConstraints = false
self.addConstraint(NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 8))
self.addConstraint(NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 5))
label.sizeToFit()
return label
}()
}
|
apache-2.0
|
crazypoo/PTools
|
Pods/CollectionViewPagingLayout/Lib/Scale/ScaleTransformViewOptions.Translation3dOptions.swift
|
1
|
1328
|
//
// ScaleTransformViewOptions.Translation3dOptions.swift
// CollectionViewPagingLayout
//
// Created by Amir on 27/03/2020.
// Copyright © 2020 Amir Khorsandi. All rights reserved.
//
import UIKit
public extension ScaleTransformViewOptions {
struct Translation3dOptions {
// MARK: Properties
/// The translates(x,y,z) ratios
/// (translateX = progress * translates.x * targetView.width)
/// (translateY = progress * translates.y * targetView.height)
/// (translateZ = progress * translates.z * targetView.width)
public var translateRatios: (CGFloat, CGFloat, CGFloat)
/// The minimum translate ratios
public var minTranslateRatios: (CGFloat, CGFloat, CGFloat)
/// The maximum translate ratios
public var maxTranslateRatios: (CGFloat, CGFloat, CGFloat)
// MARK: Lifecycle
public init(
translateRatios: (CGFloat, CGFloat, CGFloat),
minTranslateRatios: (CGFloat, CGFloat, CGFloat),
maxTranslateRatios: (CGFloat, CGFloat, CGFloat)
) {
self.translateRatios = translateRatios
self.minTranslateRatios = minTranslateRatios
self.maxTranslateRatios = maxTranslateRatios
}
}
}
|
mit
|
swiftdetut/30-UIScrollView
|
Scrollview-Tutorial/Scrollview-Tutorial/AppDelegate.swift
|
2
|
2164
|
//
// AppDelegate.swift
// Scrollview-Tutorial
//
// Created by Benjamin Herzog on 02.11.14.
// Copyright (c) 2014 Benjamin Herzog. 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:.
}
}
|
gpl-2.0
|
xcodeswift/xcproj
|
Sources/XcodeProj/Objects/Configuration/XCConfigurationList.swift
|
1
|
5755
|
import Foundation
/// This is the element for listing build configurations.
public final class XCConfigurationList: PBXObject {
// MARK: - Attributes
/// Element build configurations.
var buildConfigurationReferences: [PBXObjectReference]
/// Build configurations
public var buildConfigurations: [XCBuildConfiguration] {
set {
buildConfigurationReferences = newValue.references()
}
get {
buildConfigurationReferences.objects()
}
}
/// Element default configuration is visible.
public var defaultConfigurationIsVisible: Bool
/// Element default configuration name
public var defaultConfigurationName: String?
// MARK: - Init
/// Initializes the element with its properties.
///
/// - Parameters:
/// - bbuildConfigurations: build configurations.
/// - defaultConfigurationName: element default configuration name.
/// - defaultConfigurationIsVisible: default configuration is visible.
public init(buildConfigurations: [XCBuildConfiguration] = [],
defaultConfigurationName: String? = nil,
defaultConfigurationIsVisible: Bool = false) {
buildConfigurationReferences = buildConfigurations.references()
self.defaultConfigurationName = defaultConfigurationName
self.defaultConfigurationIsVisible = defaultConfigurationIsVisible
super.init()
}
// MARK: - Decodable
fileprivate enum CodingKeys: String, CodingKey {
case buildConfigurations
case defaultConfigurationName
case defaultConfigurationIsVisible
}
public required init(from decoder: Decoder) throws {
let objects = decoder.context.objects
let objectReferenceRepository = decoder.context.objectReferenceRepository
let container = try decoder.container(keyedBy: CodingKeys.self)
let buildConfigurationReferencesStrings: [String] = try container.decode(.buildConfigurations)
buildConfigurationReferences = buildConfigurationReferencesStrings
.map { objectReferenceRepository.getOrCreate(reference: $0, objects: objects) }
defaultConfigurationIsVisible = try container.decodeIntBool(.defaultConfigurationIsVisible)
defaultConfigurationName = try container.decodeIfPresent(.defaultConfigurationName)
try super.init(from: decoder)
}
}
// MARK: - Helpers
extension XCConfigurationList {
/// Returns the build configuration with the given name (if it exists)
///
/// - Parameter name: configuration name.
/// - Returns: build configuration if it exists.
public func configuration(name: String) -> XCBuildConfiguration? {
buildConfigurations.first(where: { $0.name == name })
}
/// Adds the default configurations, debug and release
///
/// - Returns: the created configurations.
public func addDefaultConfigurations() throws -> [XCBuildConfiguration] {
var configurations: [XCBuildConfiguration] = []
let debug = XCBuildConfiguration(name: "Debug")
reference.objects?.add(object: debug)
configurations.append(debug)
let release = XCBuildConfiguration(name: "Release")
reference.objects?.add(object: release)
configurations.append(release)
buildConfigurations.append(contentsOf: configurations)
return configurations
}
/// Returns the object with the given configuration list (project or target)
///
/// - Parameter reference: configuration list reference.
/// - Returns: target or project with the given configuration list.
public func objectWithConfigurationList() throws -> PBXObject? {
let projectObjects = try objects()
return projectObjects.projects.first(where: { $0.value.buildConfigurationListReference == reference })?.value ??
projectObjects.nativeTargets.first(where: { $0.value.buildConfigurationListReference == reference })?.value ??
projectObjects.aggregateTargets.first(where: { $0.value.buildConfigurationListReference == reference })?.value ??
projectObjects.legacyTargets.first(where: { $0.value.buildConfigurationListReference == reference })?.value
}
}
// MARK: - PlistSerializable
extension XCConfigurationList: PlistSerializable {
func plistKeyAndValue(proj _: PBXProj, reference: String) throws -> (key: CommentedString, value: PlistValue) {
var dictionary: [CommentedString: PlistValue] = [:]
dictionary["isa"] = .string(CommentedString(XCConfigurationList.isa))
dictionary["buildConfigurations"] = .array(buildConfigurationReferences
.map { configReference in
let config: XCBuildConfiguration? = configReference.getObject()
return .string(CommentedString(configReference.value, comment: config?.name))
})
dictionary["defaultConfigurationIsVisible"] = .string(CommentedString("\(defaultConfigurationIsVisible.int)"))
if let defaultConfigurationName = defaultConfigurationName {
dictionary["defaultConfigurationName"] = .string(CommentedString(defaultConfigurationName))
}
return (key: CommentedString(reference, comment: try plistComment()),
value: .dictionary(dictionary))
}
private func plistComment() throws -> String? {
let object = try objectWithConfigurationList()
if let project = object as? PBXProject {
return "Build configuration list for PBXProject \"\(project.name)\""
} else if let target = object as? PBXTarget {
return "Build configuration list for \(type(of: target).isa) \"\(target.name)\""
}
return nil
}
}
|
mit
|
lukaszwas/mcommerce-api
|
Sources/App/Models/Stripe/Models/BalanceHistoryList.swift
|
1
|
713
|
//
// BalanceHistoryList.swift
// Stripe
//
// Created by Anthony Castelli on 4/15/17.
//
//
import Foundation
import Vapor
public final class BalanceHistoryList: StripeModelProtocol {
public let object: String
public let hasMore: Bool
public let items: [BalanceTransactionItem]
public init(node: Node) throws {
self.object = try node.get("object")
self.hasMore = try node.get("has_more")
self.items = try node.get("data")
}
public func makeNode(in context: Context?) throws -> Node {
return try Node(node: [
"object": self.object,
"has_more": self.hasMore,
"data": self.items
])
}
}
|
mit
|
sergeyzenchenko/react-swift
|
ReactSwift/ReactSwift/Cartography/Edges.swift
|
5
|
2360
|
//
// Edges.swift
// Cartography
//
// Created by Robert Böhnke on 19/06/14.
// Copyright (c) 2014 Robert Böhnke. All rights reserved.
//
#if os(iOS)
import UIKit
#else
import AppKit
#endif
public enum Edges : Compound {
case Edges(View)
var properties: [Property] {
switch (self) {
case let .Edges(view):
return [
Edge.Top(view),
Edge.Leading(view),
Edge.Bottom(view),
Edge.Trailing(view)
]
}
}
}
public func inset(edges: Edges, all: Float) -> Expression<Edges> {
return inset(edges, all, all, all, all)
}
public func inset(edges: Edges, horizontal: Float, vertical: Float) -> Expression<Edges> {
return inset(edges, vertical, horizontal, vertical, horizontal)
}
public func inset(edges: Edges, top: Float, leading: Float, bottom: Float, trailing: Float) -> Expression<Edges> {
return Expression(edges, [ Coefficients(1, top), Coefficients(1, leading), Coefficients(1, -bottom), Coefficients(1, -trailing) ])
}
// MARK: Equality
public func ==(lhs: Edges, rhs: Expression<Edges>) -> [NSLayoutConstraint] {
return apply(lhs, coefficients: rhs.coefficients, to: rhs.value)
}
public func ==(lhs: Expression<Edges>, rhs: Edges) -> [NSLayoutConstraint] {
return rhs == lhs
}
public func ==(lhs: Edges, rhs: Edges) -> [NSLayoutConstraint] {
return apply(lhs, to: rhs)
}
// MARK: Inequality
public func <=(lhs: Edges, rhs: Edges) -> [NSLayoutConstraint] {
return apply(lhs, to: rhs, relation: NSLayoutRelation.LessThanOrEqual)
}
public func >=(lhs: Edges, rhs: Edges) -> [NSLayoutConstraint] {
return apply(lhs, to: rhs, relation: NSLayoutRelation.GreaterThanOrEqual)
}
public func <=(lhs: Edges, rhs: Expression<Edges>) -> [NSLayoutConstraint] {
return apply(lhs, coefficients: rhs.coefficients, to: rhs.value, relation: NSLayoutRelation.LessThanOrEqual)
}
public func <=(lhs: Expression<Edges>, rhs: Edges) -> [NSLayoutConstraint] {
return rhs >= lhs
}
public func >=(lhs: Edges, rhs: Expression<Edges>) -> [NSLayoutConstraint] {
return apply(lhs, coefficients: rhs.coefficients, to: rhs.value, relation: NSLayoutRelation.GreaterThanOrEqual)
}
public func >=(lhs: Expression<Edges>, rhs: Edges) -> [NSLayoutConstraint] {
return rhs <= lhs
}
|
mit
|
FabrizioBrancati/BFKit-Swift
|
Sources/BFKit/Apple/UIKit/UIColor+Extensions.swift
|
1
|
16571
|
//
// UIColor+Extensions.swift
// BFKit-Swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 - 2019 Fabrizio Brancati.
//
// 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
#if canImport(UIKit)
import UIKit
#elseif canImport(AppKit)
import AppKit
#endif
// MARK: - Global functions
/// Create an UIColor or NSColor in format RGBA.
///
/// - Parameters:
/// - red: Red value.
/// - green: Green value.
/// - blue: Blue value.
/// - alpha: Alpha value.
/// - Returns: Returns the created UIColor or NSColor.
public func RGBA(_ red: Int, _ green: Int, _ blue: Int, _ alpha: Float) -> Color {
#if canImport(UIKit)
return Color(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: CGFloat(alpha))
#elseif canImport(AppKit)
return Color(calibratedRed: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: CGFloat(alpha))
#endif
}
/// Create an UIColor or NSColor in format ARGB.
///
/// - Parameters:
/// - alpha: Alpha value.
/// - red: Red value.
/// - green: Green value.
/// - blue: Blue value.
/// - Returns: Returns the created UIColor or NSColor.
public func ARGB( _ alpha: Float, _ red: Int, _ green: Int, _ blue: Int) -> Color {
RGBA(red, green, blue, alpha)
}
/// Create an UIColor or NSColor in format RGB.
///
/// - Parameters:
/// - red: Red value.
/// - green: Green value.
/// - blue: Blue value.
/// - Returns: Returns the created UIColor or NSColor.
public func RGB(_ red: Int, _ green: Int, _ blue: Int) -> Color {
#if canImport(UIKit)
return Color(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
#elseif canImport(AppKit)
return Color(calibratedRed: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
#endif
}
// MARK: - UIColor or NSColor extension
/// This extesion adds some useful functions to UIColor or NSColor.
public extension Color {
// MARK: - Variables
#if canImport(UIKit)
/// RGB properties: red.
var redComponent: CGFloat {
guard canProvideRGBComponents(), let component = cgColor.__unsafeComponents else {
return 0.0
}
return component[0]
}
/// RGB properties: green.
var greenComponent: CGFloat {
guard canProvideRGBComponents(), let component = cgColor.__unsafeComponents else {
return 0.0
}
guard cgColor.colorSpace?.model == CGColorSpaceModel.monochrome else {
return component[1]
}
return component[0]
}
/// RGB properties: blue.
var blueComponent: CGFloat {
guard canProvideRGBComponents(), let component = cgColor.__unsafeComponents else {
return 0.0
}
guard cgColor.colorSpace?.model == CGColorSpaceModel.monochrome else {
return component[2]
}
return component[0]
}
/// RGB properties: white.
var whiteComponent: CGFloat {
guard cgColor.colorSpace?.model == CGColorSpaceModel.monochrome, let component = cgColor.__unsafeComponents else {
return 0.0
}
return component[0]
}
#endif
/// RGB properties: luminance.
var luminance: CGFloat {
if canProvideRGBComponents() {
var red: CGFloat = 0.0, green: CGFloat = 0.0, blue: CGFloat = 0.0, alpha: CGFloat = 0.0
#if canImport(UIKit)
getRed(&red, green: &green, blue: &blue, alpha: &alpha)
#elseif canImport(AppKit)
if colorSpace.colorSpaceModel == .rgb {
getRed(&red, green: &green, blue: &blue, alpha: &alpha)
} else if colorSpace.colorSpaceModel == .gray {
var white: CGFloat = 0.0
getWhite(&white, alpha: &alpha)
red = white
green = white
blue = white
}
#endif
return red * 0.2126 + green * 0.7152 + blue * 0.0722
}
return 0.0
}
/// RGBA properties: alpha.
var alpha: CGFloat {
return cgColor.alpha
}
/// HSB properties: hue.
var hue: CGFloat {
if canProvideRGBComponents() {
var hue: CGFloat = 0.0, saturation: CGFloat = 0.0, brightness: CGFloat = 0.0, alpha: CGFloat = 0.0
getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
return hue
}
return 0.0
}
/// HSB properties: saturation.
var saturation: CGFloat {
if canProvideRGBComponents() {
var hue: CGFloat = 0.0, saturation: CGFloat = 0.0, brightness: CGFloat = 0.0, alpha: CGFloat = 0.0
getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
return saturation
}
return 0.0
}
/// HSB properties: brightness.
var brightness: CGFloat {
if canProvideRGBComponents() {
var hue: CGFloat = 0.0, saturation: CGFloat = 0.0, brightness: CGFloat = 0.0, alpha: CGFloat = 0.0
getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
return brightness
}
return 0.0
}
/// Returns the HEX string from UIColor or NSColor.
var hex: String {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 0.0
getRed(&red, green: &green, blue: &blue, alpha: &alpha)
let redInt = (Int)(red * 255)
let greenInt = (Int)(green * 255)
let blueInt = (Int)(blue * 255)
let rgb: Int = redInt << 16 | greenInt << 8 | blueInt << 0
return String(format: "#%06x", rgb)
}
// MARK: - Functions
/// Create a color from HEX with alpha.
///
/// - Parameters:
/// - hex: HEX value.
/// - alpha: Alpha value.
convenience init(hex: Int, alpha: CGFloat = 1.0) {
#if canImport(UIKit)
self.init(red: CGFloat(((hex & 0xFF0000) >> 16)) / 255.0, green: CGFloat(((hex & 0xFF00) >> 8)) / 255.0, blue: CGFloat((hex & 0xFF)) / 255.0, alpha: alpha)
#elseif canImport(AppKit)
self.init(calibratedRed: CGFloat(((hex & 0xFF0000) >> 16)) / 255.0, green: CGFloat(((hex & 0xFF00) >> 8)) / 255.0, blue: CGFloat((hex & 0xFF)) / 255.0, alpha: alpha)
#endif
}
/// Create a color from a HEX string.
/// It supports the following type:
/// - #ARGB, ARGB if alphaFirst is true. #RGBA, RGBA if alphaFirst is false.
/// - #ARGB.
/// - #RRGGBB.
/// - #AARRGGBB, AARRGGBB if alphaFirst is true. #RRGGBBAA, RRGGBBAA if firstIsAlpha is false.
///
/// - Parameters:
/// - hexString: HEX string.
/// - alphaFirst: Set it to true if alpha value is the first in the HEX string. If alpha value is the last one, set it to false. Default is false.
convenience init(hex: String, alphaFirst: Bool = false) {
let colorString: String = hex.replacingOccurrences(of: "#", with: "").uppercased()
var alpha: CGFloat = 1.0, red: CGFloat = 0.0, green: CGFloat = 0.0, blue: CGFloat = 0.0
switch colorString.count {
case 3: /// RGB
alpha = 1.0
red = Color.colorComponent(fromString: colorString, range: 0..<1)
green = Color.colorComponent(fromString: colorString, range: 1..<2)
blue = Color.colorComponent(fromString: colorString, range: 2..<3)
case 4: /// ARGB if alphaFirst is true, otherwise RGBA.
if alphaFirst {
alpha = Color.colorComponent(fromString: colorString, range: 0..<1)
red = Color.colorComponent(fromString: colorString, range: 1..<2)
green = Color.colorComponent(fromString: colorString, range: 2..<3)
blue = Color.colorComponent(fromString: colorString, range: 3..<4)
} else {
red = Color.colorComponent(fromString: colorString, range: 0..<1)
green = Color.colorComponent(fromString: colorString, range: 1..<2)
blue = Color.colorComponent(fromString: colorString, range: 2..<3)
alpha = Color.colorComponent(fromString: colorString, range: 3..<4)
}
case 6: /// RRGGBB
alpha = 1.0
red = Color.colorComponent(fromString: colorString, range: 0..<2)
green = Color.colorComponent(fromString: colorString, range: 2..<4)
blue = Color.colorComponent(fromString: colorString, range: 4..<6)
case 8: /// AARRGGBB if alphaFirst is true, otherwise RRGGBBAA.
if alphaFirst {
alpha = Color.colorComponent(fromString: colorString, range: 0..<2)
red = Color.colorComponent(fromString: colorString, range: 2..<4)
green = Color.colorComponent(fromString: colorString, range: 4..<6)
blue = Color.colorComponent(fromString: colorString, range: 6..<8)
} else {
red = Color.colorComponent(fromString: colorString, range: 0..<2)
green = Color.colorComponent(fromString: colorString, range: 2..<4)
blue = Color.colorComponent(fromString: colorString, range: 4..<6)
alpha = Color.colorComponent(fromString: colorString, range: 6..<8)
}
default:
break
}
#if canImport(UIKit)
self.init(red: red, green: green, blue: blue, alpha: alpha)
#elseif canImport(AppKit)
self.init(calibratedRed: red, green: green, blue: blue, alpha: alpha)
#endif
}
/// A good contrasting color, it will be either black or white.
///
/// - Returns: Returns the color.
func contrasting() -> Color {
luminance > 0.5 ? Color.black : Color.white
}
/// A complementary color that should look good.
///
/// - Returns: Returns the color.
func complementary() -> Color? {
var hue: CGFloat = 0.0, saturation: CGFloat = 0.0, brightness: CGFloat = 0.0, alpha: CGFloat = 0.0
#if canImport(UIKit)
guard getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) else {
return nil
}
#elseif canImport(AppKit)
getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
#endif
hue += 180
if hue > 360 {
hue -= 360
}
return Color(hue: hue, saturation: saturation, brightness: brightness, alpha: alpha)
}
/// Check if the color is in RGB format.
///
/// - Returns: Returns if the color is in RGB format.
func canProvideRGBComponents() -> Bool {
guard let colorSpace = cgColor.colorSpace else {
return false
}
switch colorSpace.model {
case CGColorSpaceModel.rgb, CGColorSpaceModel.monochrome:
return true
default:
return false
}
}
/// Returns the color component from the string.
///
/// - Parameters:
/// - fromString: String to convert.
/// - start: Component start index.
/// - lenght: Component lenght.
/// - Returns: Returns the color component from the string.
private static func colorComponent(fromString string: String, range: Range<Int>) -> CGFloat {
let substring: String = string.substring(with: range)
let fullHex = (range.upperBound - range.lowerBound) == 2 ? substring : "\(substring)\(substring)"
var hexComponent: CUnsignedInt = 0
Scanner(string: fullHex).scanHexInt32(&hexComponent)
return CGFloat(hexComponent) / 255.0
}
/// Create a random color.
///
/// - Parameter alpha: Alpha value.
/// - Returns: Returns the UIColor or NSColor instance.
static func random(alpha: CGFloat = 1.0) -> Color {
let red = Int.random(in: 0...255)
let green = Int.random(in: 0...255)
let blue = Int.random(in: 0...255)
return Color(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: alpha)
}
/// Create an UIColor or NSColor from a given string. Example: "blue" or hex string.
///
/// - Parameter color: String with color.
/// - Returns: Returns the created UIColor or NSColor.
static func color(string color: String) -> Color {
if color.count >= 3 {
if Color.responds(to: Selector(color.lowercased() + "Color")) {
return convertColor(string: color)
} else {
return Color(hex: color)
}
} else {
return Color.black
}
}
#if canImport(UIKit)
/// Create an UIColor from a given string like "blue" or an hex string.
///
/// - Parameter color: String with color.
convenience init(string color: String) {
if UIColor.responds(to: Selector(color.lowercased() + "Color")) {
self.init(cgColor: UIColor.convertColor(string: color).cgColor)
} else {
self.init(hex: color)
}
}
#elseif canImport(AppKit)
/// Create a NSColor from a given string like "blue" or an hex string.
///
/// - Parameter color: String with color.
convenience init?(string color: String) {
if NSColor.responds(to: Selector(color.lowercased() + "Color")) {
self.init(cgColor: NSColor.convertColor(string: color).cgColor)
} else {
self.init(hex: color)
}
}
#endif
/// Used the retrive the color from the string color ("blue" or "red").
///
/// - Parameter color: String with the color.
/// - Returns: Returns the created UIColor or NSColor.
private static func convertColor(string color: String) -> Color {
let color = color.lowercased()
switch color {
case "black":
return Color.black
case "darkgray":
return Color.darkGray
case "lightgray":
return Color.lightGray
case "white":
return Color.white
case "gray":
return Color.gray
case "red":
return Color.red
case "green":
return Color.green
case "blue":
return Color.blue
case "cyan":
return Color.cyan
case "yellow":
return Color.yellow
case "magenta":
return Color.magenta
case "orange":
return Color.orange
case "purple":
return Color.purple
case "brown":
return Color.brown
case "clear":
return Color.clear
default:
return Color.clear
}
}
/// Creates and returns a color object that has the same color space and component values as the given color, but has the specified alpha component.
///
/// - Parameters:
/// - color: UIColor or NSColor value.
/// - alpha: Alpha value.
/// - Returns: Returns an UIColor or NSColor instance.
static func color(color: Color, alpha: CGFloat) -> Color {
color.withAlphaComponent(alpha)
}
}
|
mit
|
uber/rides-ios-sdk
|
source/UberCoreTests/UberMocks.swift
|
1
|
4792
|
//
// UberMocks.swift
// UberCoreTests
//
// 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.
@testable import UberCore
class LoginManagerPartialMock: LoginManager {
var executeLoginClosure: ((AuthenticationCompletionHandler?) -> ())?
@objc public override func login(requestedScopes scopes: [UberScope], presentingViewController: UIViewController? = nil, completion: AuthenticationCompletionHandler? = nil) {
executeLoginClosure?(completion)
}
}
@objc class LoginManagingProtocolMock: NSObject, LoginManaging {
var loginClosure: (([UberScope], UIViewController?, ((_ accessToken: AccessToken?, _ error: NSError?) -> Void)?) -> Void)?
var openURLClosure: ((UIApplication, URL, String?, Any?) -> Bool)?
var didBecomeActiveClosure: (() -> ())?
var willEnterForegroundClosure: (() -> ())?
var backingManager: LoginManaging?
init(loginManaging: LoginManaging? = nil) {
backingManager = loginManaging
super.init()
}
func login(requestedScopes scopes: [UberScope], presentingViewController: UIViewController?, completion: ((_ accessToken: AccessToken?, _ error: NSError?) -> Void)?) {
if let closure = loginClosure {
closure(scopes, presentingViewController, completion)
} else if let manager = backingManager {
manager.login(requestedScopes: scopes, presentingViewController: presentingViewController, completion: completion)
}
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any?) -> Bool {
if let closure = openURLClosure {
return closure(application, url, sourceApplication, annotation)
} else if let manager = backingManager {
return manager.application(application, open: url, sourceApplication: sourceApplication, annotation: annotation)
} else {
return false
}
}
@available(iOS 9.0, *)
public func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool {
let sourceApplication = options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String
let annotation = options[.annotation] as Any?
return application(app, open: url, sourceApplication: sourceApplication, annotation: annotation)
}
func applicationDidBecomeActive() {
if let closure = didBecomeActiveClosure {
closure()
} else if let manager = backingManager {
manager.applicationDidBecomeActive()
}
}
func applicationWillEnterForeground() {
if let closure = willEnterForegroundClosure {
closure()
} else {
backingManager?.applicationWillEnterForeground()
}
}
}
class RidesNativeAuthenticatorPartialStub: BaseAuthenticator {
var consumeResponseCompletionValue: (AccessToken?, NSError?)?
override func consumeResponse(url: URL, completion: AuthenticationCompletionHandler?) {
completion?(consumeResponseCompletionValue?.0, consumeResponseCompletionValue?.1)
}
}
class EatsNativeAuthenticatorPartialStub: BaseAuthenticator {
var consumeResponseCompletionValue: (AccessToken?, NSError?)?
override func consumeResponse(url: URL, completion: AuthenticationCompletionHandler?) {
completion?(consumeResponseCompletionValue?.0, consumeResponseCompletionValue?.1)
}
}
class ImplicitAuthenticatorPartialStub: ImplicitGrantAuthenticator {
var consumeResponseCompletionValue: (AccessToken?, NSError?)?
override func consumeResponse(url: URL, completion: AuthenticationCompletionHandler?) {
completion?(consumeResponseCompletionValue?.0, consumeResponseCompletionValue?.1)
}
}
|
mit
|
ncalexan/firefox-ios
|
XCUITests/FindInPageTest.swift
|
2
|
4240
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import XCTest
class FindInPageTests: BaseTestCase {
var navigator: Navigator!
var app: XCUIApplication!
override func setUp() {
super.setUp()
app = XCUIApplication()
navigator = createScreenGraph(app).navigator(self)
}
override func tearDown() {
super.tearDown()
}
private func openFindInPageFromMenu() {
navigator.goto(BrowserTabMenu)
let collectionViewsQuery = app.collectionViews
waitforExistence(collectionViewsQuery.cells["Find In Page"])
collectionViewsQuery.cells["Find In Page"].tap()
XCTAssertTrue(app.textFields[""].exists)
}
func testFindFromMenu() {
openFindInPageFromMenu()
// Enter some text to start finding
app.textFields[""].typeText("Book")
// Once there are matches, test previous/next buttons
waitforExistence(app.staticTexts["1/5"])
XCTAssertTrue(app.staticTexts["1/5"].exists)
let nextInPageResultButton = app.buttons["Next in-page result"]
nextInPageResultButton.tap()
waitforExistence(app.staticTexts["2/5"])
XCTAssertTrue(app.staticTexts["2/5"].exists)
nextInPageResultButton.tap()
waitforExistence(app.staticTexts["3/5"])
XCTAssertTrue(app.staticTexts["3/5"].exists)
let previousInPageResultButton = app.buttons["Previous in-page result"]
previousInPageResultButton.tap()
waitforExistence(app.staticTexts["2/5"])
XCTAssertTrue(app.staticTexts["2/5"].exists)
previousInPageResultButton.tap()
waitforExistence(app.staticTexts["1/5"])
XCTAssertTrue(app.staticTexts["1/5"].exists)
// Tapping on close dismisses the search bar
app.buttons["Done"].tap()
waitforNoExistence(app.textFields["Book"])
}
func testQueryWithNoMatches() {
openFindInPageFromMenu()
// Try to find text which does not match and check that there are not results
app.textFields[""].typeText("foo")
waitforExistence(app.staticTexts["0/0"])
XCTAssertTrue(app.staticTexts["0/0"].exists, "There should not be any matches")
}
func testBarDissapearsWhenReloading() {
openFindInPageFromMenu()
// Before reloading, it is necessary to hide the keyboard
app.textFields["url"].tap()
app.textFields["address"].typeText("\n")
// Once the page is reloaded the search bar should not appear
waitforNoExistence(app.textFields[""])
XCTAssertFalse(app.textFields[""].exists)
}
func testBarDissapearsWhenOpeningTabsTray() {
openFindInPageFromMenu()
// Going to tab tray and back to the website hides the search field.
navigator.nowAt(BrowserTab)
navigator.goto(TabTray)
waitforExistence(app.collectionViews.cells["The Book of Mozilla"])
app.collectionViews.cells["The Book of Mozilla"].tap()
XCTAssertFalse(app.textFields[""].exists)
}
// func testFindFromSelection() {
// navigator.goto(BrowserTab)
// let textToFind = "from"
//
// // Long press on the word to be found
// waitforExistence(app.webViews.staticTexts[textToFind])
// let stringToFind = app.webViews.staticTexts.matching(identifier: textToFind)
// let firstStringToFind = stringToFind.element(boundBy: 0)
// firstStringToFind.press(forDuration: 5)
//
// // Find in page is correctly launched, bar with text pre-filled and the buttons to find next and previous
// waitforExistence(app.menuItems["Find in Page"])
// app.menuItems["Find in Page"].tap()
// waitforExistence(app.textFields[textToFind])
// XCTAssertTrue(app.textFields[textToFind].exists, "The bar does not appear with the text selected to be found")
// XCTAssertTrue(app.buttons["Previous in-page result"].exists, "Find previus button exists")
// XCTAssertTrue(app.buttons["Next in-page result"].exists, "Find next button exists")
// }
}
|
mpl-2.0
|
overtake/TelegramSwift
|
Telegram-Mac/QuickLookPreview.swift
|
1
|
6911
|
//
// QuickLookPreview.swift
// Telegram-Mac
//
// Created by keepcoder on 19/10/2016.
// Copyright © 2016 Telegram. All rights reserved.
//
import Cocoa
import SwiftSignalKit
import TelegramCore
import Postbox
import TGUIKit
import Quartz
import Foundation
private class QuickLookPreviewItem : NSObject, QLPreviewItem {
let media:Media
let path:String
init(with media:Media, path:String, ext:String = "txt") {
self.path = path + "." + ext
self.media = media
do {
try? FileManager.default.linkItem(atPath: path, toPath: self.path )
}
}
var previewItemURL: URL! {
return URL(fileURLWithPath: path)
}
var previewItemTitle: String! {
if let media = media as? TelegramMediaFile {
return media.fileName ?? strings().quickLookPreview
}
return strings().quickLookPreview
}
}
fileprivate var preview:QuickLookPreview = {
return QuickLookPreview()
}()
class QuickLookPreview : NSObject, QLPreviewPanelDelegate, QLPreviewPanelDataSource {
private var panel:QLPreviewPanel!
private weak var delegate:InteractionContentViewProtocol?
private var item:QuickLookPreviewItem!
private var context: AccountContext!
private var media:Media!
private var ready:Promise<(String?,String?)> = Promise()
private let disposable:MetaDisposable = MetaDisposable()
private let resourceDisposable:MetaDisposable = MetaDisposable()
private var stableId:ChatHistoryEntryId?
override init() {
super.init()
}
public func show(context: AccountContext, with media:Media, stableId:ChatHistoryEntryId?, _ delegate:InteractionContentViewProtocol? = nil) {
self.context = context
self.media = media
self.delegate = delegate
self.stableId = stableId
panel = QLPreviewPanel.shared()
var mimeType:String = "image/jpeg"
var fileResource:TelegramMediaResource?
var fileName:String? = nil
var forceExtension: String? = nil
let signal:Signal<(String?, String?), NoError>
if let file = media as? TelegramMediaFile {
fileResource = file.resource
mimeType = file.mimeType
fileName = file.fileName
if let ext = fileName?.nsstring.pathExtension, !ext.isEmpty {
forceExtension = ext
}
signal = copyToDownloads(file, postbox: context.account.postbox) |> map { path in
if let path = path {
return (Optional(path.nsstring.deletingPathExtension), Optional(path.nsstring.pathExtension))
} else {
return (nil, nil)
}
}
} else if let image = media as? TelegramMediaImage {
fileResource = largestImageRepresentation(image.representations)?.resource
if let fileResource = fileResource {
signal = combineLatest(context.account.postbox.mediaBox.resourceData(fileResource), resourceType(mimeType: mimeType))
|> mapToSignal({ (data) -> Signal<(String?,String?), NoError> in
return .single((data.0.path, forceExtension ?? data.1))
}) |> deliverOnMainQueue
} else {
signal = .complete()
}
} else {
signal = .complete()
}
self.ready.set(signal |> deliverOnMainQueue)
disposable.set(ready.get().start(next: { [weak self] (path,ext) in
if let strongSelf = self, let path = path {
var ext:String? = ext
if ext == nil || ext == "*" {
ext = fileName?.nsstring.pathExtension
}
if let ext = ext {
let item = QuickLookPreviewItem(with: strongSelf.media, path:path, ext:ext)
if ext == "pkpass" || !FastSettings.openInQuickLook(ext) {
NSWorkspace.shared.openFile(item.path)
return
}
strongSelf.item = item
RunLoop.current.add(Timer.scheduledTimer(timeInterval: 0, target: strongSelf, selector: #selector(strongSelf.openPanelInRunLoop), userInfo: nil, repeats: false), forMode: RunLoop.Mode.modalPanel)
}
}
}))
}
@objc func openPanelInRunLoop() {
panel.updateController()
if !isOpened() {
panel.makeKeyAndOrderFront(nil)
} else {
panel.currentPreviewItemIndex = 0
}
}
func isOpened() -> Bool {
return QLPreviewPanel.sharedPreviewPanelExists() && QLPreviewPanel.shared().isVisible
}
public static var current:QuickLookPreview! {
return preview
}
deinit {
disposable.dispose()
resourceDisposable.dispose()
}
func previewPanel(_ panel: QLPreviewPanel!, previewItemAt index: Int) -> QLPreviewItem! {
return item
}
func numberOfPreviewItems(in panel: QLPreviewPanel!) -> Int {
return 1
}
func previewPanel(_ panel: QLPreviewPanel!, handle event: NSEvent!) -> Bool {
return true
}
override class func endPreviewPanelControl(_ panel: QLPreviewPanel!) {
var bp = 0
bp += 1
}
func previewPanel(_ panel: QLPreviewPanel!, sourceFrameOnScreenFor item: QLPreviewItem!) -> NSRect {
if let stableId = stableId {
let view:NSView? = delegate?.contentInteractionView(for: stableId, animateIn: false)
if let view = view, let window = view.window {
// let tframe = view.frame
return window.convertToScreen(view.convert(view.bounds, to: nil))
}
}
return NSZeroRect
}
func previewPanel(_ panel: QLPreviewPanel!, transitionImageFor item: QLPreviewItem!, contentRect: UnsafeMutablePointer<NSRect>!) -> Any! {
if let stableId = stableId {
let view:NSView? = delegate?.contentInteractionView(for: stableId, animateIn: true)
if let view = view?.copy() as? View, let contents = view.layer?.contents {
return NSImage(cgImage: contents as! CGImage, size: view.frame.size)
}
}
return nil //fake
}
func hide() -> Void {
if isOpened() {
panel.orderOut(nil)
}
self.context = nil
self.media = nil
self.stableId = nil
self.disposable.set(nil)
self.resourceDisposable.set(nil)
}
}
|
gpl-2.0
|
AirHelp/Mimus
|
Tests/MimusExamples/Test Helpers/AuthenticationManager.swift
|
1
|
224
|
//
// Copyright (©) 2017 AirHelp. All rights reserved.
//
import Foundation
protocol AuthenticationManager {
func setup()
func beginAuthentication(with email: String, password: String, options: [String: Any])
}
|
mit
|
BBBInc/AlzPrevent-ios
|
researchline/AppDelegate.swift
|
1
|
9184
|
//
// AppDelegate.swift
//
// Created by riverleo on 2015. 11. 8..
// Copyright © 2015년 bbb. All rights reserved.
//
import UIKit
import CoreData
import Alamofire
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var deviceToken: String?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let deviceToken = Constants.userDefaults.stringForKey("deviceToken")
if(deviceToken != nil){
Alamofire.request(.POST, Constants.token,
parameters: [
"deviceKey": Constants.deviceKey,
"deviceType": Constants.deviceType,
"token": deviceToken!
])
.responseJSON { (response) -> Void in
debugPrint(response)
}
}
var storyboard = UIStoryboard(name: "TabBar", bundle: nil)
self.window?.rootViewController = storyboard.instantiateInitialViewController()
if Constants.signKey() == "" || Constants.registerStep() == Constants.STEP_READY {
storyboard = UIStoryboard(name: "Welcome", bundle: nil)
self.window?.rootViewController = storyboard.instantiateInitialViewController()
} else if Constants.registerStep() == Constants.STEP_REGISTER {
storyboard = UIStoryboard(name: "Session", bundle: nil)
self.window?.rootViewController = storyboard.instantiateViewControllerWithIdentifier("AdditionalNavigationController")
} else if Constants.registerStep() == Constants.STEP_EMAIL_VERIFICATION {
storyboard = UIStoryboard(name: "Session", bundle: nil)
self.window?.rootViewController = storyboard.instantiateViewControllerWithIdentifier("EmailVerificationNavigationController")
}
self.window!.makeKeyAndVisible()
let settings = UIUserNotificationSettings(forTypes: [.Sound, .Alert, .Badge], categories: nil)
application.registerForRemoteNotifications()
application.registerUserNotificationSettings(settings)
return true
}
// MARK: Notification Methods
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let deviceTokenString = "\(deviceToken)"
.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString:"<>"))
.stringByReplacingOccurrencesOfString(" ", withString: "")
self.deviceToken = deviceTokenString
print(deviceToken)
Constants.userDefaults.setObject(deviceTokenString, forKey: "deviceToken")
Alamofire.request(.POST, Constants.token,
parameters: [
"deviceKey": Constants.deviceKey,
"deviceType": Constants.deviceType,
"token": deviceTokenString
])
.responseJSON { (response) -> Void in
debugPrint(response)
}
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
debugPrint(error)
}
// MARK: Life Cycle Methods
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.bbb.researchline" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("researchline", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
|
bsd-3-clause
|
fgengine/quickly
|
Quickly/Views/Stackbar/QStackbar.swift
|
1
|
15581
|
//
// Quickly
//
open class QStackbar : QView {
public enum DisplayMode {
case `default`
case onlyBottom
}
public var displayMode: DisplayMode = .default {
didSet(oldValue) {
if self.displayMode != oldValue {
self.setNeedsUpdateConstraints()
}
}
}
public var edgeInsets: UIEdgeInsets = UIEdgeInsets() {
didSet(oldValue) {
if self.edgeInsets != oldValue {
self.setNeedsUpdateConstraints()
}
}
}
public var contentSize: CGFloat = 50 {
didSet(oldValue) {
if self.contentSize != oldValue {
self.setNeedsUpdateConstraints()
}
}
}
public var leftViewsOffset: CGFloat = 0 {
didSet(oldValue) {
if self.leftViewsOffset != oldValue {
self.setNeedsUpdateConstraints()
}
}
}
public var leftViewsSpacing: CGFloat {
set(value) { self._leftView.spacing = value }
get { return self._leftView.spacing }
}
public var leftViews: [UIView] {
set(value) {
if self._leftView.views != value {
self._leftView.views = value
self.setNeedsUpdateConstraints()
}
}
get { return self._leftView.views }
}
public var centerViewsSpacing: CGFloat {
set(value) { self._centerView.spacing = value }
get { return self._centerView.spacing }
}
public var centerViews: [UIView] {
set(value) {
if self._centerView.views != value {
self._centerView.views = value
self.setNeedsUpdateConstraints()
}
}
get { return self._centerView.views }
}
public var rightViewsOffset: CGFloat = 0 {
didSet(oldValue) {
if self.rightViewsOffset != oldValue {
self.setNeedsUpdateConstraints()
}
}
}
public var rightViewsSpacing: CGFloat {
set(value) { self._rightView.spacing = value }
get { return self._rightView.spacing }
}
public var rightViews: [UIView] {
set(value) {
if self._rightView.views != value {
self._rightView.views = value
self.setNeedsUpdateConstraints()
}
}
get { return self._rightView.views }
}
public var bottomView: UIView? {
willSet {
guard let view = self.bottomView else { return }
view.removeFromSuperview()
self.setNeedsUpdateConstraints()
}
didSet {
guard let view = self.bottomView else { return }
view.translatesAutoresizingMaskIntoConstraints = false
self.insertSubview(view, at: 0)
self.setNeedsUpdateConstraints()
}
}
public var backgroundView: UIView? {
willSet {
guard let view = self.backgroundView else { return }
view.removeFromSuperview()
self.setNeedsUpdateConstraints()
}
didSet {
guard let view = self.backgroundView else { return }
view.translatesAutoresizingMaskIntoConstraints = false
self.insertSubview(view, at: 0)
self.setNeedsUpdateConstraints()
}
}
public var separatorView: UIView? {
willSet {
guard let view = self.separatorView else { return }
self._separatorConstraint = nil
view.removeFromSuperview()
self.setNeedsUpdateConstraints()
}
didSet {
guard let view = self.separatorView else { return }
view.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(view)
self._separatorConstraint = NSLayoutConstraint(
item: view,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: self.separatorHeight
)
self.setNeedsUpdateConstraints()
}
}
public var separatorHeight: CGFloat = 1 {
didSet(oldValue) {
if self.separatorHeight != oldValue {
if let constraint = self._separatorConstraint {
constraint.constant = self.separatorHeight
}
}
}
}
private var _contentView: UIView!
private var _leftView: WrapView!
private var _centerView: WrapView!
private var _rightView: WrapView!
private var _constraints: [NSLayoutConstraint] = [] {
willSet { self.removeConstraints(self._constraints) }
didSet { self.addConstraints(self._constraints) }
}
private var _contentConstraints: [NSLayoutConstraint] = [] {
willSet { self._contentView.removeConstraints(self._contentConstraints) }
didSet { self._contentView.addConstraints(self._contentConstraints) }
}
private var _separatorConstraint: NSLayoutConstraint? {
willSet {
guard let view = self.separatorView, let constraint = self._separatorConstraint else { return }
view.removeConstraint(constraint)
}
didSet {
guard let view = self.separatorView, let constraint = self._separatorConstraint else { return }
view.addConstraint(constraint)
}
}
public required init() {
super.init(
frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50)
)
}
public required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func setup() {
super.setup()
self.backgroundColor = UIColor.white
self._contentView = UIView(frame: self.bounds)
self._contentView.translatesAutoresizingMaskIntoConstraints = false
self._contentView.backgroundColor = UIColor.clear
self.addSubview(self._contentView)
self._leftView = WrapView(frame: self.bounds)
self._leftView.setContentCompressionResistancePriority(.defaultHigh , for: .horizontal)
self._contentView.addSubview(self._leftView)
self._centerView = WrapView(frame: self.bounds)
self._centerView.setContentCompressionResistancePriority(.defaultLow , for: .horizontal)
self._contentView.addSubview(self._centerView)
self._rightView = WrapView(frame: self.bounds)
self._rightView.setContentCompressionResistancePriority(.defaultHigh , for: .horizontal)
self._contentView.addSubview(self._rightView)
}
open override func updateConstraints() {
super.updateConstraints()
var constraints: [NSLayoutConstraint] = []
if let backgroundView = self.backgroundView {
constraints.append(contentsOf: [
backgroundView.topLayout == self.topLayout,
backgroundView.leadingLayout == self.leadingLayout,
backgroundView.trailingLayout == self.trailingLayout,
backgroundView.bottomLayout == self.bottomLayout
])
}
if let separatorView = self.separatorView {
constraints.append(contentsOf: [
separatorView.topLayout == self.bottomLayout,
separatorView.leadingLayout == self.leadingLayout,
separatorView.trailingLayout == self.trailingLayout
])
}
switch self.displayMode {
case .default:
constraints.append(contentsOf: [
self._contentView.topLayout == self.topLayout.offset(self.edgeInsets.top),
self._contentView.leadingLayout == self.leadingLayout.offset(self.edgeInsets.left),
self._contentView.trailingLayout == self.trailingLayout.offset(-self.edgeInsets.right)
])
if let bottomView = self.bottomView {
constraints.append(contentsOf: [
self._contentView.bottomLayout == bottomView.topLayout,
bottomView.leadingLayout == self.leadingLayout.offset(self.edgeInsets.left),
bottomView.trailingLayout == self.trailingLayout.offset(-self.edgeInsets.right),
bottomView.bottomLayout == self.bottomLayout.offset(-self.edgeInsets.bottom)
])
} else {
constraints.append(contentsOf: [
self._contentView.bottomLayout == self.bottomLayout.offset(-self.edgeInsets.bottom)
])
}
case .onlyBottom:
constraints.append(contentsOf: [
self._contentView.bottomLayout == self.topLayout.offset(-self.edgeInsets.top)
])
if let bottomView = self.bottomView {
constraints.append(contentsOf: [
bottomView.topLayout == self.topLayout.offset(self.edgeInsets.top),
bottomView.leadingLayout == self.leadingLayout.offset(self.edgeInsets.left),
bottomView.trailingLayout == self.trailingLayout.offset(-self.edgeInsets.right),
bottomView.bottomLayout == self.bottomLayout.offset(-self.edgeInsets.bottom)
])
} else {
constraints.append(contentsOf: [
self._contentView.bottomLayout == self.bottomLayout.offset(-self.edgeInsets.bottom)
])
}
}
self._constraints = constraints
var contentConstraints: [NSLayoutConstraint] = [
self._contentView.heightLayout == self.contentSize,
self._leftView.topLayout == self._contentView.topLayout,
self._leftView.leadingLayout == self._contentView.leadingLayout,
self._leftView.bottomLayout == self._contentView.bottomLayout,
self._centerView.topLayout == self._contentView.topLayout,
self._centerView.bottomLayout == self._contentView.bottomLayout,
self._rightView.topLayout == self._contentView.topLayout,
self._rightView.trailingLayout == self._contentView.trailingLayout,
self._rightView.bottomLayout == self._contentView.bottomLayout
]
if self.centerViews.count > 0 {
if self.leftViews.count > 0 && self.rightViews.count > 0 {
contentConstraints.append(contentsOf: [
self._centerView.leadingLayout >= self._leftView.trailingLayout.offset(self.leftViewsOffset),
self._centerView.trailingLayout <= self._rightView.leadingLayout.offset(-self.rightViewsOffset),
self._centerView.centerXLayout == self._contentView.centerXLayout
])
} else if self.leftViews.count > 0 {
contentConstraints.append(contentsOf: [
self._centerView.leadingLayout >= self._leftView.trailingLayout.offset(self.leftViewsOffset),
self._centerView.trailingLayout <= self._contentView.trailingLayout,
self._centerView.centerXLayout == self._contentView.centerXLayout
])
} else if self.rightViews.count > 0 {
contentConstraints.append(contentsOf: [
self._centerView.leadingLayout >= self._contentView.leadingLayout,
self._centerView.trailingLayout <= self._rightView.leadingLayout.offset(-self.rightViewsOffset),
self._centerView.centerXLayout == self._contentView.centerXLayout
])
} else {
contentConstraints.append(contentsOf: [
self._centerView.leadingLayout == self._contentView.leadingLayout,
self._centerView.trailingLayout == self._contentView.trailingLayout,
self._centerView.centerXLayout == self._contentView.centerXLayout
])
}
} else {
if self.leftViews.count > 0 && self.rightViews.count > 0 {
contentConstraints.append(contentsOf: [
self._leftView.trailingLayout >= self._rightView.trailingLayout.offset(self.leftViewsOffset + self.rightViewsOffset)
])
} else if self.leftViews.count > 0 {
contentConstraints.append(contentsOf: [
self._leftView.trailingLayout <= self._contentView.trailingLayout
])
} else if self.rightViews.count > 0 {
contentConstraints.append(contentsOf: [
self._rightView.leadingLayout >= self._contentView.leadingLayout
])
}
}
self._contentConstraints = contentConstraints
}
private class WrapView : QInvisibleView {
public var spacing: CGFloat = 0 {
didSet(oldValue) {
if self.spacing != oldValue {
self.setNeedsUpdateConstraints()
}
}
}
public var views: [UIView] = [] {
willSet {
for view in self.views {
view.removeFromSuperview()
}
}
didSet {
for view in self.views {
view.translatesAutoresizingMaskIntoConstraints = false
view.setContentCompressionResistancePriority(self.contentCompressionResistancePriority(for: .horizontal), for: .horizontal)
view.setContentCompressionResistancePriority(self.contentCompressionResistancePriority(for: .vertical), for: .vertical)
view.setContentHuggingPriority(self.contentHuggingPriority(for: .horizontal), for: .horizontal)
view.setContentHuggingPriority(self.contentHuggingPriority(for: .vertical), for: .vertical)
self.addSubview(view)
}
self.setNeedsUpdateConstraints()
}
}
private var _constraints: [NSLayoutConstraint] = [] {
willSet { self.removeConstraints(self._constraints) }
didSet { self.addConstraints(self._constraints) }
}
public override func setup() {
super.setup()
self.backgroundColor = UIColor.clear
self.translatesAutoresizingMaskIntoConstraints = false
}
public override func updateConstraints() {
super.updateConstraints()
var constraints: [NSLayoutConstraint] = []
if self.views.count > 0 {
var lastView: UIView? = nil
for view in self.views {
constraints.append(view.topLayout == self.topLayout)
if let lastView = lastView {
constraints.append(view.leadingLayout == lastView.trailingLayout.offset(self.spacing))
} else {
constraints.append(view.leadingLayout == self.leadingLayout)
}
constraints.append(view.bottomLayout == self.bottomLayout)
lastView = view
}
if let lastView = lastView {
constraints.append(lastView.trailingLayout == self.trailingLayout)
}
} else {
constraints.append(self.widthLayout == 0)
}
self._constraints = constraints
}
}
}
|
mit
|
dduan/swift
|
test/SILGen/imported_struct_array_field.swift
|
1
|
336
|
// RUN: %target-swift-frontend -emit-silgen -import-objc-header %S/Inputs/array_typedef.h %s | FileCheck %s
// CHECK-LABEL: sil shared [transparent] [fragile] @_TFVSC4NameC{{.*}} : $@convention(thin) (UInt8, UInt8, UInt8, UInt8, @thin Name.Type) -> Name
func useImportedArrayTypedefInit() -> Name {
return Name(name: (0, 0, 0, 0))
}
|
apache-2.0
|
nbabaka/CMDFramework
|
CMDFramework/Classes/Colors.swift
|
1
|
8987
|
//
// Colors.swift
// CINEMOOD Apps Framework
//
// Created by Nikolay Karataev on 15.08.17.
// Copyright © 2017 CINEMOOD Trendsetters Co. All rights reserved.
//
import UIKit
public extension UIColor {
public struct background {
public static var greenForSwipeCell: UIColor {
return UIColor(red: 35/255.0, green: 184/255.0, blue: 64/255.0, alpha: 1.0)
}
public static var redForSwipeCell: UIColor {
return UIColor(red: 230/255.0, green: 13/255.0, blue: 67/255.0, alpha: 1.0)
}
public static var devicesCell: UIColor {
return UIColor(red: 45/255.0, green: 45/255.0, blue: 53/255.0, alpha: 1.0)
}
public static var activeDevicesCell: UIColor {
return UIColor(red: 85/255.0, green: 85/255.0, blue: 93/255.0, alpha: 1.0)
}
public static var blueButton: UIColor {
return UIColor(red:40/255.0, green:146/255.0, blue:211/255.0, alpha:1)
}
public static var switchBack: UIColor {
return UIColor(red: 55/255.0, green: 55/255.0, blue: 66/255.0, alpha: 1.0)
}
public static var chatAgent: UIColor {
return UIColor(red: 97/255.0, green: 97/255.0, blue: 97/255.0, alpha: 1.0)
}
public static var chatVisitor: UIColor {
return UIColor(red: 40/255.0, green: 146/255.0, blue: 211/255.0, alpha: 1.0)
}
}
public struct textColor {
public static var tableViewHeader: UIColor {
return UIColor(red: 114/255.0, green: 114/255.0, blue: 127/255.0, alpha: 1.0)
}
public static var chatAgent: UIColor {
return UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1.0)
}
public static var chatAgentName: UIColor {
return UIColor(red: 230/255.0, green: 230/255.0, blue: 230/255.0, alpha: 1.0)
}
public static var chatAgentTimestamp: UIColor {
return UIColor(red: 230/255.0, green: 230/255.0, blue: 230/255.0, alpha: 1.0)
}
public static var chatVisitor: UIColor {
return UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1.0)
}
public static var chatVisitorTimestamp: UIColor {
return UIColor(red: 230/255.0, green: 230/255.0, blue: 230/255.0, alpha: 1.0)
}
public static var chatSystem: UIColor {
return UIColor(red: 200/255.0, green: 200/255.0, blue: 200/255.0, alpha: 1.0)
}
public static var loadingLabel: UIColor {
return UIColor(red: 220/255.0, green: 220/255.0, blue: 230/255.0, alpha: 1.0)
}
public static var chatURL: UIColor {
return UIColor(red: 230/255.0, green: 230/255.0, blue: 230/255.0, alpha: 1.0)
}
}
public struct labels {
public static var TBFLabelTextColor: UIColor {
return UIColor(red: 160/255.0, green: 163/255.0, blue: 179/255.0, alpha: 1.0)
}
public static var cellStatusLabelOther: UIColor {
return UIColor(red: 160/255.0, green: 163/255.0, blue: 179/255.0, alpha: 1.0)
}
public static var sectorLabelTextColor: UIColor {
return UIColor(red: 70/255.0, green: 70/255.0, blue: 80/255.0, alpha: 1.0)
}
public static var insetLabelBorder: UIColor {
return UIColor(red: 230/255.0, green: 230/255.0, blue: 230/255.0, alpha: 1.0)
}
public static var insetLabelBackground: UIColor {
return UIColor(red: 45/255.0, green: 45/255.0, blue: 53/255.0, alpha: 1.0)
}
}
public struct buttons {
public static var blueButtonBackground: UIColor {
return UIColor(red: 40.0 / 255.0, green: 146.0 / 255.0, blue: 211.0 / 255.0, alpha: 1.0)
}
public static var blueButtonBackgroundHighlight: UIColor {
return UIColor(red: 0.0, green: 153.0 / 255.0, blue: 212.0 / 255.0, alpha: 1.0)
}
public static var blueButtonBackgroundDisabled: UIColor {
return UIColor(red: 55.0 / 255.0, green: 55.0 / 255.0, blue: 66.0 / 255.0, alpha: 1.0)
}
public static var blueButtonTitle: UIColor {
return UIColor(red: 212.0 / 255.0, green: 233.0 / 255.0, blue: 246.0 / 255.0, alpha: 1.0)
}
public static var blueButtonTitleHighlight: UIColor {
return UIColor.white
}
public static var blueButtonTitleDisabled: UIColor {
return UIColor(red: 64/255.0, green: 64/255.0, blue: 67/255.0, alpha: 1.0)
}
public static var blueButtonShadow: UIColor {
return UIColor(red: 17.0 / 255.0, green: 134.0 / 255.0, blue: 207.0 / 255.0, alpha: 0.5)
}
public static var classicButtonTitle: UIColor {
return UIColor(red: 91.0 / 255.0, green: 93.0 / 255.0, blue: 110.0 / 255.0, alpha: 1.0)
}
public static var classicButtonTitleHightlight: UIColor {
return UIColor(red: 195.0 / 255.0, green: 199.0 / 255.0, blue: 217.0 / 255.0, alpha: 1.0)
}
public static var backButtonTitle: UIColor {
return UIColor(red: 195.0 / 255.0, green: 199.0 / 255.0, blue: 217.0 / 255.0, alpha: 1.0)
}
public static var grayButtonBackground: UIColor {
return UIColor(red: 55.0 / 255.0, green: 55.0 / 255.0, blue: 66.0 / 255.0, alpha: 1.0)
}
public static var grayButtonBackgroundHighlight: UIColor {
return UIColor(red: 55.0 / 255.0, green: 55.0 / 255.0, blue: 66.0 / 255.0, alpha: 1.0)
}
public static var grayButtonShadow: UIColor {
return UIColor(red: 55.0 / 255.0, green: 55.0 / 255.0, blue: 66.0 / 255.0, alpha: 1.0)
}
public static var grayButtonTitle: UIColor {
return UIColor(red: 167.0 / 255.0, green: 170.0 / 255.0, blue: 187.0 / 255.0, alpha: 1.0)
}
public static var grayButtonTitleHighlight: UIColor {
return UIColor.white
}
public static var rightImageTitle: UIColor {
return UIColor(white: 111.0 / 255.0, alpha: 1.0)
}
public static var rightImageTint: UIColor {
return UIColor(white: 111.0 / 255.0, alpha: 1.0)
}
public static var colorButtonBackground: UIColor {
return UIColor(red: 45/255.0, green: 45/255.0, blue: 53/255.0, alpha: 1.0)
}
public static var colorButtonBackgroundHighlight: UIColor {
return UIColor(red: 174/255.0, green: 174/255.0, blue: 186/255.0, alpha: 1.0)
}
public static var colorButtonTint: UIColor {
return UIColor(red: 20/255.0, green: 20/255.0, blue: 24/255.0, alpha: 1.0)
}
public static var colorButtonTitleHighlight: UIColor {
return UIColor(red: 20/255.0, green: 20/255.0, blue: 24/255.0, alpha: 1.0)
}
public static var colorButtonTitle: UIColor {
return UIColor(red: 114/255.0, green: 114/255.0, blue: 127/255.0, alpha: 1.0)
}
public static var redButtonBackground: UIColor {
return UIColor(red: 230/255.0, green: 13/255.0, blue: 67/255.0, alpha: 1.0)
}
public static var redButtonTitle: UIColor {
return UIColor(red: 230/255.0, green: 13/255.0, blue: 67/255.0, alpha: 1.0)
}
}
public struct textWidgets {
public static var activeText: UIColor {
return UIColor(red: 20/255.0, green: 20/255.0, blue: 24/255.0, alpha: 1.0)
}
public static var nonActiveText: UIColor {
return UIColor(red: 114/255.0, green: 114/255.0, blue: 127/255.0, alpha: 1.0)
}
public static var activeBackground: UIColor {
return UIColor(red: 174/255.0, green: 174/255.0, blue: 186/255.0, alpha: 1.0)
}
public static var nonActiveBackground: UIColor {
return UIColor(red: 45/255.0, green: 45/255.0, blue: 53/255.0, alpha: 1.0)
}
public static var activePlaceholder: UIColor {
return UIColor(red: 82/255.0, green: 85/255.0, blue: 98/255.0, alpha: 1.0)
}
public static var nonActivePlaceholder: UIColor {
return UIColor(red: 82/255.0, green: 85/255.0, blue: 98/255.0, alpha: 1.0)
}
}
public struct padColors {
public static var roundedRect: UIColor {
return UIColor(red:34/255.0, green:35/255.0, blue:39/255.0, alpha:1)
}
}
}
|
mit
|
gerardogrisolini/Webretail
|
Sources/Webretail/Models/OrderModel.swift
|
1
|
277
|
//
// OrderModel.swift
// Webretail
//
// Created by Gerardo Grisolini on 18/11/17.
//
struct OrderModel: Codable {
public var shipping : String = ""
public var shippingCost : Double = 0.0
public var payment : String = ""
public var paypal : String = ""
}
|
apache-2.0
|
Dsternheim/Pokedex
|
PokedexUITests/PokedexUITests.swift
|
1
|
1251
|
//
// PokedexUITests.swift
// PokedexUITests
//
// Created by David Sternheim on 8/7/17.
// Copyright © 2017 David Sternheim. All rights reserved.
//
import XCTest
class PokedexUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
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() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
|
mit
|
benkraus/Operations
|
Operations/NSLock+Operations.swift
|
1
|
1531
|
/*
The MIT License (MIT)
Original work Copyright (c) 2015 pluralsight
Modified work Copyright 2016 Ben Kraus
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
extension NSLock {
func withCriticalScope<T>(@noescape block: Void -> T) -> T {
lock()
let value = block()
unlock()
return value
}
}
extension NSRecursiveLock {
func withCriticalScope<T>(@noescape block: Void -> T) -> T {
lock()
let value = block()
unlock()
return value
}
}
|
mit
|
BarlowTucker/ProtocolExtensions-Playground
|
Protocol Extensions.playground/Pages/Protocol Extensions - Intro.xcplaygroundpage/Contents.swift
|
1
|
1370
|
//: # Protocol Extensions
//: **Barlow Tucker** - @barlow_tucker
import Foundation
import UIKit
//
protocol TheProtocol {
var theVariable:String {get}
func funcOne() -> String
func funcTwo() -> String
}
extension TheProtocol {
func funcOne() -> String {
return "funcOne was called from TheProtocol extension"
}
func funcTwo() -> String {
return "funcTwo was called from TheProtocol extension"
}
func funcThree() -> String {
return "funcThree was called from TheProtocol extension"
}
var theVariable:String {
get {
return "TheVariable"
}
}
}
extension TheProtocol where Self: CustomStringConvertible {
func toString() -> String {
return self.description
}
}
class TheClass: TheProtocol {
func funcOne() -> String {
return "funcOne was called from TheClass"
}
func funcThree() -> String {
return "funcThree was called from TheClass"
}
}
struct TheStruct: TheProtocol {
}
extension Bool: TheProtocol {
}
let classOne = TheClass()
print(classOne.funcOne())
print(classOne.funcTwo())
print(classOne.funcThree())
let classTwo:TheProtocol = TheClass()
print(classTwo.funcOne())
print(classTwo.funcTwo())
print(classTwo.funcThree())
let foo:Bool = false
foo.toString()
//: [Next](@next)
|
mit
|
MTR2D2/TIY-Assignments
|
VenueMenu/VenueMenu/Extensions.swift
|
1
|
1357
|
//
// Extensions.swift
// VenueMenu
//
// Created by Michael Reynolds on 12/3/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
extension UIImageView
{
func downloadImageFrom(imageURL: String)
{
let formattedImageURL = imageURL.stringByReplacingOccurrencesOfString("\\", withString: "")
if let URL = NSURL(string: formattedImageURL)
{
let task = NSURLSession.sharedSession().dataTaskWithURL(URL, completionHandler:
{ (imageData, _, error) -> Void in
if imageData != nil
{
if let image = UIImage(data: imageData!)
{
self.contentMode = .ScaleToFill
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.image = image
})
}
}
else
{
print(error?.localizedDescription)
// self.image = UIImage(named: "na.png")
}
})//.resume()
task.resume()
}
else
{
print("URL was invalid \(imageURL)")
}
}
}
|
cc0-1.0
|
JGiola/swift-package-manager
|
Sources/Utility/Versioning.swift
|
2
|
2830
|
/*
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 http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import clibc
/// A Swift version number.
///
/// Note that these are *NOT* semantically versioned numbers.
public struct SwiftVersion {
/// The version number.
public var version: (major: Int, minor: Int, patch: Int)
/// Whether or not this is a development version.
public var isDevelopment: Bool
/// Build information, as an unstructured string.
public var buildIdentifier: String?
/// The major component of the version number.
public var major: Int { return version.major }
/// The minor component of the version number.
public var minor: Int { return version.minor }
/// The patch component of the version number.
public var patch: Int { return version.patch }
/// The version as a readable string.
public var displayString: String {
var result = "\(major).\(minor).\(patch)"
if isDevelopment {
result += "-dev"
}
if let buildIdentifier = self.buildIdentifier {
result += " (" + buildIdentifier + ")"
}
return result
}
/// The complete product version display string (including the name).
public var completeDisplayString: String {
var vendorPrefix = String(cString: SPM_VendorNameString())
if !vendorPrefix.isEmpty {
vendorPrefix += " "
}
return vendorPrefix + "Swift Package Manager - Swift " + displayString
}
/// The list of version specific identifiers to search when attempting to
/// load version specific package or version information, in order of
/// preference.
public var versionSpecificKeys: [String] {
return [
"@swift-\(major).\(minor).\(patch)",
"@swift-\(major).\(minor)",
"@swift-\(major)",
]
}
}
private func getBuildIdentifier() -> String? {
let buildIdentifier = String(cString: SPM_BuildIdentifierString())
return buildIdentifier.isEmpty ? nil : buildIdentifier
}
/// Version support for the package manager.
public struct Versioning {
/// The current version of the package manager.
public static let currentVersion = SwiftVersion(
version: (5, 0, 0),
isDevelopment: false,
buildIdentifier: getBuildIdentifier())
/// The list of version specific "keys" to search when attempting to load
/// version specific package or version information, in order of preference.
public static let currentVersionSpecificKeys = currentVersion.versionSpecificKeys
}
|
apache-2.0
|
coderYDW/DYShortcutItemDemo
|
DYTouchDemo/DYTouchDemo/AppDelegate.swift
|
1
|
2112
|
//
// AppDelegate.swift
// DYTouchDemo
//
// Created by DovYoung on 2017/2/4.
// Copyright © 2017年 DovYoung. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
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
|
antoninbiret/DataSourceKit
|
DataSourceKit/Classes/Extensions/Foundation/Int+Extension.swift
|
1
|
251
|
//
// Int+Extension.swift
// Pods
//
// Created by Antonin Biret on 02/06/2017.
//
//
import Foundation
extension Int {
internal static func _indexes(from index: Int, offset: Int) -> [Int] {
return Array(index..<(index+offset))
}
}
|
mit
|
phimage/MomXML
|
Sources/FromXML/MomFetchIndex+FromXML.swift
|
1
|
1772
|
//
// MomFetchIndex+FromXML.swift
// MomXML
//
// Created by Eric Marchand on 09/10/2019.
// Copyright © 2019 phimage. All rights reserved.
//
import Foundation
extension MomFetchIndex: XMLObject {
public init?(xml: XML) {
guard let element = xml.element, element.name == "fetchIndex" else {
return nil
}
guard let name = element.attribute(by: "name")?.text else {
return nil
}
self.init(name: name)
for child in xml.children {
if let entry = MomFetchIndexElement(xml: child) {
self.elements.append(entry)
} else {
MomXML.orphanCallback?(xml, MomFetchIndexElement.self)
}
}
}
}
extension MomFetchIndexElement: XMLObject {
public init?(xml: XML) {
guard let element = xml.element, element.name == "fetchIndexElement" else {
return nil
}
guard let typeString = element.attribute(by: "type")?.text,
let type = MomFetchIndexElementType(rawValue: typeString.lowercased()),
let order = element.attribute(by: "order")?.text else {
return nil
}
if let property = element.attribute(by: "property")?.text {
self.init(property: property, type: type, order: order)
} else if let expression = element.attribute(by: "expression")?.text,
let expressionTypeString = element.attribute(by: "expressionType")?.text,
let expressionType = MomAttribute.AttributeType(rawValue: expressionTypeString) {
self.init(expression: expression, expressionType: expressionType, type: type, order: order)
} else {
return nil // unknown type
}
}
}
|
mit
|
aahmedae/blitz-news-ios
|
Blitz News/View/NewsItemTableViewCell.swift
|
1
|
972
|
//
// NewsItemTableViewCell.swift
// Blitz News
//
// Created by Asad Ahmed on 5/13/17.
// Custom table view cell for displaying a news article
//
import UIKit
class NewsItemTableViewCell: UITableViewCell
{
@IBOutlet weak var backgroundImageView: UIImageView!
@IBOutlet weak var sourceLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var infoView: UIView!
override func awakeFromNib()
{
super.awakeFromNib()
infoView.layer.cornerRadius = 12.0
infoView.isHidden = true
}
override func prepareForReuse()
{
backgroundImageView.image = nil
contentView.layer.contents = nil
}
override func setSelected(_ selected: Bool, animated: Bool)
{
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
mit
|
omaarr90/healthcare
|
Sources/App/Models/Post.swift
|
1
|
990
|
import Vapor
import Fluent
import Foundation
final class Post: Model {
var id: Node?
var content: String
init(content: String) {
self.id = UUID().uuidString.makeNode()
self.content = content
}
init(node: Node, in context: Context) throws {
id = try node.extract("id")
content = try node.extract("content")
}
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id": id,
"content": content
])
}
}
extension Post {
/**
This will automatically fetch from database, using example here to load
automatically for example. Remove on real models.
*/
public convenience init?(from string: String) throws {
self.init(content: string)
}
}
extension Post: Preparation {
static func prepare(_ database: Database) throws {
//
}
static func revert(_ database: Database) throws {
//
}
}
|
mit
|
lovehhf/edx-app-ios
|
Source/CourseOutlineTableSource.swift
|
1
|
7187
|
//
// CourseOutlineTableSource.swift
// edX
//
// Created by Akiva Leffert on 4/30/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
protocol CourseOutlineTableControllerDelegate : class {
func outlineTableController(controller : CourseOutlineTableController, choseBlock:CourseBlock, withParentID:CourseBlockID)
func outlineTableController(controller : CourseOutlineTableController, choseDownloadVideosRootedAtBlock:CourseBlock)
}
class CourseOutlineTableController : UITableViewController, CourseVideoTableViewCellDelegate, CourseSectionTableViewCellDelegate {
weak var delegate : CourseOutlineTableControllerDelegate?
private let courseID : String
private let headerContainer = UIView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, 44))
private let lastAccessedView = CourseOutlineHeaderView(frame: CGRectZero, styles: OEXStyles.sharedStyles(), titleText : OEXLocalizedString("LAST_ACCESSED", nil), subtitleText : "Placeholder")
let refreshController = PullRefreshController()
init(courseID : String) {
self.courseID = courseID
super.init(nibName: nil, bundle: nil)
}
required init!(coder aDecoder: NSCoder!) {
fatalError("init(coder:) has not been implemented")
}
var groups : [CourseOutlineQuerier.BlockGroup] = []
override func viewDidLoad() {
tableView.dataSource = self
tableView.delegate = self
tableView.tableFooterView = UIView(frame: CGRectZero)
tableView.registerClass(CourseOutlineHeaderCell.self, forHeaderFooterViewReuseIdentifier: CourseOutlineHeaderCell.identifier)
tableView.registerClass(CourseVideoTableViewCell.self, forCellReuseIdentifier: CourseVideoTableViewCell.identifier)
tableView.registerClass(CourseHTMLTableViewCell.self, forCellReuseIdentifier: CourseHTMLTableViewCell.identifier)
tableView.registerClass(CourseProblemTableViewCell.self, forCellReuseIdentifier: CourseProblemTableViewCell.identifier)
tableView.registerClass(CourseUnknownTableViewCell.self, forCellReuseIdentifier: CourseUnknownTableViewCell.identifier)
tableView.registerClass(CourseSectionTableViewCell.self, forCellReuseIdentifier: CourseSectionTableViewCell.identifier)
headerContainer.addSubview(lastAccessedView)
lastAccessedView.snp_makeConstraints { (make) -> Void in
make.edges.equalTo(self.headerContainer)
}
refreshController.setupInScrollView(self.tableView)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return groups.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let group = groups[section]
return group.children.count
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 30
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
// Will remove manual heights when dropping iOS7 support and move to automatic cell heights.
return 60.0
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let group = groups[section]
let header = tableView.dequeueReusableHeaderFooterViewWithIdentifier(CourseOutlineHeaderCell.identifier) as! CourseOutlineHeaderCell
header.block = group.block
return header
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let group = groups[indexPath.section]
let nodes = group.children
let block = nodes[indexPath.row]
switch nodes[indexPath.row].displayType {
case .Video:
let cell = tableView.dequeueReusableCellWithIdentifier(CourseVideoTableViewCell.identifier, forIndexPath: indexPath) as! CourseVideoTableViewCell
cell.block = block
cell.localState = OEXInterface.sharedInterface().stateForVideoWithID(block.blockID, courseID : courseID)
cell.delegate = self
return cell
case .HTML(.Base):
let cell = tableView.dequeueReusableCellWithIdentifier(CourseHTMLTableViewCell.identifier, forIndexPath: indexPath) as! CourseHTMLTableViewCell
cell.block = block
return cell
case .HTML(.Problem):
let cell = tableView.dequeueReusableCellWithIdentifier(CourseProblemTableViewCell.identifier, forIndexPath: indexPath) as! CourseProblemTableViewCell
cell.block = block
return cell
case .Unknown:
let cell = tableView.dequeueReusableCellWithIdentifier(CourseUnknownTableViewCell.identifier, forIndexPath: indexPath) as! CourseUnknownTableViewCell
cell.block = block
return cell
case .Outline, .Unit:
var cell = tableView.dequeueReusableCellWithIdentifier(CourseSectionTableViewCell.identifier, forIndexPath: indexPath) as! CourseSectionTableViewCell
cell.block = nodes[indexPath.row]
cell.delegate = self
return cell
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let group = groups[indexPath.section]
let chosenBlock = group.children[indexPath.row]
self.delegate?.outlineTableController(self, choseBlock: chosenBlock, withParentID: group.block.blockID)
}
override func scrollViewDidScroll(scrollView: UIScrollView) {
self.refreshController.scrollViewDidScroll(scrollView)
}
func videoCellChoseDownload(cell: CourseVideoTableViewCell, block : CourseBlock) {
self.delegate?.outlineTableController(self, choseDownloadVideosRootedAtBlock: block)
}
func sectionCellChoseDownload(cell: CourseSectionTableViewCell, block: CourseBlock) {
self.delegate?.outlineTableController(self, choseDownloadVideosRootedAtBlock: block)
}
func choseViewLastAccessedWithItem(item : CourseLastAccessed) {
for group in groups {
let childNodes = group.children
let currentLastViewedIndex = childNodes.firstIndexMatching({$0.blockID == item.moduleId})
if let matchedIndex = currentLastViewedIndex {
self.delegate?.outlineTableController(self, choseBlock: childNodes[matchedIndex], withParentID: group.block.blockID)
break
}
}
}
/// Shows the last accessed Header from the item as argument. Also, sets the relevant action if the course block exists in the course outline.
func showLastAccessedWithItem(item : CourseLastAccessed) {
tableView.tableHeaderView = self.headerContainer
lastAccessedView.subtitleText = item.moduleName
lastAccessedView.setViewButtonAction { [weak self] _ in
self?.choseViewLastAccessedWithItem(item)
}
}
func hideLastAccessed() {
tableView.tableHeaderView = nil
}
}
|
apache-2.0
|
jianghongbing/APIReferenceDemo
|
UIKit/UIContentContainer/UIContentContainer/AppDelegate.swift
|
1
|
2277
|
//
// AppDelegate.swift
// UIContentContainer
//
// Created by pantosoft on 2018/8/21.
// Copyright © 2018年 jianghongbing. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// window = UIWindow(frame: UIScreen.main.bounds)
// window?.rootViewController = ContainerViewController()
// window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
|
mit
|
firebase/firebase-ios-sdk
|
FirebaseMessaging/Apps/AdvancedSample/NotificationServiceExtension/NotificationService.swift
|
2
|
2113
|
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UserNotifications
import FirebaseMessaging
class NotificationService: UNNotificationServiceExtension {
var contentHandler: ((UNNotificationContent) -> Void)?
var bestAttemptContent: UNMutableNotificationContent?
override func didReceive(_ request: UNNotificationRequest,
withContentHandler contentHandler: @escaping (UNNotificationContent)
-> Void) {
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
if let bestAttemptContent = bestAttemptContent {
// Modify the notification content here...
bestAttemptContent.title = "\(bestAttemptContent.title) 👩🏻💻"
// Log Delivery signals and export to BigQuery.
Messaging.serviceExtension()
.exportDeliveryMetricsToBigQuery(withMessageInfo: request.content.userInfo)
// Add image, call this last to finish with the content handler.
Messaging.serviceExtension()
.populateNotificationContent(bestAttemptContent, withContentHandler: contentHandler)
}
}
override func serviceExtensionTimeWillExpire() {
// Called just before the extension will be terminated by the system.
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
contentHandler(bestAttemptContent)
}
}
}
|
apache-2.0
|
gregomni/swift
|
stdlib/public/core/Assert.swift
|
3
|
13100
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// Performs a traditional C-style assert with an optional message.
///
/// Use this function for internal sanity checks that are active during testing
/// but do not impact performance of shipping code. To check for invalid usage
/// in Release builds, see `precondition(_:_:file:line:)`.
///
/// * In playgrounds and `-Onone` builds (the default for Xcode's Debug
/// configuration): If `condition` evaluates to `false`, stop program
/// execution in a debuggable state after printing `message`.
///
/// * In `-O` builds (the default for Xcode's Release configuration),
/// `condition` is not evaluated, and there are no effects.
///
/// * In `-Ounchecked` builds, `condition` is not evaluated, but the optimizer
/// may assume that it *always* evaluates to `true`. Failure to satisfy that
/// assumption is a serious programming error.
///
/// - Parameters:
/// - condition: The condition to test. `condition` is only evaluated in
/// playgrounds and `-Onone` builds.
/// - message: A string to print if `condition` is evaluated to `false`. The
/// default is an empty string.
/// - file: The file name to print with `message` if the assertion fails. The
/// default is the file where `assert(_:_:file:line:)` is called.
/// - line: The line number to print along with `message` if the assertion
/// fails. The default is the line number where `assert(_:_:file:line:)`
/// is called.
@_transparent
public func assert(
_ condition: @autoclosure () -> Bool,
_ message: @autoclosure () -> String = String(),
file: StaticString = #file, line: UInt = #line
) {
// Only assert in debug mode.
if _isDebugAssertConfiguration() {
if !_fastPath(condition()) {
_assertionFailure("Assertion failed", message(), file: file, line: line,
flags: _fatalErrorFlags())
}
}
}
/// Checks a necessary condition for making forward progress.
///
/// Use this function to detect conditions that must prevent the program from
/// proceeding, even in shipping code.
///
/// * In playgrounds and `-Onone` builds (the default for Xcode's Debug
/// configuration): If `condition` evaluates to `false`, stop program
/// execution in a debuggable state after printing `message`.
///
/// * In `-O` builds (the default for Xcode's Release configuration): If
/// `condition` evaluates to `false`, stop program execution.
///
/// * In `-Ounchecked` builds, `condition` is not evaluated, but the optimizer
/// may assume that it *always* evaluates to `true`. Failure to satisfy that
/// assumption is a serious programming error.
///
/// - Parameters:
/// - condition: The condition to test. `condition` is not evaluated in
/// `-Ounchecked` builds.
/// - message: A string to print if `condition` is evaluated to `false` in a
/// playground or `-Onone` build. The default is an empty string.
/// - file: The file name to print with `message` if the precondition fails.
/// The default is the file where `precondition(_:_:file:line:)` is
/// called.
/// - line: The line number to print along with `message` if the assertion
/// fails. The default is the line number where
/// `precondition(_:_:file:line:)` is called.
@_transparent
public func precondition(
_ condition: @autoclosure () -> Bool,
_ message: @autoclosure () -> String = String(),
file: StaticString = #file, line: UInt = #line
) {
// Only check in debug and release mode. In release mode just trap.
if _isDebugAssertConfiguration() {
if !_fastPath(condition()) {
_assertionFailure("Precondition failed", message(), file: file, line: line,
flags: _fatalErrorFlags())
}
} else if _isReleaseAssertConfiguration() {
let error = !condition()
Builtin.condfail_message(error._value,
StaticString("precondition failure").unsafeRawPointer)
}
}
/// Indicates that an internal sanity check failed.
///
/// Use this function to stop the program, without impacting the performance of
/// shipping code, when control flow is not expected to reach the call---for
/// example, in the `default` case of a `switch` where you have knowledge that
/// one of the other cases must be satisfied. To protect code from invalid
/// usage in Release builds, see `preconditionFailure(_:file:line:)`.
///
/// * In playgrounds and `-Onone` builds (the default for Xcode's Debug
/// configuration), stop program execution in a debuggable state after
/// printing `message`.
///
/// * In `-O` builds, has no effect.
///
/// * In `-Ounchecked` builds, the optimizer may assume that this function is
/// never called. Failure to satisfy that assumption is a serious
/// programming error.
///
/// - Parameters:
/// - message: A string to print in a playground or `-Onone` build. The
/// default is an empty string.
/// - file: The file name to print with `message`. The default is the file
/// where `assertionFailure(_:file:line:)` is called.
/// - line: The line number to print along with `message`. The default is the
/// line number where `assertionFailure(_:file:line:)` is called.
@inlinable
@inline(__always)
public func assertionFailure(
_ message: @autoclosure () -> String = String(),
file: StaticString = #file, line: UInt = #line
) {
if _isDebugAssertConfiguration() {
_assertionFailure("Fatal error", message(), file: file, line: line,
flags: _fatalErrorFlags())
}
else if _isFastAssertConfiguration() {
_conditionallyUnreachable()
}
}
/// Indicates that a precondition was violated.
///
/// Use this function to stop the program when control flow can only reach the
/// call if your API was improperly used. This function's effects vary
/// depending on the build flag used:
///
/// * In playgrounds and `-Onone` builds (the default for Xcode's Debug
/// configuration), stops program execution in a debuggable state after
/// printing `message`.
///
/// * In `-O` builds (the default for Xcode's Release configuration), stops
/// program execution.
///
/// * In `-Ounchecked` builds, the optimizer may assume that this function is
/// never called. Failure to satisfy that assumption is a serious
/// programming error.
///
/// - Parameters:
/// - message: A string to print in a playground or `-Onone` build. The
/// default is an empty string.
/// - file: The file name to print with `message`. The default is the file
/// where `preconditionFailure(_:file:line:)` is called.
/// - line: The line number to print along with `message`. The default is the
/// line number where `preconditionFailure(_:file:line:)` is called.
@_transparent
public func preconditionFailure(
_ message: @autoclosure () -> String = String(),
file: StaticString = #file, line: UInt = #line
) -> Never {
// Only check in debug and release mode. In release mode just trap.
if _isDebugAssertConfiguration() {
_assertionFailure("Fatal error", message(), file: file, line: line,
flags: _fatalErrorFlags())
} else if _isReleaseAssertConfiguration() {
Builtin.condfail_message(true._value,
StaticString("precondition failure").unsafeRawPointer)
}
_conditionallyUnreachable()
}
/// Unconditionally prints a given message and stops execution.
///
/// - Parameters:
/// - message: The string to print. The default is an empty string.
/// - file: The file name to print with `message`. The default is the file
/// where `fatalError(_:file:line:)` is called.
/// - line: The line number to print along with `message`. The default is the
/// line number where `fatalError(_:file:line:)` is called.
@_transparent
public func fatalError(
_ message: @autoclosure () -> String = String(),
file: StaticString = #file, line: UInt = #line
) -> Never {
_assertionFailure("Fatal error", message(), file: file, line: line,
flags: _fatalErrorFlags())
}
/// Library precondition checks.
///
/// Library precondition checks are enabled in debug mode and release mode. When
/// building in fast mode they are disabled. In release mode they don't print
/// an error message but just trap. In debug mode they print an error message
/// and abort.
@usableFromInline @_transparent
internal func _precondition(
_ condition: @autoclosure () -> Bool, _ message: StaticString = StaticString(),
file: StaticString = #file, line: UInt = #line
) {
// Only check in debug and release mode. In release mode just trap.
if _isDebugAssertConfiguration() {
if !_fastPath(condition()) {
_assertionFailure("Fatal error", message, file: file, line: line,
flags: _fatalErrorFlags())
}
} else if _isReleaseAssertConfiguration() {
let error = !condition()
Builtin.condfail_message(error._value, message.unsafeRawPointer)
}
}
@usableFromInline @_transparent
internal func _preconditionFailure(
_ message: StaticString = StaticString(),
file: StaticString = #file, line: UInt = #line
) -> Never {
_precondition(false, message, file: file, line: line)
_conditionallyUnreachable()
}
/// If `error` is true, prints an error message in debug mode, traps in release
/// mode, and returns an undefined error otherwise.
/// Otherwise returns `result`.
@_transparent
public func _overflowChecked<T>(
_ args: (T, Bool),
file: StaticString = #file, line: UInt = #line
) -> T {
let (result, error) = args
if _isDebugAssertConfiguration() {
if _slowPath(error) {
_fatalErrorMessage("Fatal error", "Overflow/underflow",
file: file, line: line, flags: _fatalErrorFlags())
}
} else {
Builtin.condfail_message(error._value,
StaticString("_overflowChecked failure").unsafeRawPointer)
}
return result
}
/// Debug library precondition checks.
///
/// Debug library precondition checks are only on in debug mode. In release and
/// in fast mode they are disabled. In debug mode they print an error message
/// and abort.
/// They are meant to be used when the check is not comprehensively checking for
/// all possible errors.
@usableFromInline @_transparent
internal func _debugPrecondition(
_ condition: @autoclosure () -> Bool, _ message: StaticString = StaticString(),
file: StaticString = #file, line: UInt = #line
) {
#if SWIFT_STDLIB_ENABLE_DEBUG_PRECONDITIONS_IN_RELEASE
_precondition(condition(), message, file: file, line: line)
#else
// Only check in debug mode.
if _slowPath(_isDebugAssertConfiguration()) {
if !_fastPath(condition()) {
_fatalErrorMessage("Fatal error", message, file: file, line: line,
flags: _fatalErrorFlags())
}
}
#endif
}
@usableFromInline @_transparent
internal func _debugPreconditionFailure(
_ message: StaticString = StaticString(),
file: StaticString = #file, line: UInt = #line
) -> Never {
#if SWIFT_STDLIB_ENABLE_DEBUG_PRECONDITIONS_IN_RELEASE
_preconditionFailure(message, file: file, line: line)
#else
if _slowPath(_isDebugAssertConfiguration()) {
_precondition(false, message, file: file, line: line)
}
_conditionallyUnreachable()
#endif
}
/// Internal checks.
///
/// Internal checks are to be used for checking correctness conditions in the
/// standard library. They are only enable when the standard library is built
/// with the build configuration INTERNAL_CHECKS_ENABLED enabled. Otherwise, the
/// call to this function is a noop.
@usableFromInline @_transparent
internal func _internalInvariant(
_ condition: @autoclosure () -> Bool, _ message: StaticString = StaticString(),
file: StaticString = #file, line: UInt = #line
) {
#if INTERNAL_CHECKS_ENABLED
if !_fastPath(condition()) {
_fatalErrorMessage("Fatal error", message, file: file, line: line,
flags: _fatalErrorFlags())
}
#endif
}
// Only perform the invariant check on Swift 5.1 and later
@_alwaysEmitIntoClient // Swift 5.1
@_transparent
internal func _internalInvariant_5_1(
_ condition: @autoclosure () -> Bool, _ message: StaticString = StaticString(),
file: StaticString = #file, line: UInt = #line
) {
#if INTERNAL_CHECKS_ENABLED
// FIXME: The below won't run the assert on 5.1 stdlib if testing on older
// OSes, which means that testing may not test the assertion. We need a real
// solution to this.
guard #available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) //SwiftStdlib 5.1
else { return }
_internalInvariant(condition(), message, file: file, line: line)
#endif
}
@usableFromInline @_transparent
internal func _internalInvariantFailure(
_ message: StaticString = StaticString(),
file: StaticString = #file, line: UInt = #line
) -> Never {
_internalInvariant(false, message, file: file, line: line)
_conditionallyUnreachable()
}
|
apache-2.0
|
tarunon/RxExtensions
|
RxExtensions/Throttle3.swift
|
1
|
4562
|
//
// Throttle2.swift
// RxExtensions
//
// Created by Nobuo Saito on 2016/07/22.
// Copyright © 2016年 tarunon. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
class Throttle3Sink<O: ObserverType>
: Sink<O>
, ObserverType
, LockOwnerType
, SynchronizedOnType {
typealias E = O.E
typealias Element = O.E
typealias ParentType = Throttle3<Element>
typealias DisposeKey = CompositeDisposable.DisposeKey
private let _parent: ParentType
let _lock = NSRecursiveLock()
// state
private var _id = 0 as UInt64
private var _value: Element? = nil
private var _dropping: Bool = false
let cancellable = CompositeDisposable()
init(parent: ParentType, observer: O) {
_parent = parent
super.init(observer: observer)
}
func run() -> Disposable {
let subscription = _parent._source.subscribe(self)
return Disposables.create(subscription, cancellable)
}
func on(_ event: Event<Element>) {
synchronizedOn(event)
}
func _synchronized_on(_ event: Event<Element>) {
switch event {
case .next(let element):
_id = _id &+ 1
let currentId = _id
let d = SingleAssignmentDisposable()
if let key = self.cancellable.insert(d) {
_value = element
if _dropping {
d.setDisposable(Disposables.create(
_parent._scheduler.scheduleRelative((currentId), dueTime: _parent._dueTime, action: self.propagate),
_parent._scheduler.scheduleRelative((currentId, key), dueTime: _parent._dueTime, action: self.endDrop)
))
} else {
_dropping = true
d.setDisposable(Disposables.create(
_parent._scheduler.scheduleRelative((), dueTime: 0.0, action: self.propagate),
_parent._scheduler.scheduleRelative((currentId, key), dueTime: _parent._dueTime, action: self.endDrop)
))
}
}
case .error:
_value = nil
forwardOn(event)
dispose()
case .completed:
if let value = _value {
_value = nil
forwardOn(.next(value))
}
forwardOn(.completed)
dispose()
}
}
func propagate() -> Disposable {
_lock.lock(); defer { _lock.unlock() } // {
if let value = _value {
_value = nil
forwardOn(.next(value))
}
// }
return Disposables.create()
}
func propagate(currentId: UInt64) -> Disposable {
_lock.lock(); defer { _lock.unlock() } // {
if let value = _value, currentId == _id {
_value = nil
forwardOn(.next(value))
}
// }
return Disposables.create()
}
func endDrop(currentId: UInt64, key: DisposeKey) -> Disposable {
_lock.lock(); defer { _lock.unlock() } // {
cancellable.remove(for: key)
if currentId == _id {
_dropping = false
}
// }
return Disposables.create()
}
}
class Throttle3<Element> : Producer<Element> {
fileprivate let _source: Observable<Element>
fileprivate let _dueTime: RxTimeInterval
fileprivate let _scheduler: SchedulerType
init(source: Observable<Element>, dueTime: RxTimeInterval, scheduler: SchedulerType) {
_source = source
_dueTime = dueTime
_scheduler = scheduler
}
override func run<O: ObserverType>(_ observer: O) -> Disposable where O.E == Element {
let sink = Throttle3Sink(parent: self, observer: observer)
sink.setDisposable(sink.run())
return sink
}
}
extension ObservableType {
/**
throttle3 is like of throttle2, and send last event after wait dueTime.
*/
public func throttle3(_ dueTime: RxTimeInterval, scheduler: SchedulerType) -> Observable<Self.E> {
return Throttle3(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler).asObservable()
}
}
extension SharedSequence {
/**
throttle3 is like of throttle2, and send last event after wait dueTime.
*/
public func throttle3(_ dueTime: RxTimeInterval) -> SharedSequence {
return Throttle3(source: self.asObservable(), dueTime: dueTime, scheduler: MainScheduler.instance).asSharedSequence(onErrorDriveWith: SharedSequence.empty())
}
}
|
mit
|
keith/radars
|
WMOCoverage/WMOCoverage/Bar.swift
|
1
|
48
|
public func bar() -> String {
return "hi"
}
|
mit
|
spritekitbook/spritekitbook-swift
|
Chapter 6/Start/SpaceRunner/SpaceRunner/Math.swift
|
2
|
1265
|
//
// Math.swift
// SpaceRunner
//
// Created by Jeremy Novak on 8/30/16.
// Copyright © 2016 Spritekit Book. All rights reserved.
//
import SpriteKit
func DegreesToRadians(degrees: CGFloat) -> CGFloat {
return degrees * CGFloat(M_PI) / 180.0
}
func RadiansToDegrees(radians: CGFloat) -> CGFloat {
return radians * 180.0 / CGFloat(M_PI)
}
func Smooth(startPoint: CGFloat, endPoint: CGFloat, percentToMove: CGFloat) -> CGFloat {
return (startPoint * (1 - percentToMove)) + endPoint * percentToMove
}
func AngleBetweenPoints(targetPosition: CGPoint, currentPosition: CGPoint) -> CGFloat {
let deltaX = targetPosition.x - currentPosition.x
let deltaY = targetPosition.y - currentPosition.y
return CGFloat(atan2(Float(deltaY), Float(deltaX))) - DegreesToRadians(degrees: 90)
}
func DistanceBetweenPoints(firstPoint: CGPoint, secondPoint: CGPoint) -> CGFloat {
return CGFloat(hypotf(Float(secondPoint.x - firstPoint.x), Float(secondPoint.y - firstPoint.y)))
}
func Clamp(value: CGFloat, min: CGFloat, max: CGFloat) -> CGFloat {
var newMin = min
var newMax = max
if (min > max) {
newMin = max
newMax = min
}
return value < newMin ? newMin : value < newMax ? value : newMax
}
|
apache-2.0
|
apurushottam/IPhone-Learning-Codes
|
Project 7-Easy Browser/Project 7-Easy Browser/AppDelegate.swift
|
1
|
2168
|
//
// AppDelegate.swift
// Project 7-Easy Browser
//
// Created by Ashutosh Purushottam on 9/28/15.
// Copyright © 2015 Vivid Designs. 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:.
}
}
|
apache-2.0
|
lennet/proNotes
|
app/proNotesTests/DocumentPageTests.swift
|
1
|
3384
|
//
// DocumentPageTests.swift
// proNotes
//
// Created by Leo Thomas on 12/02/16.
// Copyright © 2016 leonardthomas. All rights reserved.
//
import XCTest
@testable import proNotes
class DocumentPageTests: XCTestCase {
func testEquals() {
let firstPage = DocumentPage(index: 0)
let secondPage = DocumentPage(index: 1)
XCTAssertEqual(firstPage, firstPage)
XCTAssertNotEqual(firstPage, secondPage)
firstPage.addSketchLayer(nil)
firstPage.index = 1
XCTAssertNotEqual(firstPage, secondPage)
secondPage.addSketchLayer(nil)
XCTAssertEqual(firstPage, secondPage)
}
func testRemoveLayer() {
let page = DocumentPage(index: 0)
page.addSketchLayer(nil)
page.addTextLayer("Text testlayer")
let layerCount = page.layers.count
let layer = TextLayer(index: 1, docPage: page, origin: .zero, size: CGSize.zero, text: "This ist not the orginal Textlayer")
page.removeLayer(layer) // nothing should happen because layer is not in layers array
XCTAssertEqual(page.layers.count, layerCount)
page.removeLayer(page.layers[0])
XCTAssertEqual(page.layers.count, layerCount-1)
XCTAssertEqual(page.layers[0].type, DocumentLayerType.text)
}
func testSwapLayer() {
let page = DocumentPage(index: 0)
page.addSketchLayer(nil)
page.addTextLayer("Text testlayer")
let firstLayer = page[0]
let secondLayer = page[1]
page.swapLayerPositions(0, secondIndex: 2) // nothing should happen because secondIndex is out of range
XCTAssertEqual(firstLayer, page[0])
XCTAssertEqual(secondLayer, page[1])
page.addSketchLayer(nil)
page.addTextLayer("Text testlayer")
page.addSketchLayer(nil)
page.addTextLayer("Text testlayer")
page.addSketchLayer(nil)
page.addTextLayer("Text testlayer")
let oldPage = page
page.swapLayerPositions(0, secondIndex: 1)
XCTAssertEqual(firstLayer, page[1])
XCTAssertEqual(secondLayer, page[0])
page.swapLayerPositions(1, secondIndex: 0)
XCTAssertEqual(oldPage, page)
}
func testEncodeDecode() {
let page = DocumentPage(index: 0)
page.addSketchLayer(nil)
page.addTextLayer("Text testlayer")
page.swapLayerPositions(0, secondIndex: 1)
let archivedPageData = NSKeyedArchiver.archivedData(withRootObject: page)
let unarchivedPage = NSKeyedUnarchiver.unarchiveObject(with: archivedPageData) as? DocumentPage
XCTAssertEqual(page, unarchivedPage)
let pdfPage = DocumentPage(index: 0)
let pdfURL = Bundle(for: type(of: self)).url(forResource: "test", withExtension: "pdf")!
let documentRef = CGPDFDocument(pdfURL as CFURL)!
pdfPage.addPDFLayer(PDFUtility.getPageAsData(1, document: documentRef)! as Data)
let archivedPDFPageData = NSKeyedArchiver.archivedData(withRootObject: pdfPage)
let unarchivedPDFPage = NSKeyedUnarchiver.unarchiveObject(with: archivedPDFPageData) as? DocumentPage
XCTAssertEqual(unarchivedPDFPage, pdfPage)
}
}
|
mit
|
PerfectExamples/staffDirectory
|
Sources/staffDirectory/handlers/HandlerHelpers.swift
|
2
|
1620
|
//
// HandlerHelpers.swift
// Perfect-App-Template
//
// Created by Jonathan Guthrie on 2017-04-01.
//
//
import PerfectHTTP
import StORM
extension Handlers {
static func error(_ request: HTTPRequest, _ response: HTTPResponse, error: String, code: HTTPResponseStatus = .badRequest) {
do {
response.status = code
try response.setBody(json: ["error": "\(error)"])
} catch {
print(error)
}
response.completed()
}
static func unimplemented(data: [String:Any]) throws -> RequestHandler {
return {
request, response in
response.status = .notImplemented
response.completed()
}
}
// Common helper function to dump rows to JSON
static func nestedDataDict(_ rows: [StORM]) -> [Any] {
var d = [Any]()
for i in rows {
d.append(i.asDataDict())
}
return d
}
// Used for healthcheck functionality for monitors and load balancers.
// Do not remove unless you have an alternate plan
static func healthcheck(data: [String:Any]) throws -> RequestHandler {
return {
request, response in
let _ = try? response.setBody(json: ["health": "ok"])
response.completed()
}
}
// Handles psuedo redirects.
// Will serve up alternate content, for example if you wish to report an error condition, like missing data.
static func redirectRequest(_ request: HTTPRequest, _ response: HTTPResponse, msg: String, template: String, additional: [String:String] = [String:String]()) {
var context: [String : Any] = [
"msg": msg
]
for i in additional {
context[i.0] = i.1
}
response.render(template: template, context: context)
response.completed()
return
}
}
|
apache-2.0
|
loganSims/wsdot-ios-app
|
wsdot/TwitterCell.swift
|
2
|
1019
|
//
// TwitterCell.swift
// WSDOT
//
// Copyright (c) 2016 Washington State Department of Transportation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>
//
import UIKit
class TwitterCell: UITableViewCell {
@IBOutlet weak var mediaImageView: UIImageView!
@IBOutlet weak var iconView: UIImageView!
@IBOutlet weak var contentLabel: INDLinkLabel!
@IBOutlet weak var publishedLabel: UILabel!
}
|
gpl-3.0
|
natecook1000/swift-compiler-crashes
|
crashes-duplicates/19563-no-stacktrace.swift
|
11
|
213
|
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
lazy
}
{
enum A {
let a {
{
class
case c,
{
|
mit
|
natecook1000/swift-compiler-crashes
|
crashes-duplicates/18833-swift-sourcemanager-getmessage.swift
|
11
|
214
|
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
( [ {
protocol a {
enum e {
{
}
class
case ,
|
mit
|
natecook1000/swift-compiler-crashes
|
crashes-duplicates/07582-swift-unboundgenerictype-get.swift
|
11
|
291
|
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class a<l {
class A? {
class A")
func p() { p()
func g: A? {
enum e : P {
}
}
protocol A {
func a
typealias B : a {
class
|
mit
|
RxSwiftCommunity/RxGesture
|
Example/RxGesture/AppDelegate.swift
|
1
|
266
|
//
// AppDelegate.swift
// RxGesture
//
// Created by Marin Todorov on 03/22/2016.
// Copyright (c) 2016 Marin Todorov. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
}
|
mit
|
jwfriese/FrequentFlyer
|
FrequentFlyerTests/Pipelines/PublicPipelinesViewControllerSpec.swift
|
1
|
14310
|
import XCTest
import Quick
import Nimble
import Fleet
import RxSwift
@testable import FrequentFlyer
class PublicPipelinesViewControllerSpec: QuickSpec {
class MockPublicPipelinesDataStreamProducer: PublicPipelinesDataStreamProducer {
var pipelinesGroupsSubject = PublishSubject<[PipelineGroupSection]>()
var capturedConcourseURL: String?
override func openStream(forConcourseWithURL concourseURL: String) -> Observable<[PipelineGroupSection]> {
capturedConcourseURL = concourseURL
return pipelinesGroupsSubject
}
}
override func spec() {
describe("PublicPipelinesViewController"){
var subject: PublicPipelinesViewController!
var mockPublicPipelinesDataStreamProducer: MockPublicPipelinesDataStreamProducer!
var mockJobsViewController: JobsViewController!
var mockTeamsViewController: TeamsViewController!
var mockConcourseEntryViewController: ConcourseEntryViewController!
beforeEach {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
subject = storyboard.instantiateViewController(withIdentifier: PublicPipelinesViewController.storyboardIdentifier) as! PublicPipelinesViewController
mockJobsViewController = try! storyboard.mockIdentifier(JobsViewController.storyboardIdentifier, usingMockFor: JobsViewController.self)
mockTeamsViewController = try! storyboard.mockIdentifier(TeamsViewController.storyboardIdentifier, usingMockFor: TeamsViewController.self)
mockConcourseEntryViewController = try! storyboard.mockIdentifier(ConcourseEntryViewController.storyboardIdentifier, usingMockFor: ConcourseEntryViewController.self)
subject.concourseURLString = "concourseURL"
mockPublicPipelinesDataStreamProducer = MockPublicPipelinesDataStreamProducer()
subject.publicPipelinesDataStreamProducer = mockPublicPipelinesDataStreamProducer
}
describe("After the view has loaded") {
beforeEach {
_ = Fleet.setInAppWindowRootNavigation(subject)
}
it("sets the title") {
expect(subject.title).to(equal("Pipelines"))
}
it("sets the data source as the delegate of the table view") {
expect(subject.pipelinesTableView?.rx.delegate.forwardToDelegate()).toEventually(beIdenticalTo(subject.publicPipelinesTableViewDataSource))
}
it("opens the data stream") {
expect(mockPublicPipelinesDataStreamProducer.capturedConcourseURL).to(equal("concourseURL"))
}
it("has an active loading indicator") {
expect(subject.loadingIndicator?.isAnimating).toEventually(beTrue())
expect(subject.loadingIndicator?.isHidden).toEventually(beFalse())
}
it("hides the table views row lines while there is no content") {
expect(subject.pipelinesTableView?.separatorStyle).toEventually(equal(UITableViewCellSeparatorStyle.none))
}
describe("Tapping the gear in the navigation item") {
beforeEach {
subject.gearBarButtonItem?.tap()
}
describe("Tapping the 'Log Into a Team' button in the action sheet") {
it("sends the app to the \(TeamsViewController.self)") {
let actionSheet: () -> UIAlertController? = {
return Fleet.getApplicationScreen()?.topmostViewController as? UIAlertController
}
var actionSheetDidAppear = false
var didAttemptLogIntoATeamTap = false
let assertDidBeginLoggingIntoATeam: () -> Bool = {
if !actionSheetDidAppear {
if actionSheet() != nil {
actionSheetDidAppear = true
}
return false
}
if !didAttemptLogIntoATeamTap {
actionSheet()!.tapAlertAction(withTitle: "Log Into a Team")
didAttemptLogIntoATeamTap = true
return false
}
return Fleet.getApplicationScreen()?.topmostViewController === mockTeamsViewController
}
expect(assertDidBeginLoggingIntoATeam()).toEventually(beTrue())
}
}
describe("Tapping the 'Select a Concourse' button in the action sheet") {
it("sends the app to the \(ConcourseEntryViewController.self)") {
let actionSheet: () -> UIAlertController? = {
return Fleet.getApplicationScreen()?.topmostViewController as? UIAlertController
}
var actionSheetDidAppear = false
var didAttemptSelectAConcourseTap = false
let assertDidBeginSelectingAConcourse: () -> Bool = {
if !actionSheetDidAppear {
if actionSheet() != nil {
actionSheetDidAppear = true
}
return false
}
if !didAttemptSelectAConcourseTap {
actionSheet()!.tapAlertAction(withTitle: "Select a Concourse")
didAttemptSelectAConcourseTap = true
return false
}
return Fleet.getApplicationScreen()?.topmostViewController === mockConcourseEntryViewController
}
expect(assertDidBeginSelectingAConcourse()).toEventually(beTrue())
}
}
describe("Tapping the 'Cancel' button in the action sheet") {
it("dismisses the action sheet") {
let actionSheet: () -> UIAlertController? = {
return Fleet.getApplicationScreen()?.topmostViewController as? UIAlertController
}
var actionSheetDidAppear = false
var didAttemptLogOutTap = false
let assertDidDismissActionSheet: () -> Bool = {
if !actionSheetDidAppear {
if actionSheet() != nil {
actionSheetDidAppear = true
}
return false
}
if !didAttemptLogOutTap {
actionSheet()!.tapAlertAction(withTitle: "Cancel")
didAttemptLogOutTap = true
return false
}
return Fleet.getApplicationScreen()?.topmostViewController === subject
}
expect(assertDidDismissActionSheet()).toEventually(beTrue())
}
}
}
describe("When the public pipelines data stream spits out some pipelines") {
beforeEach {
let pipelineOne = Pipeline(name: "pipeline one", isPublic: true, teamName: "cat")
let pipelineTwo = Pipeline(name: "pipeline two", isPublic: true, teamName: "turtle")
let pipelineThree = Pipeline(name: "pipeline three", isPublic: true, teamName: "dog")
var catSection = PipelineGroupSection()
catSection.items.append(pipelineOne)
var turtleSection = PipelineGroupSection()
turtleSection.items.append(pipelineTwo)
var dogSection = PipelineGroupSection()
dogSection.items.append(pipelineThree)
mockPublicPipelinesDataStreamProducer.pipelinesGroupsSubject.onNext([catSection, turtleSection, dogSection])
mockPublicPipelinesDataStreamProducer.pipelinesGroupsSubject.onCompleted()
RunLoop.main.run(mode: RunLoopMode.defaultRunLoopMode, before: Date(timeIntervalSinceNow: 1))
}
it("stops and hides the loading indicator") {
expect(subject.loadingIndicator?.isAnimating).toEventually(beFalse())
expect(subject.loadingIndicator?.isHidden).toEventually(beTrue())
}
it("shows the table views row lines") {
expect(subject.pipelinesTableView?.separatorStyle).toEventually(equal(UITableViewCellSeparatorStyle.singleLine))
}
it("creates a cell in each of the rows for each of the pipelines returned") {
let cellOne = subject.pipelinesTableView!.fetchCell(at: IndexPath(row: 0, section: 0), asType: PipelineTableViewCell.self)
expect(cellOne.nameLabel?.text).to(equal("pipeline one"))
let cellTwo = subject.pipelinesTableView!.fetchCell(at: IndexPath(row: 0, section: 1), asType: PipelineTableViewCell.self)
expect(cellTwo.nameLabel?.text).to(equal("pipeline two"))
}
describe("Tapping one of the cells") {
beforeEach {
subject.pipelinesTableView!.selectRow(at: IndexPath(row: 0, section: 0))
}
it("sets up and presents the pipeline's jobs page") {
func jobsViewController() -> JobsViewController? {
return Fleet.getApplicationScreen()?.topmostViewController as? JobsViewController
}
expect(jobsViewController()).toEventually(beIdenticalTo(mockJobsViewController))
expect(jobsViewController()?.pipeline).toEventually(equal(Pipeline(name: "pipeline one", isPublic: true, teamName: "cat")))
expect(jobsViewController()?.target).toEventually(beNil())
expect(jobsViewController()?.dataStream).toEventually(beAKindOf(PublicJobsDataStream.self))
expect((jobsViewController()?.dataStream as? PublicJobsDataStream)?.concourseURL).toEventually(equal("concourseURL"))
}
it("immediately deselects the cell") {
let selectedCell = subject.pipelinesTableView?.cellForRow(at: IndexPath(row: 0, section: 0))
expect(selectedCell).toEventuallyNot(beNil())
expect(selectedCell?.isHighlighted).toEventually(beFalse())
expect(selectedCell?.isSelected).toEventually(beFalse())
}
}
}
describe("When the public pipelines data stream emits an error") {
beforeEach {
mockPublicPipelinesDataStreamProducer.pipelinesGroupsSubject.onError(UnexpectedError(""))
RunLoop.main.run(mode: RunLoopMode.defaultRunLoopMode, before: Date(timeIntervalSinceNow: 1))
}
it("stops and hides the loading indicator") {
expect(subject.loadingIndicator?.isAnimating).toEventually(beFalse())
expect(subject.loadingIndicator?.isHidden).toEventually(beTrue())
}
it("shows the table views row lines") {
expect(subject.pipelinesTableView?.separatorStyle).toEventually(equal(UITableViewCellSeparatorStyle.singleLine))
}
it("presents an alert describing the error") {
let alert: () -> UIAlertController? = {
return Fleet.getApplicationScreen()?.topmostViewController as? UIAlertController
}
expect(alert()).toEventuallyNot(beNil())
expect(alert()?.title).toEventually(equal("Error"))
expect(alert()?.message).toEventually(equal("An unexpected error has occurred. Please try again."))
}
describe("Tapping the 'OK' button on the alert") {
it("dismisses the alert") {
let screen = Fleet.getApplicationScreen()
var didTapOK = false
let assertOKTappedBehavior = { () -> Bool in
if didTapOK {
return screen?.topmostViewController === subject
}
if let alert = screen?.topmostViewController as? UIAlertController {
alert.tapAlertAction(withTitle: "OK")
didTapOK = true
}
return false
}
expect(assertOKTappedBehavior()).toEventually(beTrue())
}
}
}
}
}
}
}
|
apache-2.0
|
airspeedswift/swift-compiler-crashes
|
crashes-fuzzing/01884-swift-typechecker-resolvetypeincontext.swift
|
1
|
247
|
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let b {
protocol d {
typealias d: d
struct d: a
protocol a {
{
}
}
{
}
func >
|
mit
|
airspeedswift/swift-compiler-crashes
|
crashes-fuzzing/01215-swift-optional-swift-diagnostic-operator.swift
|
12
|
224
|
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func l<c {
{
}
class l {
func m {
b } let c = a
func b
|
mit
|
Fenrikur/ef-app_ios
|
EurofurenceTests/Presenter Tests/Tutorial/WhenThePerformInitialDownloadPageAppearsWithCellularNetwork.swift
|
1
|
2520
|
@testable import Eurofurence
import EurofurenceModel
import XCTest
class WhenThePerformInitialDownloadPageAppearsWithCellularNetwork: XCTestCase {
var context: TutorialModuleTestBuilder.Context!
override func setUp() {
super.setUp()
context = TutorialModuleTestBuilder()
.with(CellularNetwork())
.with(UserAcknowledgedPushPermissions())
.build()
}
func testTappingThePrimaryButtonTellsAlertRouterToShowAlert() {
context.page.simulateTappingPrimaryActionButton()
XCTAssertTrue(context.alertRouter.didShowAlert)
}
func testTappingThePrimaryButtonShouldNotCompleteTutorial() {
context.page.simulateTappingPrimaryActionButton()
XCTAssertFalse(context.delegate.wasToldTutorialFinished)
}
func testTappingThePrimaryButtonTellsAlertRouterToShowAlertWithWarnUserAboutCellularDownloadsTitle() {
context.page.simulateTappingPrimaryActionButton()
XCTAssertEqual(context.alertRouter.presentedAlertTitle, .cellularDownloadAlertTitle)
}
func testTappingThePrimaryButtonTellsAlertRouterToShowAlertWithWarnUserAboutCellularDownloadsMessage() {
context.page.simulateTappingPrimaryActionButton()
XCTAssertEqual(context.alertRouter.presentedAlertMessage, .cellularDownloadAlertMessage)
}
func testTappingThePrimaryButtonTellsAlertRouterToShowAlertWithContinueDownloadOverCellularAction() {
context.page.simulateTappingPrimaryActionButton()
let action = context.alertRouter.presentedActions.first
XCTAssertEqual(action?.title, .cellularDownloadAlertContinueOverCellularTitle)
}
func testTappingThePrimaryButtonTellsAlertRouterToShowAlertWithCancelAction() {
context.page.simulateTappingPrimaryActionButton()
let action = context.alertRouter.presentedActions.last
XCTAssertEqual(action?.title, .cancel)
}
func testTappingThePrimaryButtonThenInvokingFirstActionShouldTellTheDelegateTheTutorialFinished() {
context.page.simulateTappingPrimaryActionButton()
context.alertRouter.presentedActions.first?.invoke()
XCTAssertTrue(context.delegate.wasToldTutorialFinished)
}
func testTappingThePrimaryButtonThenInvokingFirstActionShouldMarkTheTutorialAsComplete() {
context.page.simulateTappingPrimaryActionButton()
context.alertRouter.presentedActions.first?.invoke()
XCTAssertTrue(context.tutorialStateProviding.didMarkTutorialAsComplete)
}
}
|
mit
|
Fenrikur/ef-app_ios
|
EurofurenceTests/Director/Test Doubles/StubDealerDetailModuleFactory.swift
|
1
|
422
|
@testable import Eurofurence
import EurofurenceModel
import EurofurenceModelTestDoubles
import UIKit
class StubDealerDetailModuleProviding: DealerDetailModuleProviding {
let stubInterface = UIViewController()
private(set) var capturedModel: DealerIdentifier?
func makeDealerDetailModule(for dealer: DealerIdentifier) -> UIViewController {
capturedModel = dealer
return stubInterface
}
}
|
mit
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.