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 |
---|---|---|---|---|---|
rondinellimorais/RMExtensionKit | Example/RMExtensionKit/AppDelegate.swift | 1 | 2131 | //
// AppDelegate.swift
// RMExtensionKit
//
// Created by Rondinelli Morais on 10/31/2016.
// Copyright (c) 2016 Rondinelli Morais. 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 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 |
apple/swift-nio | IntegrationTests/tests_04_performance/test_01_resources/test_1000000_asyncwriter.swift | 1 | 1228 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2022 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOCore
import DequeModule
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
fileprivate struct Delegate: NIOAsyncWriterSinkDelegate, Sendable {
typealias Element = Int
func didYield(contentsOf sequence: Deque<Int>) {}
func didTerminate(error: Error?) {}
}
func run(identifier: String) {
guard #available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) else {
return
}
measure(identifier: identifier) {
let delegate = Delegate()
let newWriter = NIOAsyncWriter<Int, Delegate>.makeWriter(isWritable: true, delegate: delegate)
let writer = newWriter.writer
for i in 0..<1000000 {
try! await writer.yield(i)
}
return 1000000
}
}
| apache-2.0 |
evgenyneu/walk-to-circle-ios | walk to circleTests/iiDateTests.swift | 1 | 476 | import UIKit
import WalkToCircle
import XCTest
class iiDateTests: XCTestCase {
func testGetDateAsString() {
let date = iiDate.fromYearMonthDay(2072, month: 4, day: 7)!
let result = iiDate.toStringAsYearMonthDay(date)
XCTAssertEqual("2072.4.7", result)
}
func testGetDateFromYearMonthDay() {
let date = iiDate.fromYearMonthDay(2017, month: 12, day: 26)!
let result = iiDate.toStringAsYearMonthDay(date)
XCTAssertEqual("2017.12.26", result)
}
} | mit |
kevintulod/CascadeKit-iOS | CascadeKit/CascadeKit/Helpers/Extensions/UIScreen+Extras.swift | 1 | 336 | //
// UIScreen+Extras.swift
// CascadeKit
//
// Created by Kevin Tulod on 1/7/17.
// Copyright © 2017 Kevin Tulod. All rights reserved.
//
import UIKit
extension UIScreen {
/// Returns the exact value of one pixel in the current screen's scale
var onePx: CGFloat {
return CGFloat(1)/nativeScale
}
}
| mit |
firebase/firebase-ios-sdk | FirebaseMessaging/Apps/AdvancedSample/SampleWatchWatchKitExtension/ExtensionDelegate.swift | 2 | 1718 | // 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 WatchKit
import FirebaseCore
import FirebaseMessaging
class ExtensionDelegate: NSObject, WKExtensionDelegate, MessagingDelegate {
func applicationDidFinishLaunching() {
FirebaseApp.configure()
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound]) { granted, error in
if granted {
WKExtension.shared().registerForRemoteNotifications()
}
}
Messaging.messaging().delegate = self
}
/// MessagingDelegate
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
print("token:\n" + fcmToken!)
Messaging.messaging().subscribe(toTopic: "watch") { error in
if error != nil {
print("error:" + error.debugDescription)
} else {
print("Successfully subscribed to topic")
}
}
}
/// WKExtensionDelegate
func didRegisterForRemoteNotifications(withDeviceToken deviceToken: Data) {
/// Swizzling should be disabled in Messaging for watchOS, set APNS token manually.
print("Set APNS Token\n")
Messaging.messaging().apnsToken = deviceToken
}
}
| apache-2.0 |
fizx/jane | ruby/lib/vendor/grpc-swift/Sources/protoc-gen-swiftgrpc/io.swift | 1 | 1684 | /*
* Copyright 2017, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
// The I/O code below is derived from Apple's swift-protobuf project.
// https://github.com/apple/swift-protobuf
// BEGIN swift-protobuf derivation
#if os(Linux)
import Glibc
#else
import Darwin.C
#endif
enum PluginError: Error {
/// Raised for any errors reading the input
case readFailure
}
// Alias clib's write() so Stdout.write(bytes:) can call it.
private let _write = write
class Stdin {
static func readall() throws -> Data {
let fd: Int32 = 0
let buffSize = 32
var buff = [UInt8]()
while true {
var fragment = [UInt8](repeating: 0, count: buffSize)
let count = read(fd, &fragment, buffSize)
if count < 0 {
throw PluginError.readFailure
}
if count < buffSize {
buff += fragment[0..<count]
return Data(bytes: buff)
}
buff += fragment
}
}
}
class Stdout {
static func write(bytes: Data) {
bytes.withUnsafeBytes { (p: UnsafePointer<UInt8>) -> Void in
_ = _write(1, p, bytes.count)
}
}
}
// END swift-protobuf derivation
| mit |
indexsky/ShiftPoint | ShiftPoint/ShiftPoint/Bouncer.swift | 2 | 2479 | //
// Bouncer.swift
// ShiftPoint
//
// Created by Ashton Wai on 3/4/16.
// Copyright © 2016 Ashton Wai & Zachary Bebel. All rights reserved.
//
import SpriteKit
class Bouncer : Enemy {
let score: Int = Config.Enemy.Bouncer.BOUNCER_SCORE
let hp: Int = Config.Enemy.Bouncer.BOUNCER_HEALTH
let color: SKColor = Config.Enemy.Bouncer.BOUNCER_COLOR
let bouncerSize: CGSize = Config.Enemy.Bouncer.BOUNCER_SIZE
var velocity: CGPoint = CGPoint.zero
var delta: CGFloat
// MARK: - Initialization -
init(pos: CGPoint, gameScene: GameScene) {
self.delta = CGFloat(Int.random(20...30))
super.init(size: bouncerSize, scorePoints: score, hitPoints: hp, typeColor: color, gameScene: gameScene)
let threshold: CGFloat = 10
let vector = CGPoint(
x: CGFloat.random(cos(threshold * degreesToRadians),max:cos((180 - threshold) * degreesToRadians)),
y: CGFloat.random(sin(threshold * degreesToRadians),max:sin((180 - threshold) * degreesToRadians))
)
self.forward = vector.normalized() // bottom facing up
//self.forward = CGPoint.randomUnitVector()
let width = bouncerSize.width
let height = bouncerSize.height
let center = CGPoint(x: -width/2, y: -height/2)
self.name = "bouncer"
self.position = pos
self.zPosition = Config.GameLayer.Sprite
self.path = CGPath(rect: CGRect(origin: center, size: bouncerSize), transform: nil)
self.fillColor = SKColor.clear
self.strokeColor = color
self.lineWidth = 3
self.physicsBody = SKPhysicsBody(rectangleOf: bouncerSize)
self.physicsBody?.isDynamic = true
self.physicsBody?.categoryBitMask = PhysicsCategory.Enemy
self.physicsBody?.contactTestBitMask = PhysicsCategory.Bullet
self.physicsBody?.collisionBitMask = PhysicsCategory.OuterBounds
self.physicsBody?.angularDamping = 0
self.physicsBody?.linearDamping = 0
self.physicsBody?.restitution = 1
self.physicsBody?.friction = 0
self.physicsBody?.allowsRotation = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Movement Controls -
override func move() {
self.physicsBody?.applyImpulse(CGVector(dx: forward.x * delta, dy: forward.y * delta))
}
}
| mit |
tryswift/trySwiftData | TrySwiftData/ViewModels/SessionViewModel/SessionTypeViewModels/SessionDisplayableTypes/OfficeHoursSessionViewModel.swift | 1 | 1728 | //
// OfficeHoursSessionViewModel.swift
// Pods
//
// Created by Natasha Murashev on 3/23/17.
//
//
struct OfficeHoursSessionViewModel: SessionDisplayable {
private let session: Session
private let dataDefaults: SessionDataDefaults
init?(_ session: Session) {
if session.type == .officeHours {
self.session = session
dataDefaults = SessionDataDefaults(session: session)
} else {
return nil
}
}
var title: String {
guard let speaker = session.presentation?.speaker?.localizedName else {
return "Office Hours".localized()
}
return String(format: "Office Hours with %@".localized(), speaker)
}
var presenter: String {
if let presentation = session.presentation {
return presentation.speaker?.localizedName ?? "⁉️"
}
return "⁉️"
}
var imageURL: URL {
if let imageURL = dataDefaults.customImageAssetURL {
return imageURL
}
if let speakerImage = session.presentation?.speaker?.imageURL {
return speakerImage
}
return dataDefaults.imageURL
}
var location: String {
return dataDefaults.location
}
var shortDescription: String {
return "Q&A".localized()
}
var longDescription: String {
return session.presentation?.speaker?.localizedBio ?? dataDefaults.longDescription
}
var selectable: Bool {
return true
}
var twitter: String {
let twitter = session.presentation?.speaker?.twitter ?? dataDefaults.twitter
return "@\(twitter)"
}
}
| mit |
adrfer/swift | validation-test/compiler_crashers_fixed/27827-swift-constraints-simplifylocator.swift | 4 | 257 | // 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
var:{{let
v{class B<f:d
struct d<f:f.c}}{
| apache-2.0 |
adrfer/swift | validation-test/compiler_crashers_fixed/26451-swift-parser-parsedecl.swift | 13 | 257 | // 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
var:{
for h:{
func a{struct Q{
class
case,
| apache-2.0 |
khizkhiz/swift | validation-test/compiler_crashers_fixed/26190-swift-iterabledeclcontext-getmembers.swift | 13 | 299 | // 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
{({{{{{{}{{{{{{{}{{{{{{{{{{{}}{{{{{{{{}{{{(({{{}{{{{{[{{}{{{{{func u(){var:{struct a
| apache-2.0 |
ioscreator/ioscreator | IOSPageControlTutorial/IOSPageControlTutorial/AppDelegate.swift | 1 | 1438 | //
// AppDelegate.swift
// IOSPageControlTutorial
//
// Created by Arthur Knopper on 21/01/2020.
// Copyright © 2020 Arthur Knopper. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| mit |
SafeCar/iOS | Pods/CameraEngine/CameraEngine/CameraEngineDeviceInput.swift | 1 | 1590 | //
// CameraEngineDeviceInput.swift
// CameraEngine2
//
// Created by Remi Robert on 01/02/16.
// Copyright © 2016 Remi Robert. All rights reserved.
//
import UIKit
import AVFoundation
public enum CameraEngineDeviceInputErrorType: ErrorType {
case UnableToAddCamera
case UnableToAddMic
}
class CameraEngineDeviceInput {
private var cameraDeviceInput: AVCaptureDeviceInput?
private var micDeviceInput: AVCaptureDeviceInput?
func configureInputCamera(session: AVCaptureSession, device: AVCaptureDevice) throws {
let possibleCameraInput: AnyObject? = try AVCaptureDeviceInput(device: device)
if let cameraInput = possibleCameraInput as? AVCaptureDeviceInput {
if let currentDeviceInput = self.cameraDeviceInput {
session.removeInput(currentDeviceInput)
}
self.cameraDeviceInput = cameraInput
if session.canAddInput(self.cameraDeviceInput) {
session.addInput(self.cameraDeviceInput)
}
else {
throw CameraEngineDeviceInputErrorType.UnableToAddCamera
}
}
}
func configureInputMic(session: AVCaptureSession, device: AVCaptureDevice) throws {
if self.micDeviceInput != nil {
return
}
try self.micDeviceInput = AVCaptureDeviceInput(device: device)
if session.canAddInput(self.micDeviceInput) {
session.addInput(self.micDeviceInput)
}
else {
throw CameraEngineDeviceInputErrorType.UnableToAddMic
}
}
} | mit |
nanthi1990/SideMenuController | Project/SideMenuController/SideMenuControllerTests/SideMenuControllerTests.swift | 2 | 938 | //
// SideMenuControllerTests.swift
// SideMenuControllerTests
//
// Created by Teodor Patras on 07.03.15.
// Copyright (c) 2015 Teodor Patras. All rights reserved.
//
import UIKit
import XCTest
class SideMenuControllerTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
LYM-mg/DemoTest | 其他功能/MGImagePickerControllerDemo/Pods/SnapKit/Source/ConstraintMaker.swift | 31 | 7210 | //
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
public class ConstraintMaker {
public var left: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.left)
}
public var top: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.top)
}
public var bottom: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.bottom)
}
public var right: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.right)
}
public var leading: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.leading)
}
public var trailing: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.trailing)
}
public var width: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.width)
}
public var height: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.height)
}
public var centerX: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.centerX)
}
public var centerY: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.centerY)
}
@available(*, deprecated:3.0, message:"Use lastBaseline instead")
public var baseline: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.lastBaseline)
}
public var lastBaseline: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.lastBaseline)
}
@available(iOS 8.0, OSX 10.11, *)
public var firstBaseline: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.firstBaseline)
}
@available(iOS 8.0, *)
public var leftMargin: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.leftMargin)
}
@available(iOS 8.0, *)
public var rightMargin: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.rightMargin)
}
@available(iOS 8.0, *)
public var topMargin: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.topMargin)
}
@available(iOS 8.0, *)
public var bottomMargin: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.bottomMargin)
}
@available(iOS 8.0, *)
public var leadingMargin: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.leadingMargin)
}
@available(iOS 8.0, *)
public var trailingMargin: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.trailingMargin)
}
@available(iOS 8.0, *)
public var centerXWithinMargins: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.centerXWithinMargins)
}
@available(iOS 8.0, *)
public var centerYWithinMargins: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.centerYWithinMargins)
}
public var edges: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.edges)
}
public var size: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.size)
}
public var center: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.center)
}
@available(iOS 8.0, *)
public var margins: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.margins)
}
@available(iOS 8.0, *)
public var centerWithinMargins: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.centerWithinMargins)
}
private let item: LayoutConstraintItem
private var descriptions = [ConstraintDescription]()
internal init(item: LayoutConstraintItem) {
self.item = item
self.item.prepare()
}
internal func makeExtendableWithAttributes(_ attributes: ConstraintAttributes) -> ConstraintMakerExtendable {
let description = ConstraintDescription(item: self.item, attributes: attributes)
self.descriptions.append(description)
return ConstraintMakerExtendable(description)
}
internal static func prepareConstraints(item: LayoutConstraintItem, closure: (_ make: ConstraintMaker) -> Void) -> [Constraint] {
let maker = ConstraintMaker(item: item)
closure(maker)
var constraints: [Constraint] = []
for description in maker.descriptions {
guard let constraint = description.constraint else {
continue
}
constraints.append(constraint)
}
return constraints
}
internal static func makeConstraints(item: LayoutConstraintItem, closure: (_ make: ConstraintMaker) -> Void) {
let constraints = prepareConstraints(item: item, closure: closure)
for constraint in constraints {
constraint.activateIfNeeded(updatingExisting: false)
}
}
internal static func remakeConstraints(item: LayoutConstraintItem, closure: (_ make: ConstraintMaker) -> Void) {
self.removeConstraints(item: item)
self.makeConstraints(item: item, closure: closure)
}
internal static func updateConstraints(item: LayoutConstraintItem, closure: (_ make: ConstraintMaker) -> Void) {
guard item.constraints.count > 0 else {
self.makeConstraints(item: item, closure: closure)
return
}
let constraints = prepareConstraints(item: item, closure: closure)
for constraint in constraints {
constraint.activateIfNeeded(updatingExisting: true)
}
}
internal static func removeConstraints(item: LayoutConstraintItem) {
let constraints = item.constraints
for constraint in constraints {
constraint.deactivateIfNeeded()
}
}
}
| mit |
aiaio/DesignStudioExpress | DesignStudioExpress/Extensions/RealmSwiftExtension.swift | 1 | 392 | //
// RealmSwiftExtension.swift
// DesignStudioExpress
//
// Created by Kristijan Perusko on 11/16/15.
// Copyright © 2015 Alexander Interactive. All rights reserved.
//
import Foundation
import RealmSwift
extension Results {
// converts the Results object to an array
func toArray<T>(ofType: T.Type) -> [T] {
return (0..<self.count).flatMap { self[$0] as? T }
}
} | mit |
tomterror666/MyLotto | MyLotto/MyLotto/Model/Win.swift | 1 | 2703 | //
// Win.swift
// MyLotto
//
// Created by Andre Heß on 17/04/16.
// Copyright © 2016 Andre Heß. All rights reserved.
//
import UIKit
class Win: NSObject {
var winningDrawingRate:DrawingRate?
var winningNumbers:NSArray?
var winningZusatzZahl:NSInteger
var winningSuperZahl:NSInteger
var guess:Guess
var drawing:Drawing
static func winWithGuessAndDrawing(guess:Guess, drawing:Drawing) -> Win {
let me = Win(guess: guess, drawing: drawing)
return me
}
init(guess:Guess, drawing:Drawing) {
self.guess = guess
self.drawing = drawing
self.winningSuperZahl = -1
self.winningZusatzZahl = -1
self.winningDrawingRate = nil
self.winningNumbers = nil
super.init()
self.checkForWinning()
}
func checkForWinning() {
self.calcWinningNumbers()
self.checkDrawingType()
self.examineWinningDrawingRate()
}
func calcWinningNumbers() {
let winningNumbers = NSMutableArray.init(capacity: 6)
for drawingNumber in self.drawing.drawingNumbers {
if (self.guess.numbers.containsObject(drawingNumber)) {
winningNumbers.addObject(drawingNumber)
}
}
self.winningNumbers = winningNumbers
}
func checkDrawingType() {
if (self.drawing.drawingType == DrawingType.drawingTypeZusatzZahl) {
self.winningSuperZahl = -1
self.winningZusatzZahl = self.guess.numbers.containsObject(NSNumber.init(integer: self.drawing.zusatzZahl!)) ? self.drawing.zusatzZahl! : -1
}
else if (self.drawing.drawingType == DrawingType.drawingTypeSuperZahl) {
self.winningSuperZahl = self.guess.numbers.containsObject(NSNumber.init(integer: self.drawing.superZahl!)) ? self.drawing.superZahl! : -1
self.winningZusatzZahl = -1
}
else if (self.drawing.drawingType == DrawingType.drawingTypeZusatzZahlUndSuperZahl) {
self.winningSuperZahl = self.guess.numbers.containsObject(NSNumber.init(integer: self.drawing.superZahl!)) ? self.drawing.superZahl! : -1
self.winningZusatzZahl = self.guess.numbers.containsObject(NSNumber.init(integer: self.drawing.zusatzZahl!)) ? self.drawing.zusatzZahl! : -1
}
else {
self.winningSuperZahl = -1
self.winningZusatzZahl = -1
}
}
func examineWinningDrawingRate() {
let numberOfWinnings = self.winningNumbers != nil ? self.winningNumbers!.count : 0
for object:AnyObject in self.drawing.rates {
let rate:DrawingRate = object as! DrawingRate
if ((rate.winningConditions == numberOfWinnings) &&
((rate.winningConditions.needsZusatzZahl && (self.winningZusatzZahl > -1)) || !rate.winningConditions.needsZusatzZahl) &&
((rate.winningConditions.needsSuperZahl && (self.winningSuperZahl > -1)) || !rate.winningConditions.needsSuperZahl)) {
self.winningDrawingRate = rate
return
}
}
}
}
| mit |
xwu/swift | test/Generics/sr14580.swift | 1 | 1474 | // RUN: %target-typecheck-verify-swift -requirement-machine-protocol-signatures=on
// RUN: %target-swift-frontend -typecheck -debug-generic-signatures -requirement-machine-protocol-signatures=on %s 2>&1 | %FileCheck %s
public protocol ScalarProtocol: ScalarMultiplicative where Self == Scalar {
}
public protocol ScalarMultiplicative {
associatedtype Scalar: ScalarProtocol
}
public protocol MapReduceArithmetic: ScalarMultiplicative, Collection where Element: ScalarMultiplicative {}
public protocol Tensor: MapReduceArithmetic where Element == Scalar {
}
// CHECK-LABEL: sr14580.(file).ColorModel@
// CHECK-LABEL: Requirement signature: <Self where Self : Tensor, Self == Self.Float16Components.Model, Self.Element == Double, Self.Float16Components : ColorComponents, Self.Float32Components : ColorComponents, Self.Float16Components.Element == Double, Self.Float16Components.Model == Self.Float32Components.Model, Self.Float32Components.Element == Double>
public protocol ColorModel: Tensor where Scalar == Double {
associatedtype Float16Components: ColorComponents where Float16Components.Model == Self, Float16Components.Scalar == Double
associatedtype Float32Components: ColorComponents where Float32Components.Model == Self, Float32Components.Scalar == Double
}
public protocol ColorComponents: Tensor {
associatedtype Model: ColorModel
}
extension Double : ScalarMultiplicative {}
extension Double : ScalarProtocol {
public typealias Scalar = Self
}
| apache-2.0 |
yunuserenguzel/SlidingTabbarController | Example/SlidingTabbarController/ViewController.swift | 1 | 755 | //
// ViewController.swift
// SlidingTabbarExample
//
// Created by Yunus Eren Guzel on 18/02/16.
// Copyright © 2016 yeg. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let imageView = UIImageView()
convenience init(imageName: String) {
self.init()
imageView.image = UIImage(named: imageName)
}
override func viewDidLoad() {
super.viewDidLoad()
imageView.contentMode = .scaleAspectFill
view.addSubview(imageView)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
imageView.frame = view.bounds
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
ahoppen/swift | test/stdlib/IntervalTraps.swift | 10 | 1853 | //===--- IntervalTraps.swift ----------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// RUN: %empty-directory(%t)
// RUN: %target-build-swift %s -o %t/a.out_Debug -Onone
// RUN: %target-build-swift %s -o %t/a.out_Release -O
//
// RUN: %target-codesign %t/a.out_Debug
// RUN: %target-codesign %t/a.out_Release
// RUN: %target-run %t/a.out_Debug
// RUN: %target-run %t/a.out_Release
// REQUIRES: executable_test
// UNSUPPORTED: OS=wasi
import StdlibUnittest
let testSuiteSuffix = _isDebugAssertConfiguration() ? "_debug" : "_release"
var IntervalTraps = TestSuite("IntervalTraps" + testSuiteSuffix)
IntervalTraps.test("HalfOpen")
.skip(.custom(
{ _isFastAssertConfiguration() },
reason: "this trap is not guaranteed to happen in -Ounchecked"))
.code {
var interval = 1.0..<1.0
// FIXME: the plan is for floating point numbers to no longer be
// strideable; then this will drop the "OfStrideable"
expectType(Range<Double>.self, &interval)
expectCrashLater()
_ = 1.0..<0.0
}
IntervalTraps.test("Closed")
.skip(.custom(
{ _isFastAssertConfiguration() },
reason: "this trap is not guaranteed to happen in -Ounchecked"))
.code {
var interval = 1.0...1.0
// FIXME: the plan is for floating point numbers to no longer be
// strideable; then this will drop the "OfStrideable"
expectType(ClosedRange<Double>.self, &interval)
expectCrashLater()
_ = 1.0...0.0
}
runAllTests()
| apache-2.0 |
jwieringa/AllIncomeFoods | iOS/SnapFresh/Extensions/CLLocationCoordinate2D+isValid.swift | 3 | 1145 | /*
* Copyright 2015 Marco Abundo, Ysiad Ferreiras, Aaron Bannert, Jeremy Canfield and Michelle Koeth
*
* 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 CoreLocation
extension CLLocationCoordinate2D {
/*!
* @abstract check for a valid coordinate
*
* @returns true if the coordinate is valid, false otherwise
*/
var isValid: Bool {
get {
var valid = false
if CLLocationCoordinate2DIsValid(self) && (self.latitude != 0.0) && (self.longitude != 0.0) {
valid = true
}
return valid
}
}
}
| apache-2.0 |
Davidde94/StemCode_iOS | StemCode/StemProjectKit/StemGroup.swift | 1 | 3065 | //
// StemGroup.swift
// StemCode
//
// Created by David Evans on 20/04/2018.
// Copyright © 2018 BlackPoint LTD. All rights reserved.
//
import Foundation
import Signals
struct StemGroupCodable: Decodable, Hashable {
let identifier: String
let name: String
let isFolder: Bool
let childGroups: Set<StemGroupCodable>
let childFiles: [String]
}
public final class StemGroup: StemItem, Encodable {
public let identifier: String
public let parentProject: Stem
private(set) public var name: String
private(set) public var isFolder: Bool
private var childFileIdentifiers: [String]
private(set)public var childGroups: Set<StemGroup>
public var childFiles: [StemFile] {
return parentProject.files(for: childFileIdentifiers)
}
private(set) public var parentGroup: StemGroup?
public let nameChanged = Signal<(StemGroup, String)>()
public let fileAdded = Signal<StemFile>()
public let groupAdded = Signal<StemGroup>()
public let removedFromParentGroup = Signal<StemGroup>()
public init(project: Stem, name: String, isFolder: Bool) {
self.parentProject = project
self.name = name
self.isFolder = isFolder
self.childFileIdentifiers = [String]()
self.childGroups = Set<StemGroup>()
self.identifier = NSUUID().uuidString
}
public func addChild(_ child: StemFile) {
child.removeFromParentGroup()
if self.childFileIdentifiers.firstIndex(of: child.identifier) != nil {
return
}
child.parentGroup = self
childFileIdentifiers.append(child.identifier)
child.removedFromParentGroup.subscribe(with: self) { (file) in
let index = self.childFileIdentifiers.firstIndex(of: file.identifier)!
self.childFileIdentifiers.remove(at: index)
child.removedFromParentGroup.cancelSubscription(for: self)
}
fileAdded.fire(child)
}
public func addChild(_ child: StemGroup) {
child.removeFromParentGroup()
if childGroups.contains(child) {
return
}
childGroups.insert(child)
child.removedFromParentGroup.subscribe(with: self) { (group) in
self.childGroups.remove(child)
child.removedFromParentGroup.cancelSubscription(for: self)
}
child.parentGroup = self
groupAdded.fire(child)
}
public func removeFromParentGroup() {
parentGroup = nil
removedFromParentGroup.fire(self)
}
// MARK: - Codable
enum CodingKeys: String, CodingKey {
case identifier
case name
case isFolder
case childGroups
case childFileIdentifiers = "childFiles"
}
init(codableData: StemGroupCodable, parentGroup: StemGroup?, parentProject: Stem) {
self.identifier = codableData.identifier
self.name = codableData.name
self.isFolder = codableData.isFolder
self.parentProject = parentProject
self.childFileIdentifiers = codableData.childFiles
childGroups = Set<StemGroup>()
childGroups = Set<StemGroup>(codableData.childGroups.map { StemGroup(codableData: $0, parentGroup: self, parentProject: parentProject) })
parentProject.files(for: childFileIdentifiers).forEach { (file) in
file.parentGroup = self
}
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/03972-swift-sourcemanager-getmessage.swift | 11 | 246 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
return m(([Void{
[[[[Void{
let end = [Void{
let end = [Void{
{
class
case c,
| mit |
ishepherdMiner/Daily_ui_set | Daily_ui_set/Daily_ui_set/Kit/JABeatView.swift | 1 | 184 | //
// JABeatView.swift
// Daily_ui_set
//
// Created by Jason on 13/12/2016.
// Copyright © 2016 Jason. All rights reserved.
//
import UIKit
class JABeatView: UIView {
}
| mit |
PandaraWen/DJIDemoKit | DJIDemoKit/DDKTableSectionHeader.swift | 1 | 1557 | //
// DDKStartTableSectionHeader.swift
// DJIDemoKitDemo
//
// Created by Pandara on 2017/9/1.
// Copyright © 2017年 Pandara. All rights reserved.
//
import UIKit
import SnapKit
class DDKTableSectionHeader: UITableViewHeaderFooterView {
var titleLabel: UILabel!
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
self.setupSubviews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: UI
fileprivate extension DDKTableSectionHeader {
func setupSubviews() {
let bgView = UIView()
bgView.backgroundColor = UIColor.white
self.addSubview(bgView)
bgView.snp.makeConstraints { (make) in
make.edges.equalTo(self)
}
let headerView = UIView()
headerView.backgroundColor = UIColor(r: 0, g: 140, b: 255, a: 1)
self.addSubview(headerView)
headerView.snp.makeConstraints({ (make) in
make.left.top.bottom.equalTo(self)
make.width.equalTo(4)
})
self.titleLabel = {
let label = UILabel()
label.font = UIFont.boldSystemFont(ofSize: 18)
label.textColor = UIColor.ddkVIBlue
self.addSubview(label)
label.snp.makeConstraints({ (make) in
make.left.equalTo(headerView.snp.right).offset(8)
make.top.right.bottom.equalTo(self)
})
return label
}()
}
}
| mit |
zachmokahn/SUV | Sources/SUV/libUV/Operation/UVTCPConnect.swift | 1 | 55 | import libUV
public let UVTCPConnect = uv_tcp_connect
| mit |
kazuhiro49/StringStylizer | StringStylizer/StringStylizer.swift | 1 | 18974 | //
// StringSerializer.swift
//
// Copyright (c) 2016 Kazuhiro Hayashi
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
/**
Type safely builder class for NSAttributedString.
It makes NSAttributedString more intitive by wrapping method chains and operators.
#### Usage
when you convert String to NSAttributedString which has some colors, sizes and fonts, you can write it in a linear manner.
```
let label = UILabel(frame: CGRectMake(0, 0, 100, 50))
// build NSAttributedString.
let greed = "Hi, ".stylize().color(0x2200ee).size(12).font(.HelveticaNeue).attr
// build NSAttributedString with ranges.
let msg = "something happened ".stylize()
.range(0..<9) .color(0x009911).size(12).font(.HelveticaNeue)
.range(10..<UInt.max).color(0xaa22cc).size(14).font(.HelveticaNeue_Bold).attr
// build NSAttributedString objects and join them.
let name = "to ".stylize().color(0x23abfc).size(12).font(.HelveticaNeue).attr +
"you".stylize().color(0x123456).size(14).font(.HelveticaNeue_Italic).underline(.StyleDouble).attr
label.attributedText = greed + msg + name
```
This sample code generates the following styled label.
<img width="261" src="https://cloud.githubusercontent.com/assets/18266814/14254571/49882d08-facb-11e5-9e3d-c37cbef6a003.png">
*/
public class StringStylizer<T: StringStylizerStatus>: StringLiteralConvertible {
public typealias ExtendedGraphemeClusterLiteralType = String
public typealias UnicodeScalarLiteralType = String
private var _attrString: NSAttributedString
private var _attributes = [String: AnyObject]()
private var _range: Range<UInt>
// MARK:- Initializer
init(string: String, range: Range<UInt>? = nil, attributes: [String: AnyObject] = [String: AnyObject]()) {
let range = range ?? 0..<UInt(string.characters.count)
_attrString = NSAttributedString(string: string)
_attributes = attributes
_range = range
}
init(attributedString: NSAttributedString, range: Range<UInt>, attributes: [String: AnyObject] = [String: AnyObject]()) {
_attrString = attributedString
_attributes = attributes
_range = range
}
public required init(unicodeScalarLiteral value: UnicodeScalarLiteralType) {
_attrString = NSMutableAttributedString(string: value)
_range = 0..<UInt(_attrString.string.characters.count)
}
public required init(stringLiteral value: StringLiteralType) {
_attrString = NSMutableAttributedString(string: value)
_range = 0..<UInt(_attrString.string.characters.count)
}
public required init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) {
_attrString = NSMutableAttributedString(string: value)
_range = 0..<UInt(_attrString.string.characters.count)
}
// MARK:- Attributes
// https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSAttributedString_Class/index.html#//apple_ref/doc/c_ref/NSLinkAttributeName
/**
The value of NSForegroundColorAttributeName
- parameter rgb:UInt
- parameter alpha:Double (default: 1.0)
- returns: StringStylizer<Styling>
*/
public func color(rgb: UInt, alpha: Double = 1.0) -> StringStylizer<Styling> {
_attributes[NSForegroundColorAttributeName] = self.rgb(rgb, alpha: alpha)
let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes)
return stylizer
}
/**
The value of NSForegroundColorAttributeName
- parameter color:UIColor
- returns: StringStylizer<Styling>
*/
public func color(color: UIColor) -> StringStylizer<Styling> {
_attributes[NSForegroundColorAttributeName] = color
let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes)
return stylizer
}
/**
The value of NSFontAttributeName
- parameter font:UIFont
- returns: StringStylizer<Styling>
*/
public func font(font: UIFont) -> StringStylizer<Styling> {
_attributes[NSFontAttributeName] = font
let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes)
return stylizer
}
/**
The name value of NSFontAttributeName
- parameter name:String
- returns: StringStylizer<Styling>
*/
public func font(name: String) -> StringStylizer<Styling> {
let font: UIFont
if let currentFont = _attributes[NSFontAttributeName] as? UIFont {
font = UIFont(name: name, size: currentFont.pointSize) ?? UIFont()
} else {
font = UIFont(name: name, size: UIFont.systemFontSize()) ?? UIFont()
}
_attributes[NSFontAttributeName] = font
let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes)
return stylizer
}
/**
The name value of NSFontAttributeName
- parameter name:StringStylizerFontName
- returns: StringStylizer<Styling>
*/
public func font(name: StringStylizerFontName) -> StringStylizer<Styling> {
let font: UIFont
if let currentFont = _attributes[NSFontAttributeName] as? UIFont {
font = UIFont(name: name.rawValue, size: currentFont.pointSize) ?? UIFont()
} else {
font = UIFont(name: name.rawValue, size: UIFont.systemFontSize()) ?? UIFont()
}
_attributes[NSFontAttributeName] = font
let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes)
return stylizer
}
/**
The size value of NSFontAttributeName
- parameter size:Double
- returns: StringStylizer<Styling>
*/
public func size(size: Double) -> StringStylizer<Styling> {
let font: UIFont
if let currentFont = _attributes[NSFontAttributeName] as? UIFont {
font = UIFont(name: currentFont.fontName, size: CGFloat(size)) ?? UIFont()
} else {
font = UIFont.systemFontOfSize(CGFloat(size))
}
_attributes[NSFontAttributeName] = font
let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes)
return stylizer
}
/**
The value of NSBackgroundColorAttributeName
- parameter rgb:UInt
- parameter alpha:Double (default:1.0)
- returns: StringStylizer<Styling>
*/
public func background(rgb: UInt, alpha: Double = 1.0) -> StringStylizer<Styling> {
_attributes[NSBackgroundColorAttributeName] = self.rgb(rgb, alpha: alpha)
let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes)
return stylizer
}
/**
The value of NSKernAttributeName
- parameter value:Double
- returns: StringStylizer<Styling>
*/
public func karn(value: Double) -> StringStylizer<Styling> {
_attributes[NSKernAttributeName] = value
let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes)
return stylizer
}
/**
The values of NSUnderlineStyleAttributeName and NSUnderlineColorAttributeName
- parameter style:NSUnderlineStyle...
- parameter rgb:UInt? (default:nil)
- parameter alpha:Double (default:1.0)
- returns: StringStylizer<Styling>
*/
public func underline(style: NSUnderlineStyle..., rgb: UInt? = nil, alpha: Double = 1) -> StringStylizer<Styling> {
let _style: [NSUnderlineStyle] = style.isEmpty ? [.StyleSingle] : style
let value = _style.reduce(0) { (sum, elem) -> Int in
return sum | elem.rawValue
}
_attributes[NSUnderlineStyleAttributeName] = value
_attributes[NSUnderlineColorAttributeName] = rgb.flatMap { self.rgb($0, alpha: alpha) }
let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes)
return stylizer
}
/**
The values of NSStrokeWidthAttributeName and NSStrokeColorAttributeName
- parameter rgb:UInt? (default:nil)
- parameter alpha:Double (default:1.0)
- returns: StringStylizer<Styling>
*/
public func stroke(rgb rgb: UInt, alpha: Double = 1.0, width: Double = 1) -> StringStylizer<Styling> {
_attributes[NSStrokeWidthAttributeName] = width
_attributes[NSStrokeColorAttributeName] = self.rgb(rgb, alpha: alpha)
let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes)
return stylizer
}
/**
The values of NSStrokeWidthAttributeName and NSStrokeColorAttributeName
- parameter color:UIColor
- parameter alpha:Double (default:1.0)
- parameter width:Double (default:1.0)
- returns: StringStylizer<Styling>
*/
public func stroke(color color: UIColor, alpha: Double = 1.0, width: Double = 1) -> StringStylizer<Styling> {
_attributes[NSStrokeWidthAttributeName] = width
_attributes[NSStrokeColorAttributeName] = color
let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes)
return stylizer
}
/**
The values of NSStrikethroughStyleAttributeName and NSStrikethroughColorAttributeName
- parameter style:NSUnderlineStyle...
- parameter rgb:UInt? (default:nil)
- parameter alpha:Double (default:1.0)
- returns: StringStylizer<Styling>
*/
public func strokeThrogh(style: NSUnderlineStyle..., rgb: UInt? = nil, alpha: Double = 1) -> StringStylizer<Styling> {
let _style: [NSUnderlineStyle] = style.isEmpty ? [.StyleSingle] : style
let value = _style.reduce(0) { (sum, elem) -> Int in
return sum | elem.rawValue
}
_attributes[NSStrikethroughStyleAttributeName] = value
_attributes[NSStrikethroughColorAttributeName] = rgb.flatMap { self.rgb($0, alpha: alpha) }
let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes)
return stylizer
}
/**
The value of NSShadowAttributeName
- parameter value:NSShadow
- returns: StringStylizer<Styling>
*/
public func shadow(value: NSShadow) -> StringStylizer<Styling> {
_attributes[NSShadowAttributeName] = value
let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes)
return stylizer
}
/**
The value of NSLigatureAttributeName
- parameter value:Int
- returns: StringStylizer<Styling>
*/
public func ligeture(value: Int) -> StringStylizer<Styling> {
_attributes[NSLigatureAttributeName] = value
let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes)
return stylizer
}
/**
The value of NSLinkAttributeName
- parameter url:NSURL
- returns: StringStylizer<Styling>
*/
public func link(url: NSURL) -> StringStylizer<Styling> {
_attributes[NSLinkAttributeName] = url
let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes)
return stylizer
}
/**
The value of NSBaselineOffsetAttributeName
- parameter value:Double
- returns: StringStylizer<Styling>
*/
public func baselineOffset(value: Double) -> StringStylizer<Styling> {
_attributes[NSBaselineOffsetAttributeName] = value
let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes)
return stylizer
}
private func rgb(rgb: UInt, alpha: Double) -> UIColor {
return UIColor(
red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgb & 0x0000FF) / 255.0,
alpha: CGFloat(alpha)
)
}
}
public extension StringStylizer {
public func paragraph(style: NSParagraphStyle) -> StringStylizer<Styling> {
_attributes[NSParagraphStyleAttributeName] = style
let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes)
return stylizer
}
public func paragraphAlignment(alignment: NSTextAlignment) -> StringStylizer<Styling> {
let style: NSMutableParagraphStyle
if let currentStyle = _attributes[NSParagraphStyleAttributeName] as? NSMutableParagraphStyle {
currentStyle.alignment = alignment
style = currentStyle
} else {
style = NSMutableParagraphStyle()
style.alignment = alignment
}
_attributes[NSParagraphStyleAttributeName] = style
let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes)
return stylizer
}
public func paragraphIndent(firstLineHead firstLineHead: CGFloat? = nil, tail: CGFloat? = nil, otherHead: CGFloat? = nil) -> StringStylizer<Styling> {
let style = getParagraphStyle()
if let firstLineHead = firstLineHead {
style.firstLineHeadIndent = firstLineHead
}
if let otherHead = otherHead {
style.headIndent = otherHead
}
if let tail = tail {
style.tailIndent = tail
}
_attributes[NSParagraphStyleAttributeName] = style
let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes)
return stylizer
}
public func paragraphLineBreak(lineBreakMode: NSLineBreakMode) -> StringStylizer<Styling> {
let style = getParagraphStyle()
style.lineBreakMode = lineBreakMode
_attributes[NSParagraphStyleAttributeName] = style
let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes)
return stylizer
}
public func paragraphLineHeight(maximum maximum: CGFloat? = nil, minimum: CGFloat? = nil, multiple: CGFloat? = nil) -> StringStylizer<Styling> {
let style = getParagraphStyle()
if let maximum = maximum {
style.maximumLineHeight = maximum
}
if let minimum = minimum {
style.minimumLineHeight = minimum
}
if let multiple = multiple {
style.lineHeightMultiple = multiple
}
_attributes[NSParagraphStyleAttributeName] = style
let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes)
return stylizer
}
public func paragraphLineSpacing(after after: CGFloat? = nil, before: CGFloat? = nil) -> StringStylizer<Styling> {
let style = getParagraphStyle()
if let after = after {
style.lineSpacing = after
}
if let before = before {
style.paragraphSpacingBefore = before
}
_attributes[NSParagraphStyleAttributeName] = style
let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes)
return stylizer
}
public func paragraphBaseWritingDirection(baseWritingDirection: NSWritingDirection) -> StringStylizer<Styling> {
let style: NSMutableParagraphStyle
if let currentStyle = _attributes[NSParagraphStyleAttributeName] as? NSMutableParagraphStyle {
style = currentStyle
} else {
style = NSMutableParagraphStyle()
}
style.baseWritingDirection = baseWritingDirection
_attributes[NSParagraphStyleAttributeName] = style
let stylizer = StringStylizer<Styling>(attributedString: _attrString, range: _range, attributes: _attributes)
return stylizer
}
public var count: Int {
return _attrString.length
}
private func getParagraphStyle() -> NSMutableParagraphStyle {
if let currentStyle = _attributes[NSParagraphStyleAttributeName] as? NSMutableParagraphStyle {
return currentStyle
} else {
return NSMutableParagraphStyle()
}
}
}
public extension StringStylizer where T: Styling {
/// generates NSAttributedString
public var attr: NSAttributedString {
let range = Int(_range.startIndex)..<Int(_range.endIndex)
let attrString = NSMutableAttributedString(attributedString: _attrString)
attrString.setAttributes(_attributes, range: NSRange(range))
return attrString
}
/**
set range to assign attributes
- parameter range:Range (default: nil)
- returns: StringStylizer<NarrowDown>
*/
public func range(range: Range<UInt>? = nil) -> StringStylizer<NarrowDown> {
let attrString = NSMutableAttributedString(attributedString: _attrString)
attrString.setAttributes(_attributes, range: NSRange(Int(_range.startIndex)..<Int(_range.endIndex)))
let range = range ?? 0..<UInt(attrString.length)
let endIndex = min(range.endIndex, UInt(_attrString.length))
let validRange = range.startIndex..<endIndex
return StringStylizer<NarrowDown>(attributedString: attrString, range: validRange)
}
} | mit |
tbaranes/IncrementableLabel | IncrementableLabel Example/Example/tvOS Example/ViewController.swift | 2 | 1772 | //
// ViewController.swift
// IncrementableLabel
//
// Created by Tom Baranes on 20/01/16.
// Copyright © 2016 Recisio. All rights reserved.
//
import UIKit
import IncrementableLabel
class ViewController: UIViewController {
// MARK: Properties
@IBOutlet weak var label1: IncrementableLabel!
@IBOutlet weak var label2: IncrementableLabel!
@IBOutlet weak var label3: IncrementableLabel!
@IBOutlet weak var label4: IncrementableLabel!
@IBOutlet weak var label5: IncrementableLabel!
// MARK: Life cycle
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: IBAction
@IBAction func startIncrementationPressed(sender: AnyObject) {
label1.increment(fromValue: 0, toValue: 100, duration: 3)
label2.format = "%f"
label2.increment(fromValue: 0.0, toValue: 100.0, duration: 3)
label3.option = .easeInOut
label3.stringFormatter = { value in
return String(format: "EaseInOutAnimation: %d", Int(value))
}
label3.increment(fromValue: 0.0, toValue: 100.0, duration: 3)
label4.option = .easeOut
label4.attributedTextFormatter = { value in
let string = String(format: "EaseOutAnimation + attributedString: %d", Int(value))
let attributedString = NSMutableAttributedString(string: string, attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 16.0)])
return attributedString
}
label4.incrementFromZero(toValue: 1000, duration: 1)
label5.textColor = UIColor.black
label5.incrementFromZero(toValue: 1000, duration: 1) {
self.label5.textColor = UIColor.green
}
}
}
| mit |
mightydeveloper/swift | validation-test/compiler_crashers/27646-swift-markasobjc.swift | 9 | 294 | // RUN: not --crash %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 d<T where g:C{
struct D{struct d<a
class B{
let _=[a:d<f
let a{b
| apache-2.0 |
Aishwarya-Ramakrishnan/sparkios | Source/Phone/ObjectMap/AlertType.swift | 1 | 1319 | // Copyright 2016 Cisco Systems Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import ObjectMapper
struct AlertType: Mappable {
var action: String?
init?(map: Map){
}
mutating func mapping(map: Map) {
action <- map["action"]
}
}
| mit |
Oscareli98/Moya | Demo/DemoTests/MoyaProviderSpec.swift | 2 | 20953 | import Quick
import Moya
import Nimble
import ReactiveCocoa
import RxSwift
class MoyaProviderSpec: QuickSpec {
override func spec() {
describe("valid endpoints") {
describe("with stubbed responses") {
describe("a provider", {
var provider: MoyaProvider<GitHub>!
beforeEach {
provider = MoyaProvider<GitHub>(stubBehavior: MoyaProvider.ImmediateStubbingBehaviour)
}
it("returns stubbed data for zen request") {
var message: String?
let target: GitHub = .Zen
provider.request(target) { (data, statusCode, response, error) in
if let data = data {
message = NSString(data: data, encoding: NSUTF8StringEncoding) as? String
}
}
let sampleData = target.sampleData as NSData
expect(message).to(equal(NSString(data: sampleData, encoding: NSUTF8StringEncoding)))
}
it("returns stubbed data for user profile request") {
var message: String?
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target) { (data, statusCode, response, error) in
if let data = data {
message = NSString(data: data, encoding: NSUTF8StringEncoding) as? String
}
}
let sampleData = target.sampleData as NSData
expect(message).to(equal(NSString(data: sampleData, encoding: NSUTF8StringEncoding)))
}
it("returns equivalent Endpoint instances for the same target") {
let target: GitHub = .Zen
let endpoint1 = provider.endpoint(target)
let endpoint2 = provider.endpoint(target)
expect(endpoint1).to(equal(endpoint2))
}
it("returns a cancellable object when a request is made") {
let target: GitHub = .UserProfile("ashfurrow")
let cancellable: Cancellable = provider.request(target) { (_, _, _, _) in }
expect(cancellable).toNot(beNil())
}
})
it("notifies at the beginning of network requests") {
var called = false
var provider = MoyaProvider<GitHub>(stubBehavior: MoyaProvider.ImmediateStubbingBehaviour, networkActivityClosure: { (change) -> () in
if change == .Began {
called = true
}
})
let target: GitHub = .Zen
provider.request(target) { (data, statusCode, response, error) in }
expect(called) == true
}
it("notifies at the end of network requests") {
var called = false
var provider = MoyaProvider<GitHub>(stubBehavior: MoyaProvider.ImmediateStubbingBehaviour, networkActivityClosure: { (change) -> () in
if change == .Ended {
called = true
}
})
let target: GitHub = .Zen
provider.request(target) { (data, statusCode, response, error) in }
expect(called) == true
}
describe("a provider with lazy data", { () -> () in
var provider: MoyaProvider<GitHub>!
beforeEach {
provider = MoyaProvider<GitHub>(endpointClosure: lazyEndpointClosure, stubBehavior: MoyaProvider.ImmediateStubbingBehaviour)
}
it("returns stubbed data for zen request") {
var message: String?
let target: GitHub = .Zen
provider.request(target) { (data, statusCode, response, error) in
if let data = data {
message = NSString(data: data, encoding: NSUTF8StringEncoding) as? String
}
}
let sampleData = target.sampleData as NSData
expect(message).to(equal(NSString(data: sampleData, encoding: NSUTF8StringEncoding)))
}
})
it("delays execution when appropriate") {
let provider = MoyaProvider<GitHub>(stubBehavior: MoyaProvider.DelayedStubbingBehaviour(2))
let startDate = NSDate()
var endDate: NSDate?
let target: GitHub = .Zen
waitUntil(timeout: 3) { done in
provider.request(target) { (data, statusCode, response, error) in
endDate = NSDate()
done()
}
return
}
expect{
return endDate?.timeIntervalSinceDate(startDate)
}.to( beGreaterThanOrEqualTo(NSTimeInterval(2)) )
}
describe("a provider with a custom endpoint resolver") { () -> () in
var provider: MoyaProvider<GitHub>!
var executed = false
let newSampleResponse = "New Sample Response"
beforeEach {
executed = false
let endpointResolution = { (endpoint: Endpoint<GitHub>) -> (NSURLRequest) in
executed = true
return endpoint.urlRequest
}
provider = MoyaProvider<GitHub>(endpointResolver: endpointResolution, stubBehavior: MoyaProvider.ImmediateStubbingBehaviour)
}
it("executes the endpoint resolver") {
let target: GitHub = .Zen
provider.request(target, completion: { (data, statusCode, response, error) in })
let sampleData = target.sampleData as NSData
expect(executed).to(beTruthy())
}
}
describe("a reactive provider", { () -> () in
var provider: ReactiveCocoaMoyaProvider<GitHub>!
beforeEach {
provider = ReactiveCocoaMoyaProvider<GitHub>(stubBehavior: MoyaProvider.ImmediateStubbingBehaviour)
}
it("returns a MoyaResponse object") {
var called = false
provider.request(.Zen).subscribeNext { (object) -> Void in
if let response = object as? MoyaResponse {
called = true
}
}
expect(called).to(beTruthy())
}
it("returns stubbed data for zen request") {
var message: String?
let target: GitHub = .Zen
provider.request(target).subscribeNext { (object) -> Void in
if let response = object as? MoyaResponse {
message = NSString(data: response.data, encoding: NSUTF8StringEncoding) as? String
}
}
let sampleData = target.sampleData as NSData
expect(message).toNot(beNil())
}
it("returns correct data for user profile request") {
var receivedResponse: NSDictionary?
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target).subscribeNext { (object) -> Void in
if let response = object as? MoyaResponse {
receivedResponse = NSJSONSerialization.JSONObjectWithData(response.data, options: nil, error: nil) as? NSDictionary
}
}
let sampleData = target.sampleData as NSData
let sampleResponse: NSDictionary = NSJSONSerialization.JSONObjectWithData(sampleData, options: nil, error: nil) as! NSDictionary
expect(receivedResponse).toNot(beNil())
}
it("returns identical signals for inflight requests") {
let target: GitHub = .Zen
var response: MoyaResponse!
// The synchronous nature of stubbed responses makes this kind of tricky. We use the
// subscribeNext closure to get the provider into a state where the signal has been
// added to the inflightRequests dictionary. Then we ask for an identical request,
// which should return the same signal. We can't *test* those signals equivalency
// due to the use of RACSignal.defer, but we can check if the number of inflight
// requests went up or not.
let outerSignal = provider.request(target)
outerSignal.subscribeNext { (object) -> Void in
response = object as? MoyaResponse
expect(provider.inflightRequests.count).to(equal(1))
// Create a new signal and force subscription, so that the inflightRequests dictionary is accessed.
let innerSignal = provider.request(target)
innerSignal.subscribeNext { (object) -> Void in
// nop
}
expect(provider.inflightRequests.count).to(equal(1))
}
expect(provider.inflightRequests.count).to(equal(0))
}
})
describe("a RxSwift provider", { () -> () in
var provider: RxMoyaProvider<GitHub>!
beforeEach {
provider = RxMoyaProvider(stubBehavior: MoyaProvider.ImmediateStubbingBehaviour)
}
it("returns a MoyaResponse object") {
var called = false
provider.request(.Zen) >- subscribeNext { (object) -> Void in
called = true
}
expect(called).to(beTruthy())
}
it("returns stubbed data for zen request") {
var message: String?
let target: GitHub = .Zen
provider.request(target) >- subscribeNext { (response) -> Void in
message = NSString(data: response.data, encoding: NSUTF8StringEncoding) as? String
}
let sampleString = NSString(data: (target.sampleData as NSData), encoding: NSUTF8StringEncoding)
expect(message).to(equal(sampleString))
}
it("returns correct data for user profile request") {
var receivedResponse: NSDictionary?
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target) >- subscribeNext { (response) -> Void in
receivedResponse = NSJSONSerialization.JSONObjectWithData(response.data, options: nil, error: nil) as? NSDictionary
}
let sampleData = target.sampleData as NSData
let sampleResponse: NSDictionary = NSJSONSerialization.JSONObjectWithData(sampleData, options: nil, error: nil) as! NSDictionary
expect(receivedResponse).toNot(beNil())
}
it("returns identical signals for inflight requests") {
let target: GitHub = .Zen
var response: MoyaResponse!
let outerSignal = provider.request(target)
outerSignal >- subscribeNext { (response) -> Void in
expect(provider.inflightRequests.count).to(equal(1))
let innerSignal = provider.request(target)
innerSignal >- subscribeNext { (object) -> Void in
expect(provider.inflightRequests.count).to(equal(1))
}
}
expect(provider.inflightRequests.count).to(equal(0))
}
})
describe("a subsclassed reactive provider that tracks cancellation with delayed stubs") {
struct TestCancellable: Cancellable {
static var cancelled = false
func cancel() {
TestCancellable.cancelled = true
}
}
class TestProvider<T: MoyaTarget>: ReactiveCocoaMoyaProvider<T> {
override init(endpointClosure: MoyaEndpointsClosure = MoyaProvider.DefaultEndpointMapping, endpointResolver: MoyaEndpointResolution = MoyaProvider.DefaultEnpointResolution, stubBehavior: MoyaStubbedBehavior = MoyaProvider.NoStubbingBehavior, networkActivityClosure: Moya.NetworkActivityClosure? = nil) {
super.init(endpointClosure: endpointClosure, endpointResolver: endpointResolver, stubBehavior: stubBehavior, networkActivityClosure: networkActivityClosure)
}
override func request(token: T, completion: MoyaCompletion) -> Cancellable {
return TestCancellable()
}
}
var provider: ReactiveCocoaMoyaProvider<GitHub>!
beforeEach {
TestCancellable.cancelled = false
provider = TestProvider<GitHub>(stubBehavior: MoyaProvider.DelayedStubbingBehaviour(1))
}
it("cancels network request when subscription is cancelled") {
var called = false
let target: GitHub = .Zen
let disposable = provider.request(target).subscribeCompleted { () -> Void in
// Should never be executed
fail()
}
disposable.dispose()
expect(TestCancellable.cancelled).to( beTrue() )
}
}
}
describe("with stubbed errors") {
describe("a provider") { () -> () in
var provider: MoyaProvider<GitHub>!
beforeEach {
provider = MoyaProvider(endpointClosure: failureEndpointClosure, stubBehavior: MoyaProvider.ImmediateStubbingBehaviour)
}
it("returns stubbed data for zen request") {
var errored = false
let target: GitHub = .Zen
provider.request(target) { (object, statusCode, response, error) in
if error != nil {
errored = true
}
}
let sampleData = target.sampleData as NSData
expect(errored).toEventually(beTruthy())
}
it("returns stubbed data for user profile request") {
var errored = false
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target) { (object, statusCode, response, error) in
if error != nil {
errored = true
}
}
let sampleData = target.sampleData as NSData
expect{errored}.toEventually(beTruthy(), timeout: 1, pollInterval: 0.1)
}
it("returns stubbed error data when present") {
var errorMessage = ""
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target) { (object, statusCode, response, error) in
if let object = object {
errorMessage = NSString(data: object, encoding: NSUTF8StringEncoding) as! String
}
}
expect{errorMessage}.toEventually(equal("Houston, we have a problem"), timeout: 1, pollInterval: 0.1)
}
}
describe("a reactive provider", { () -> () in
var provider: ReactiveCocoaMoyaProvider<GitHub>!
beforeEach {
provider = ReactiveCocoaMoyaProvider<GitHub>(endpointClosure: failureEndpointClosure, stubBehavior: MoyaProvider.ImmediateStubbingBehaviour)
}
it("returns stubbed data for zen request") {
var errored = false
let target: GitHub = .Zen
provider.request(target).subscribeError { (error) -> Void in
errored = true
}
expect(errored).to(beTruthy())
}
it("returns correct data for user profile request") {
var errored = false
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target).subscribeError { (error) -> Void in
errored = true
}
expect(errored).to(beTruthy())
}
})
describe("a failing reactive provider") {
var provider: ReactiveCocoaMoyaProvider<GitHub>!
beforeEach {
provider = ReactiveCocoaMoyaProvider<GitHub>(endpointClosure: failureEndpointClosure, stubBehavior: MoyaProvider.ImmediateStubbingBehaviour)
}
it("returns the HTTP status code as the error code") {
var code: Int?
provider.request(.Zen).subscribeError { (error) -> Void in
code = error.code
}
expect(code).toNot(beNil())
expect(code).to(equal(401))
}
}
}
}
}
}
| mit |
ashleymills/Keychain.swift | Example/Simple-KeychainSwift/Keychain.swift | 1 | 5545 | //
// KeychainWrapper.swift
// Keychain sample app
//
// Created by Ashley Mills on 17/04/2015.
// Copyright (c) 2015 Joylord Systems Ltd. All rights reserved.
//
import Foundation
// MARK: - *** Public methods ***
public class Keychain {
public class func set(_ value:String, forKey key:String) -> Bool {
if valueExists(forKey: key) {
return update(value, forKey: key)
} else {
return create(value, forKey: key)
}
}
public class func set(_ bool:Bool, forKey key:String) -> Bool {
let value = bool ? "true" : "false"
return set(value, forKey: key)
}
public class func value(forKey key: String) -> String? {
guard let valueData = valueData(forKey: key) else { return nil }
return NSString(data: valueData, encoding: String.Encoding.utf8.rawValue) as String?
}
public class func bool(forKey key: String) -> Bool {
return value(forKey: key) == "true"
}
public class func removeValue(forKey key:String) -> Bool {
return deleteValue(forKey: key)
}
public class func reset() -> Bool {
let searchDictionary = basicDictionary()
let status = SecItemDelete(searchDictionary as CFDictionary)
return status == errSecSuccess
}
public class func allValues() -> [[String: String]]? {
var searchDictionary = basicDictionary()
searchDictionary[kSecMatchLimit as String] = kSecMatchLimitAll
searchDictionary[kSecReturnAttributes as String] = kCFBooleanTrue
searchDictionary[kSecReturnData as String] = kCFBooleanTrue
var retrievedAttributes: AnyObject?
var retrievedData: AnyObject?
var status = SecItemCopyMatching(searchDictionary as CFDictionary, &retrievedAttributes)
if status != errSecSuccess {
return nil
}
status = SecItemCopyMatching(searchDictionary as CFDictionary, &retrievedData)
if status != errSecSuccess {
return nil
}
guard let attributeDicts = retrievedAttributes as? [[String: AnyObject]] else { return nil }
var allValues = [[String : String]]()
for attributeDict in attributeDicts {
guard let keyData = attributeDict[kSecAttrAccount as String] as? Data else { continue }
guard let valueData = attributeDict[kSecValueData as String] as? Data else { continue }
guard let key = NSString(data: keyData, encoding: String.Encoding.utf8.rawValue) as String? else { continue }
guard let value = NSString(data: valueData, encoding: String.Encoding.utf8.rawValue) as String? else { continue }
allValues.append([key: value])
}
return allValues
}
}
// MARK: - *** Private methods ***
fileprivate extension Keychain {
class func valueExists(forKey key: String) -> Bool {
return valueData(forKey: key) != nil
}
class func create(_ value: String, forKey key: String) -> Bool {
var dictionary = newSearchDictionary(forKey: key)
dictionary[kSecValueData as String] = value.data(using: String.Encoding.utf8, allowLossyConversion: false) as AnyObject?
let status = SecItemAdd(dictionary as CFDictionary, nil)
return status == errSecSuccess
}
class func update(_ value: String, forKey key: String) -> Bool {
let searchDictionary = newSearchDictionary(forKey: key)
var updateDictionary = [String: AnyObject]()
updateDictionary[kSecValueData as String] = value.data(using: String.Encoding.utf8, allowLossyConversion: false) as AnyObject?
let status = SecItemUpdate(searchDictionary as CFDictionary, updateDictionary as CFDictionary)
return status == errSecSuccess
}
class func deleteValue(forKey key: String) -> Bool {
let searchDictionary = newSearchDictionary(forKey: key)
let status = SecItemDelete(searchDictionary as CFDictionary)
return status == errSecSuccess
}
class func valueData(forKey key: String) -> Data? {
var searchDictionary = newSearchDictionary(forKey: key)
searchDictionary[kSecMatchLimit as String] = kSecMatchLimitOne
searchDictionary[kSecReturnData as String] = kCFBooleanTrue
var retrievedData: AnyObject?
let status = SecItemCopyMatching(searchDictionary as CFDictionary, &retrievedData)
var data: Data?
if status == errSecSuccess {
data = retrievedData as? Data
}
return data
}
class func newSearchDictionary(forKey key: String) -> [String: AnyObject] {
let encodedIdentifier = key.data(using: String.Encoding.utf8, allowLossyConversion: false)
var searchDictionary = basicDictionary()
searchDictionary[kSecAttrGeneric as String] = encodedIdentifier as AnyObject?
searchDictionary[kSecAttrAccount as String] = encodedIdentifier as AnyObject?
return searchDictionary
}
class func basicDictionary() -> [String: AnyObject] {
let serviceName = Bundle(for: self).infoDictionary![kCFBundleIdentifierKey as String] as! String
return [kSecClass as String : kSecClassGenericPassword, kSecAttrService as String : serviceName as AnyObject]
}
}
| mit |
elegion/ios-Flamingo | Framework/FlamingoTests/NetworkClientReporterCallTests.swift | 1 | 3389 | //
// NetworkClientReporterCallTests.swift
// FlamingoTests
//
// Created by Nikolay Ischuk on 23.01.2018.
// Copyright © 2018 ELN. All rights reserved.
//
import Foundation
import XCTest
import Flamingo
private class MockLogger: Logger {
private(set) var logSended: Bool = false
public func log(_ message: String, context: [String: Any]?) {
self.logSended = true
}
}
private class MockReporter: LoggingClient {
var willSendCallClosure: (() -> Void)?
private(set) var willSendCalled: Bool = false
private(set) var didRecieveCalled: Bool = false
override func willSendRequest<Request>(_ networkRequest: Request) where Request: NetworkRequest {
willSendCalled = true
willSendCallClosure?()
super.willSendRequest(networkRequest)
}
override func didRecieveResponse<Request>(for request: Request, context: NetworkContext) where Request: NetworkRequest {
didRecieveCalled = true
super.didRecieveResponse(for: request, context: context)
}
}
class NetworkClientReporterCallTests: XCTestCase {
var client: NetworkClient!
override func setUp() {
super.setUp()
let configuration = NetworkDefaultConfiguration(baseURL: "http://www.mocky.io/")
client = NetworkDefaultClient(configuration: configuration, session: .shared)
}
override func tearDown() {
client = nil
super.tearDown()
}
func test_reporterCalls() {
let logger1 = MockLogger()
let reporter1 = MockReporter(logger: logger1)
let reporter2 = MockReporter(logger: SimpleLogger(appName: #file))
client.addReporter(reporter1, storagePolicy: .weak)
client.addReporter(reporter2, storagePolicy: .weak)
let asyncExpectation = expectation(description: #function)
let request = RealFailedTestRequest()
client.removeReporter(reporter2)
client.sendRequest(request) {
_, _ in
asyncExpectation.fulfill()
}
waitForExpectations(timeout: 10) {
_ in
XCTAssertTrue(reporter1.willSendCalled)
XCTAssertTrue(reporter1.didRecieveCalled)
XCTAssertFalse(reporter2.willSendCalled)
XCTAssertFalse(reporter2.didRecieveCalled)
XCTAssertTrue(logger1.logSended, "Logs are not sended")
}
}
func test_storagePolicy() {
var wasCalled1 = false
var wasCalled2 = false
var reporter1: MockReporter! = MockReporter(logger: SimpleLogger(appName: #file))
var reporter2: MockReporter! = MockReporter(logger: SimpleLogger(appName: #file))
let configuration = NetworkDefaultConfiguration(baseURL: "http://www.mocky.io/", parallel: false)
let networkClient = NetworkDefaultClient(configuration: configuration, session: .shared)
networkClient.addReporter(reporter1, storagePolicy: .weak)
networkClient.addReporter(reporter2, storagePolicy: .strong)
reporter1.willSendCallClosure = {
wasCalled1 = true
}
reporter2.willSendCallClosure = {
wasCalled2 = true
}
reporter1 = nil
reporter2 = nil
let stubRequest = StubRequest()
networkClient.sendRequest(stubRequest, completionHandler: nil)
XCTAssertFalse(wasCalled1)
XCTAssertTrue(wasCalled2)
}
}
| mit |
Boss-XP/ChatToolBar | BXPChatToolBar/BXPChatToolBar/Classes/BXPChat/BXPChatViewController/view/BXPChatMessageCell.swift | 1 | 9833 | //
// BXPChatMessageCell.swift
// BXPChatToolBar
//
// Created by 向攀 on 17/1/5.
// Copyright © 2017年 Yunyun Network Technology Co,Ltd. All rights reserved.
//
import UIKit
class BXPChatMessageCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
let averterList = ["demo_avatar_jobs","demo_avatar_cook","demo_avatar_woz"]
var messageWidth: CGFloat = 66
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
backgroundColor = UIColor(red: 222/255, green: 222/255, blue: 222/255, alpha: 1.0)
selectionStyle = UITableViewCellSelectionStyle.none
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
contentView.addSubview(leftAvatarImageView)
leftAvatarImageView.image = UIImage(named: averterList[Int(arc4random_uniform(2))])
contentView.addSubview(rightAvatarImageView)
rightAvatarImageView.image = UIImage(named: averterList[Int(arc4random_uniform(2))])
contentView.addSubview(leftMessageBackView)
contentView.addSubview(rightMessageBackView)
leftMessageBackView.addSubview(leftMessageTextLabel)
rightMessageBackView.addSubview(rightMessageTextLabel)
setupLeft()
setupRight()
}
func setupLeft() -> Void {
/*let constraintLeft = NSLayoutConstraint(item: leftMessageBackView, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: contentView, attribute: NSLayoutAttribute.left, multiplier: 1.0, constant: 66)
let constraintTop = NSLayoutConstraint(item: leftMessageBackView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: contentView, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 0)
let constraintBottom = NSLayoutConstraint(item: leftMessageBackView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: contentView, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: 0)
let constraintWidth = NSLayoutConstraint(item: leftMessageBackView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: 72)
let constraintHeight = NSLayoutConstraint(item: leftMessageBackView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.greaterThanOrEqual, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: 50)
contentView.addConstraints([constraintLeft, constraintTop, constraintBottom])
leftMessageBackView.addConstraints([constraintWidth, constraintHeight])
*/
let constraintLeft1 = NSLayoutConstraint(item: leftMessageTextLabel, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: leftMessageBackView, attribute: NSLayoutAttribute.left, multiplier: 1.0, constant: 10)
let constraintRight1 = NSLayoutConstraint(item: leftMessageTextLabel, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: leftMessageBackView, attribute: NSLayoutAttribute.right, multiplier: 1.0, constant: -10)
let constraintTop1 = NSLayoutConstraint(item: leftMessageTextLabel, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: leftMessageBackView, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 10)
let constraintBottom1 = NSLayoutConstraint(item: leftMessageTextLabel, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: leftMessageBackView, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: -10)
leftMessageBackView.addConstraints([constraintLeft1, constraintTop1, constraintBottom1, constraintRight1])
}
func setupRight() -> Void {
/*let constraintRight = NSLayoutConstraint(item: rightMessageBackView, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: contentView, attribute: NSLayoutAttribute.right, multiplier: 1.0, constant: -66)
let constraintTop = NSLayoutConstraint(item: rightMessageBackView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: contentView, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 0)
let constraintBottom = NSLayoutConstraint(item: rightMessageBackView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: contentView, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: 0)
let constraintWidth = NSLayoutConstraint(item: rightMessageBackView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: messageWidth)
contentView.addConstraints([constraintRight, constraintTop, constraintBottom])
rightMessageBackView.addConstraints([constraintWidth])
*/
let constraintLeft1 = NSLayoutConstraint(item: rightMessageTextLabel, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: rightMessageBackView, attribute: NSLayoutAttribute.left, multiplier: 1.0, constant: 10)
let constraintRight1 = NSLayoutConstraint(item: rightMessageTextLabel, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: rightMessageBackView, attribute: NSLayoutAttribute.right, multiplier: 1.0, constant: -10)
let constraintTop1 = NSLayoutConstraint(item: rightMessageTextLabel, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: rightMessageBackView, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 10)
let constraintBottom1 = NSLayoutConstraint(item: rightMessageTextLabel, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: rightMessageBackView, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: -10)
rightMessageBackView.addConstraints([constraintLeft1, constraintTop1, constraintBottom1, constraintRight1])
}
lazy var leftAvatarImageView: UIImageView = {
let tempImageView = UIImageView(frame: CGRect(x: 10, y: 10, width: 50, height: 50))
tempImageView.layer.cornerRadius = 6
tempImageView.layer.masksToBounds = true
return tempImageView
}()
lazy var leftMessageBackView: UIImageView = {
let tempImageView = UIImageView()//(frame: CGRect(x: 66, y: 10, width: 50, height: 50))
tempImageView.image = UIImage(named: "chat_bubble_common_left")
// tempImageView.layer.cornerRadius = 6
// tempImageView.layer.masksToBounds = true
return tempImageView
}()
lazy var rightAvatarImageView: UIImageView = {
let tempImageView = UIImageView(frame: CGRect(x: UIScreen.main.bounds.size.width - 60, y: 10, width: 50, height: 50))
tempImageView.layer.cornerRadius = 6
tempImageView.layer.masksToBounds = true
return tempImageView
}()
lazy var rightMessageBackView: UIImageView = {
let tempImageView = UIImageView()//(frame: CGRect(x: 66, y: 10, width: 50, height: 50))
tempImageView.image = UIImage(named: "chat_bubble_common_right")
return tempImageView
}()
lazy var leftMessageTextLabel: UILabel = {
let textLabel = UILabel()
textLabel.numberOfLines = 0
textLabel.font = UIFont.systemFont(ofSize: 16)
textLabel.textColor = UIColor.black
// self.contentView.addSubview(textLabel)
return textLabel
}()
lazy var rightMessageTextLabel: UILabel = {
let textLabel = UILabel()
textLabel.numberOfLines = 0
textLabel.font = UIFont.systemFont(ofSize: 16)
textLabel.textColor = UIColor.black
textLabel.textAlignment = NSTextAlignment.right
// self.contentView.addSubview(textLabel)
return textLabel
}()
func setLeftMessageText(attributeString: NSAttributedString, width: CGFloat) -> Void {
rightAvatarImageView.isHidden = true
rightMessageBackView.isHidden = true
var frame = CGRect(x: 62, y: 10, width: 240, height: 80)
leftMessageBackView.frame = frame//CGRect(x: 62, y: 10, width: 240, height: 80)
frame.origin.x = 15
frame.origin.y = 10
frame.size.width -= 25
frame.size.height -= 20
leftMessageTextLabel.frame = frame
leftMessageTextLabel.attributedText = attributeString
if width > 66 {
messageWidth = width
}
// layoutIfNeeded()
// layoutSubviews()
}
func setRightMessageText(attributeString: NSAttributedString, width: CGFloat) -> Void {
leftAvatarImageView.isHidden = true
leftMessageBackView.isHidden = true
let width: CGFloat = 200
var frame = CGRect(x: UIScreen.main.bounds.size.width - width - 62, y: 10, width: width, height: 80)
rightMessageBackView.frame = frame//CGRect(x: UIScreen.main.bounds.size.width - 240 - 62, y: 10, width: 240, height: 80)
frame.origin.x = 10
frame.origin.y = 10
frame.size.width -= 25
frame.size.height -= 20
rightMessageTextLabel.frame = frame
rightMessageTextLabel.attributedText = attributeString
if width > 66 {
messageWidth = width
}
// layoutIfNeeded()
}
}
| apache-2.0 |
AaoIi/AAAlertController | FMAlertController/FMAlertController/FMAlertController.swift | 1 | 14659 | //
// FMAlertController.swift
// FMAlertController
//
// Created by AaoIi on 4/13/16.
// Copyright © 2016 Saad Albasha. All rights reserved.
//
import UIKit
public class FMAlertController: UIViewController {
public enum animationType{
case `default`
case shake
case slideDown
case slideUp
case slideRight
case slideLeft
case fade
}
enum type {
case single
case double
case triple
}
//* create alert with one cancel button
@IBOutlet fileprivate var viewOneButton: UIView!
@IBOutlet fileprivate var viewOneHeight: NSLayoutConstraint!
@IBOutlet fileprivate var titleLabel: UILabel!
@IBOutlet fileprivate var titleLabelHeight: NSLayoutConstraint!
@IBOutlet fileprivate var messageLabel: UILabel!
@IBOutlet fileprivate var cancelButton: UIButton!
//* create alert with cancel and action button
@IBOutlet fileprivate var viewWithTwoButtons: UIView!
@IBOutlet fileprivate var viewTwoHeight: NSLayoutConstraint!
@IBOutlet fileprivate var titleLabel2: UILabel!
@IBOutlet fileprivate var titleLabel2Height: NSLayoutConstraint!
@IBOutlet fileprivate var messageLabel2: UILabel!
@IBOutlet fileprivate var cancelButton2: UIButton!
@IBOutlet fileprivate var okButton: UIButton!
//* create alert with cancel and two action buttons
@IBOutlet fileprivate var viewWithThreeButtons: UIView!
@IBOutlet fileprivate var viewThreeHeight: NSLayoutConstraint!
@IBOutlet fileprivate var titleLabel3: UILabel!
@IBOutlet fileprivate var titleLabel3Height: NSLayoutConstraint!
@IBOutlet fileprivate var messageLabel3: UILabel!
@IBOutlet fileprivate var firstButton: UIButton!
@IBOutlet fileprivate var secondButton: UIButton!
@IBOutlet fileprivate var cancelButton3: UIButton!
//* local variables
fileprivate var titleText : String?
fileprivate var messageText : String?
fileprivate var cancelButtonTitle : String?
fileprivate var firstButtonTitle : String?
fileprivate var secondButtonTitle : String?
fileprivate var viewType : type = .single
fileprivate var firstActionCompletion : () -> (Void) = {}
fileprivate var secondActionCompletion : () -> (Void) = {}
fileprivate var cancelCompletionBlock : () -> (Void) = {}
fileprivate var animationStyle : animationType!
//MARK:- Life Cycle
override required init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
@available(*,unavailable)
override public func viewDidLoad() {
super.viewDidLoad()
self.setupView()
}
@available(*,unavailable)
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
switch viewType {
case .single:
self.performAnimation(viewOneButton)
break;
case .double:
self.performAnimation(viewWithTwoButtons)
break;
case .triple:
self.performAnimation(viewWithThreeButtons)
break;
}
}
//MARK:- Core init
fileprivate func setupView(){
switch viewType {
case .single:
//* setup for alert with cancel button
self.viewWithTwoButtons.isHidden = true
self.viewOneButton.isHidden = false
self.viewWithThreeButtons.isHidden = true
self.titleLabel.text = titleText
self.messageLabel.text = messageText
self.cancelButton.setTitle(cancelButtonTitle, for: UIControl.State())
self.cancelButton.addTarget(self, action: #selector(self.cancelAlertController(_:)), for: UIControl.Event.touchUpInside)
caclulateAlertHeight(viewOneHeight, view: viewOneButton, messageLabel: messageLabel, titleHeightConstraint: titleLabelHeight, titleLabel: titleLabel)
break;
case .double:
//* setup for alert with action and cancel button
self.viewWithTwoButtons.isHidden = false
self.viewOneButton.isHidden = true
self.viewWithThreeButtons.isHidden = true
self.titleLabel2.text = titleText
self.messageLabel2.text = messageText
self.cancelButton2.setTitle(cancelButtonTitle, for: UIControl.State())
self.cancelButton2.addTarget(self, action: #selector(self.cancelAlertController(_:)), for: UIControl.Event.touchUpInside)
self.okButton.setTitle(firstButtonTitle, for: UIControl.State())
self.okButton.addTarget(self, action: #selector(self.okAlertController(_:)), for: UIControl.Event.touchUpInside)
caclulateAlertHeight(viewTwoHeight, view: viewWithTwoButtons, messageLabel: messageLabel2, titleHeightConstraint: titleLabel2Height, titleLabel: titleLabel2)
break;
case .triple:
//* Setup for alert with two buttons and cancel button
self.viewWithTwoButtons.isHidden = true
self.viewOneButton.isHidden = true
self.viewWithThreeButtons.isHidden = false
self.titleLabel3.text = titleText
self.messageLabel3.text = messageText
self.cancelButton3.setTitle(cancelButtonTitle, for: UIControl.State())
self.cancelButton3.addTarget(self, action: #selector(self.cancelAlertController(_:)), for: UIControl.Event.touchUpInside)
self.firstButton.setTitle(firstButtonTitle, for: UIControl.State())
self.firstButton.addTarget(self, action: #selector(self.okAlertController(_:)), for: UIControl.Event.touchUpInside)
self.secondButton.setTitle(secondButtonTitle, for: UIControl.State())
self.secondButton.addTarget(self, action: #selector(self.okAlertController1(_:)), for: UIControl.Event.touchUpInside)
caclulateAlertHeight(viewThreeHeight, view: viewWithThreeButtons, messageLabel: messageLabel, titleHeightConstraint: titleLabel3Height, titleLabel: titleLabel3)
break;
}
}
fileprivate func FMAlertController(_ title:String,message:String,cancelButtonTitle:String,animationStyle:animationType,completionBlock: @escaping () -> (Void)){
self.titleText = title
self.messageText = message
self.cancelButtonTitle = cancelButtonTitle
self.viewType = .single
self.cancelCompletionBlock = completionBlock
self.animationStyle = animationStyle
}
fileprivate func FMAlertController(_ title:String,message:String,cancelButtonTitle:String,firstButtonTitle:String,animationStyle:animationType,firstActionCompletion: @escaping () -> (Void),cancelCompletionBlock: @escaping () -> (Void)){
self.titleText = title
self.messageText = message
self.cancelButtonTitle = cancelButtonTitle
self.firstButtonTitle = firstButtonTitle
self.viewType = .double
self.firstActionCompletion = firstActionCompletion
self.cancelCompletionBlock = cancelCompletionBlock
self.animationStyle = animationStyle
}
fileprivate func FMAlertController(_ title:String,message:String,firstButtonTitle:String,secondButtonTitle:String,cancelButtonTitle:String,animationStyle:animationType,firstActionCompletion: @escaping () -> (Void),secondActionCompletion: @escaping () -> (Void),cancelCompletionBlock: @escaping () -> (Void)){
self.titleText = title
self.messageText = message
self.cancelButtonTitle = cancelButtonTitle
self.firstButtonTitle = firstButtonTitle
self.secondButtonTitle = secondButtonTitle
self.viewType = .triple
self.firstActionCompletion = firstActionCompletion
self.secondActionCompletion = secondActionCompletion
self.cancelCompletionBlock = cancelCompletionBlock
self.animationStyle = animationStyle
}
//MARK:- Handlers
@objc
fileprivate func cancelAlertController(_ cancelButtonSender :UIButton) {
//* cancel alert Controller
self.cancelCompletionBlock()
self.dismiss(animated: true, completion: nil)
}
@objc
fileprivate func okAlertController(_ okButtonSender :UIButton){
//* executue completion block and cancel alert controller
self.firstActionCompletion()
self.dismiss(animated: true, completion: nil)
}
@objc
fileprivate func okAlertController1(_ okButtonSender :UIButton){
//* executue completion block and cancel alert controller
self.secondActionCompletion()
self.dismiss(animated: true, completion: nil)
}
//MARK:- View Animation
fileprivate func performAnimation(_ view:UIView){
guard let animationStyle = animationStyle else {return}
switch animationStyle {
case .default:
view.performDefaultAnimation()
break;
case .shake:
view.performShakeAnimation()
break;
case .slideDown:
view.performSlideDownAnimation()
break;
case .slideUp:
view.performSlideUpAnimation()
break;
case .slideRight:
view.performSlideRightAnimation()
break;
case .slideLeft:
view.performSlideLeftAnimation()
break;
case .fade:
view.performFadeAnimation()
break;
}
}
//MARK:- Alert Calculator
fileprivate func caclulateAlertHeight(_ viewHeightConstraint:NSLayoutConstraint,view:UIView,messageLabel:UILabel,titleHeightConstraint:NSLayoutConstraint,titleLabel:UILabel){
//* extend message to take title top
if titleLabel.text == "" {
titleHeightConstraint.constant = 0
}
//* calculate message height
let actualMessageSize = calculateTextHeight(messageLabel)
let messageSizeDifferance = actualMessageSize - 53
//* calculate title height
let actualTitleSize = calculateTextHeight(titleLabel)
let titleSizeDifferance = actualTitleSize - 21
if actualTitleSize > 21 {
titleHeightConstraint.constant += titleSizeDifferance
}
if actualMessageSize > 53 {
viewHeightConstraint.constant += messageSizeDifferance + titleHeightConstraint.constant
}else {
viewHeightConstraint.constant += titleHeightConstraint.constant - 20
}
self.view.layoutIfNeeded()
}
fileprivate func calculateTextHeight(_ LabelText:UILabel) -> CGFloat{
let labelWidth = LabelText.frame.width
let maxLabelSize = CGSize(width: labelWidth, height: CGFloat.greatestFiniteMagnitude)
let actualLabelSize = LabelText.text?.boundingRect(with: maxLabelSize, options: [.usesLineFragmentOrigin], attributes: [NSAttributedString.Key.font: LabelText.font ?? UIFont.systemFontSize], context: nil)
return actualLabelSize?.height ?? 0
}
}
// MARK: - Responsible to Show Alert
public extension FMAlertController {
class func show(_ title:String?,message:String?,cancelButtonTitle:String,completionBlock: @escaping ()->(Void),animationStyle:animationType = .default){
let bundle = Bundle(path: Bundle(for: self.classForCoder()).path(forResource: "FMAlertController", ofType: "bundle")!)
let alertView = self.init(nibName: "FMAlertController", bundle: bundle)
alertView.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
alertView.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
alertView.FMAlertController(title ?? "", message: message ?? "", cancelButtonTitle: cancelButtonTitle,animationStyle:animationStyle, completionBlock:completionBlock)
alertView.show(animated: true)
}
class func show(_ title:String?,message:String?,firstButtonTitle:String,firstActionCompletion: @escaping ()->(Void),cancelButtonTitle:String,cancelCompletionBlock: @escaping ()->(Void),animationStyle:animationType = .default){
let bundle = Bundle(path: Bundle(for: self.classForCoder()).path(forResource: "FMAlertController", ofType: "bundle")!)
let alertView = self.init(nibName: "FMAlertController", bundle: bundle)
alertView.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
alertView.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
alertView.FMAlertController(title ?? "", message: message ?? "", cancelButtonTitle: cancelButtonTitle, firstButtonTitle: firstButtonTitle,animationStyle:animationStyle, firstActionCompletion: firstActionCompletion, cancelCompletionBlock: cancelCompletionBlock)
alertView.show(animated: true)
}
class func show(_ title:String?,message:String?,firstButtonTitle:String,firstButtonCompletionBlock: @escaping ()->(Void),secondButtonTitle:String,secondButtonCompletionBlock: @escaping ()->(Void),cancelButtonTitle:String,cancelCompletionBlock: @escaping ()->(Void),animationStyle:animationType = .default){
let bundle = Bundle(path: Bundle(for: self.classForCoder()).path(forResource: "FMAlertController", ofType: "bundle")!)
let alertView = self.init(nibName: "FMAlertController", bundle: bundle)
alertView.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
alertView.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
alertView.FMAlertController(title ?? "", message: message ?? "", firstButtonTitle: firstButtonTitle, secondButtonTitle: secondButtonTitle, cancelButtonTitle: cancelButtonTitle, animationStyle: animationStyle, firstActionCompletion: firstButtonCompletionBlock, secondActionCompletion: secondButtonCompletionBlock, cancelCompletionBlock: cancelCompletionBlock)
alertView.show(animated: true)
}
}
| mit |
HotCocoaTouch/DeclarativeLayout | Example/DeclarativeLayout/READMEExample/READMEExample.swift | 1 | 2896 | import UIKit
import DeclarativeLayout
class READMEExample: UIViewController {
private lazy var viewLayout = ViewLayout(view: view)
private lazy var stackView = UIStackView()
private lazy var redView = UIView()
private lazy var orangeView = UIView()
private lazy var yellowView = UIView()
private lazy var greenView = UIView()
private lazy var blueView = UIView()
private lazy var purpleView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
title = "README Example"
layoutAllViews()
configureAllViews()
animationLoop()
}
private func animationLoop() {
Timer.scheduledTimer(withTimeInterval: 2.0, repeats: true, block: { timer in
UIView.animate(withDuration: 1.0, animations: {
self.layoutAllViews()
self.stackView.layoutIfNeeded()
})
})
}
private func layoutAllViews() {
let views = [redView,
orangeView,
yellowView,
greenView,
blueView,
purpleView]
viewLayout.updateLayoutTo { (com) in
com.stackView(self.stackView) { (com) in
com.constraints(
com.ownedView.leadingAnchor.constraint(equalTo: com.superview.leadingAnchor),
com.ownedView.trailingAnchor.constraint(equalTo: com.superview.trailingAnchor),
com.ownedView.topAnchor.constraint(equalTo: com.superview.safeAreaLayoutGuide.topAnchor,
constant: 35)
)
com.ownedView.axis = .vertical
for view in views.shuffled() {
com.arrangedView(view) { (com) in
let random = CGFloat(Int.random(in: 20..<100))
com.constraints(
com.ownedView.heightAnchor.constraint(equalToConstant: random)
)
}
com.space(CGFloat(Int.random(in: 0..<50)))
}
}
}
}
// Don't worry about this below here
private func configureAllViews() {
view.backgroundColor = .white
redView.backgroundColor = .red
orangeView.backgroundColor = .orange
yellowView.backgroundColor = .yellow
greenView.backgroundColor = .green
blueView.backgroundColor = .blue
purpleView.backgroundColor = .purple
redView.accessibilityLabel = "red"
orangeView.accessibilityLabel = "orange"
yellowView.accessibilityLabel = "yellow"
greenView.accessibilityLabel = "green"
blueView.accessibilityLabel = "blue"
purpleView.accessibilityLabel = "purple"
redView.accessibilityLabel = "red"
}
}
| mit |
CPRTeam/CCIP-iOS | Pods/CryptoSwift/Sources/CryptoSwift/UInt128.swift | 3 | 2628 | //
// UInt128.swift
//
// Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
import Foundation
struct UInt128: Equatable, ExpressibleByIntegerLiteral {
let i: (a: UInt64, b: UInt64)
typealias IntegerLiteralType = UInt64
init(integerLiteral value: IntegerLiteralType) {
self = UInt128(value)
}
init(_ raw: Array<UInt8>) {
self = raw.prefix(MemoryLayout<UInt128>.stride).withUnsafeBytes({ (rawBufferPointer) -> UInt128 in
let arr = rawBufferPointer.bindMemory(to: UInt64.self)
return UInt128((arr[0].bigEndian, arr[1].bigEndian))
})
}
init(_ raw: ArraySlice<UInt8>) {
self.init(Array(raw))
}
init(_ i: (a: UInt64, b: UInt64)) {
self.i = i
}
init(a: UInt64, b: UInt64) {
self.init((a, b))
}
init(_ b: UInt64) {
self.init((0, b))
}
// Bytes
var bytes: Array<UInt8> {
var at = self.i.a.bigEndian
var bt = self.i.b.bigEndian
let ar = Data(bytes: &at, count: MemoryLayout.size(ofValue: at))
let br = Data(bytes: &bt, count: MemoryLayout.size(ofValue: bt))
var result = Data()
result.append(ar)
result.append(br)
return result.bytes
}
static func ^ (n1: UInt128, n2: UInt128) -> UInt128 {
UInt128((n1.i.a ^ n2.i.a, n1.i.b ^ n2.i.b))
}
static func & (n1: UInt128, n2: UInt128) -> UInt128 {
UInt128((n1.i.a & n2.i.a, n1.i.b & n2.i.b))
}
static func >> (value: UInt128, by: Int) -> UInt128 {
var result = value
for _ in 0..<by {
let a = result.i.a >> 1
let b = result.i.b >> 1 + ((result.i.a & 1) << 63)
result = UInt128((a, b))
}
return result
}
// Equatable.
static func == (lhs: UInt128, rhs: UInt128) -> Bool {
lhs.i == rhs.i
}
static func != (lhs: UInt128, rhs: UInt128) -> Bool {
!(lhs == rhs)
}
}
| gpl-3.0 |
fsproru/ScoutReport | ScoutReportTests/FakeFuncCall.swift | 1 | 54 | struct FakeFuncCall {
var arguments: [AnyObject]
} | mit |
pyromobile/nubomedia-ouatclient-src | ios/LiveTales/uoat/ViewController.swift | 1 | 20081 | //
// ViewController.swift
// uoat
//
// Created by Pyro User on 4/5/16.
// Copyright © 2016 Zed. All rights reserved.
//
import UIKit
class ViewController: UIViewController, LoginSignupDelegate, ProfileDelegate
{
var user:User!
required init?(coder aDecoder: NSCoder)
{
//Detectar idioma.
let langId = NSLocale.preferredLanguages()[0].split("-")[0];
print("Idioma device: \(langId)");
print("Scale:\(UIScreen.mainScreen().scale)")
print("VIEW:\(UIScreen.mainScreen().bounds)")
LanguageMgr.getInstance.setId( langId );
//Create library with books in device.
Library.create( langId, isHD: ( UIScreen.mainScreen().scale > 1.0 ) )
var bookIds:[String] = [String]()
for book in Library.getInstance().currentBooks()
{
print("Tale detected in device: \(book.id) - \(book.title)")
bookIds.append(book.id)
}
let pos = Int(arc4random_uniform( UInt32(bookIds.count) ) )
self.bgImgPath = Library.getInstance().getFirstImageToPresentation( bookIds[pos] )
self.user = User()
self.wellcomeMsg = ""
super.init(coder: aDecoder);
//Init kuasars.
self.initKuasars();
//Load accesories to show in game.
AccesoriesMgr.create( ( UIScreen.mainScreen().scale > 1.0 ) )
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.networkStatusChanged(_:)), name: NetworkWatcher.reachabilityStatusChangedNotification, object: nil)
}
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Set background image from any book
if( self.bgMainImage.image == nil )
{
self.bgMainImage.image = UIImage( contentsOfFile: self.bgImgPath )!
let blurEffectView:UIVisualEffectView = Utils.blurEffectView(self.bgMainImage, radius: 6) //3
self.bgMainImage.addSubview( blurEffectView )
}
//buttons animations.
self.originalPosTaleModeButton = self.taleModeButton.frame
self.originalPosFreeModeButton = self.freeModeButton.frame
self.originalPosBottomGrpView = self.bottomGrpView.frame
self.originalPosJoinSessionGrpView = self.joinSessionGrpView.frame
//invite notifications.
//self.invitesButton.enabled = false
self.joinSessionGrpView.hidden = true
self.bgNotificationImage.hidden = true
self.notificationCountLabel.text = ""
//friendship notifications.
self.bgFriendshipNotificationImage.hidden = true
self.friendshipNotificationCountLabel.text = ""
}
override func viewDidLayoutSubviews()
{
super.viewDidLayoutSubviews()
//Main buttons.
if( hasSetAnimationValuesNow )
{
self.taleModeButton.frame.origin.x = self.view.bounds.width
self.freeModeButton.frame.origin.x = -self.freeModeButton.frame.width
self.bottomGrpView.frame.origin.y = self.view.bounds.height
self.joinSessionGrpView.frame.origin.x = self.view.bounds.width
}
}
override func viewDidAppear(animated: Bool)
{
super.viewDidAppear(animated)
dispatch_async(dispatch_get_main_queue(), { [unowned self] in
self.hasSetAnimationValuesNow = false
UIView.animateWithDuration( 0.5, animations:{ [unowned self] in
self.taleModeButton.frame = self.originalPosTaleModeButton
self.freeModeButton.frame = self.originalPosFreeModeButton
self.bottomGrpView.frame = self.originalPosBottomGrpView
if( !self.joinSessionGrpView.hidden )
{
self.joinSessionGrpView.frame = self.originalPosJoinSessionGrpView
}
}) { [unowned self] (finished:Bool) in
self.showNotificationsInfo()
}
})
self.showUserInfo()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prefersStatusBarHidden() -> Bool
{
return true
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
self.hasSetAnimationValuesNow = true
if( segue.identifier == "showLoginSignupView" )
{
//let navigationController = segue.destinationViewController as! UINavigationController
//let controller = navigationController.viewControllers.first as! LoginSignupViewController
let controller = segue.destinationViewController as! LoginSignupViewController
controller.user = self.user
controller.delegate = self
}
else if( segue.identifier == "showProfileView" )
{
let controller = segue.destinationViewController as! ProfileViewController
controller.user = self.user
controller.delegate = self
}
else if( segue.identifier == "showFriendsManagerView" )
{
let controller = segue.destinationViewController as! FriendsManagerViewController
controller.user = self.user
controller.notificationsByType = self.notificationsByType
}
else if( segue.identifier == "showModeLobbyView" )
{
//let navigationController = segue.destinationViewController as! UINavigationController
//let controller = navigationController.viewControllers.first as! TaleModeLobbyViewController
let controller = segue.destinationViewController as! TaleModeLobbyViewController
controller.user = self.user
controller.bgImagePath = self.bgImgPath
}
else if( segue.identifier == "showInviteNotificationsManagerView" )
{
let controller = segue.destinationViewController as! InviteNotificationsManagerViewController
controller.user = self.user
controller.bgImagePath = self.bgImgPath
controller.notificationsByType = self.notificationsByType
}
}
func willShowFriends(sender:UIButton)
{
if( NetworkWatcher.internetAvailabe )
{
UIView.animateWithDuration( 0.5, animations:{ [unowned self] in
self.taleModeButton.frame.origin.x = self.view.frame.width
self.freeModeButton.frame.origin.x = -self.freeModeButton.frame.width
self.bottomGrpView.frame.origin.y = self.view.frame.height
if( !self.joinSessionGrpView.hidden )
{
self.joinSessionGrpView.frame.origin.x = self.view.frame.width
}
}) { [unowned self] (finished:Bool) in
self.performSegueWithIdentifier( "showFriendsManagerView", sender:nil )
}
}
else
{
Utils.alertMessage( self, title:"Attention", message:"You must have internet connection!", onAlertClose:nil )
}
}
func willShowInvites(sender:UIButton)
{
if( NetworkWatcher.internetAvailabe )
{
UIView.animateWithDuration( 0.5, animations:{ [unowned self] in
self.taleModeButton.frame.origin.x = self.view.frame.width
self.freeModeButton.frame.origin.x = -self.freeModeButton.frame.width
self.bottomGrpView.frame.origin.y = self.view.frame.height
if( !self.joinSessionGrpView.hidden )
{
self.joinSessionGrpView.frame.origin.x = self.view.frame.width
}
}) { [unowned self] (finished:Bool) in
self.performSegueWithIdentifier( "showInviteNotificationsManagerView", sender:nil )
}
}
else
{
Utils.alertMessage( self, title:"Attention", message:"You must have internet connection!", onAlertClose:nil )
}
}
func networkStatusChanged(notification:NSNotification)
{
print("ViewController::networkStatusChanged was called...")
let userInfo:Dictionary<String,Bool!> = notification.userInfo as! Dictionary<String,Bool!>
let isAvailable:Bool = userInfo["isAvailable"]!
if( !isAvailable )
{
Utils.alertMessage( self, title:"Attention", message:"Internet connection lost!", onAlertClose:nil )
}
self.notificationsErrorMessageShowed = false
}
/*=============================================================*/
/* From LoginSignupDelegate */
/*=============================================================*/
func onLoginSignupReady()
{
hasSetAnimationValuesNow = false
self.showUserInfo()
self.showNotificationsInfo()
}
/*=============================================================*/
/* From ProfileDelegate */
/*=============================================================*/
func onProfileReady()
{
hasSetAnimationValuesNow = false
self.showUserInfo()
self.showNotificationsInfo()
}
/*=============================================================*/
/* UI Section */
/*=============================================================*/
@IBOutlet weak var bgMainImage: UIImageView!
@IBOutlet weak var helloLabel: UILabel!
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var taleModeButton: UIButton!
@IBOutlet weak var freeModeButton: UIButton!
@IBOutlet weak var joinSessionGrpView: UIView!
@IBOutlet weak var invitesButton: UIButton!
@IBOutlet weak var bgNotificationImage: UIImageView!
@IBOutlet weak var notificationCountLabel: UILabel!
@IBOutlet weak var bottomGrpView: UIView!
@IBOutlet weak var friendsButton: UIButton!
@IBOutlet weak var bgFriendshipNotificationImage: UIImageView!
@IBOutlet weak var friendshipNotificationCountLabel: UILabel!
//---------------------------------------------------------------
// UI Actions
//---------------------------------------------------------------
@IBAction func login(sender: UIButton)
{
if( NetworkWatcher.internetAvailabe )
{
if( !self.user.isLogged() )
{
self.performSegueWithIdentifier("showLoginSignupView", sender: nil)
}
else
{
self.performSegueWithIdentifier("showProfileView", sender: nil)
}
}
else
{
Utils.alertMessage( self, title:"Attention", message:"You must have internet connection!", onAlertClose:nil )
}
}
@IBAction func starTaleMode(sender: UIButton)
{
UIView.animateWithDuration( 0.5, animations:{ [unowned self] in
self.taleModeButton.frame.origin.x = self.view.frame.width
self.freeModeButton.frame.origin.x = -self.freeModeButton.frame.width
self.bottomGrpView.frame.origin.y = self.view.frame.height
if( !self.joinSessionGrpView.hidden )
{
self.joinSessionGrpView.frame.origin.x = self.view.frame.width
}
}) { [unowned self] (finished:Bool) in
self.user.lobby = .Tale
self.performSegueWithIdentifier("showModeLobbyView", sender: nil )
}
}
@IBAction func starFreeMode(sender: UIButton)
{
if( NetworkWatcher.internetAvailabe )
{
UIView.animateWithDuration( 0.5, animations:{ [unowned self] in
self.taleModeButton.frame.origin.x = self.view.frame.width
self.freeModeButton.frame.origin.x = -self.freeModeButton.frame.width
self.bottomGrpView.frame.origin.y = self.view.frame.height
if( !self.joinSessionGrpView.hidden )
{
self.joinSessionGrpView.frame.origin.x = self.view.frame.width
}
}) { [unowned self] (finished:Bool) in
self.user.lobby = .Free
self.performSegueWithIdentifier("showModeLobbyView", sender: nil )
}
}
else
{
Utils.alertMessage(self, title:"Attention", message:"You must have internet connection!", onAlertClose:nil )
}
}
@IBAction func showCredits(sender: UIButton)
{
performSegueWithIdentifier("showInformationView", sender: nil)
}
@IBAction func showGallery(sender: UIButton)
{
performSegueWithIdentifier("showGalleryView", sender: nil )
}
@IBAction func unwindToMainView(segue: UIStoryboardSegue)
{
//Back from TaleModeViewController or FreeModeViewController
if( segue.sourceViewController.isKindOfClass( FreeModeViewController ) )
{
let controller:FreeModeViewController = segue.sourceViewController as! FreeModeViewController
self.user = controller.user
controller.user = nil
}
else if( segue.sourceViewController.isKindOfClass( TaleModeViewController ) )
{
let controller:TaleModeViewController = segue.sourceViewController as! TaleModeViewController
self.user = controller.user
controller.user = nil
}
}
/*=============================================================*/
/* Private Section */
/*=============================================================*/
private func initKuasars()
{
KuasarsCore.setAppId( "560ab6e3e4b0b185810131aa" );
KuasarsCore.setEnvironment( KuasarsEnvironmentPRO );
KuasarsCore.setDebuggerEnabled( true );
}
private func showUserInfo()
{
if( self.user.isLogged() )
{
//Hi message and change login button title.
let hiName = self.wellcomeMsg + self.user.name;
helloLabel.text = hiName;
helloLabel.hidden = false;
loginButton.setTitle( "Profile", forState: .Normal );
//Friends button.
self.friendsButton.enabled = true
self.friendsButton.addTarget( self, action:#selector(ViewController.willShowFriends(_:)), forControlEvents:.TouchUpInside )
}
else
{
if( self.wellcomeMsg.isEmpty )
{
self.wellcomeMsg = helloLabel.text!
}
helloLabel.text = self.wellcomeMsg
helloLabel.hidden = true
loginButton.setTitle( "Registrarse", forState: .Normal )
//Friends button.
self.friendsButton.enabled = false
self.friendsButton.removeTarget( self, action:#selector(ViewController.willShowFriends(_:)), forControlEvents:.TouchUpInside )
}
}
private func showNotificationsInfo()
{
//Invite button is showed when notifications for playingroom and readingroom are received.
if( self.user.isLogged() )
{
if( NetworkWatcher.internetAvailabe )
{
NotificationModel.getAllByUser( self.user.id, onNotificationsReady:{[unowned self](notifications) in
//Show
var invitesCount:Int = 0
var friendshipRequestCount:Int = 0
if let invitesPlayingRoom = notifications[NotificationType.PlayingRoom]
{
invitesCount += invitesPlayingRoom.count
}
else if let invitesReadingRoom = notifications[NotificationType.ReadingRoom]
{
invitesCount += invitesReadingRoom.count
}
else if let friendship = notifications[NotificationType.FriendShip]
{
friendshipRequestCount += friendship.count
}
//Show invites to room notifications.
if( invitesCount > 0 )
{
//self.invitesButton.enabled = true
self.notificationCountLabel.text = "\(invitesCount)"
if( self.joinSessionGrpView.hidden )
{
self.joinSessionGrpView.hidden = false
self.bgNotificationImage.hidden = false
self.invitesButton.addTarget( self, action:#selector(ViewController.willShowInvites(_:)), forControlEvents:.TouchUpInside )
self.joinSessionGrpView.alpha = 0.0
UIView.animateWithDuration( 0.5, animations:{ [unowned self] in
self.joinSessionGrpView.alpha = 1.0
})
}
}
else
{
//self.invitesButton.enabled = false
self.joinSessionGrpView.hidden = true
self.bgNotificationImage.hidden = true
self.notificationCountLabel.text = ""
}
//Show friendship notifications.
if( friendshipRequestCount > 0 )
{
self.bgFriendshipNotificationImage.hidden = false
self.friendshipNotificationCountLabel.text = "\(friendshipRequestCount)"
}
else
{
self.bgFriendshipNotificationImage.hidden = true
self.friendshipNotificationCountLabel.text = ""
}
self.notificationsByType = notifications
})
}
else
{
if( !self.notificationsErrorMessageShowed )
{
Utils.alertMessage(self, title:"Attention", message:"You must have internet connection!", onAlertClose:nil )
self.notificationsErrorMessageShowed = true
}
}
}
else
{
//self.invitesButton.enabled = false
if( !self.joinSessionGrpView.hidden )
{
self.joinSessionGrpView.alpha = 1.0
UIView.animateWithDuration( 0.2, animations:{ [unowned self] in
self.joinSessionGrpView.alpha = 0.0
}){ [unowned self] (finished:Bool) in
self.joinSessionGrpView.hidden = true
self.bgNotificationImage.hidden = true
self.notificationCountLabel.text = ""
}
}
self.bgFriendshipNotificationImage.hidden = true
self.friendshipNotificationCountLabel.text = ""
}
}
private var hasSetAnimationValuesNow:Bool = true
private var originalPosTaleModeButton:CGRect = CGRect.zero
private var originalPosFreeModeButton:CGRect = CGRect.zero
private var originalPosBottomGrpView:CGRect = CGRect.zero
private var originalPosJoinSessionGrpView:CGRect = CGRect.zero
private var wellcomeMsg:String
private var bgImgPath:String
private var notificationsByType:[NotificationType:[Notification]] = [NotificationType:[Notification]]()
private var notificationsErrorMessageShowed:Bool = false
}
| apache-2.0 |
mcdappdev/Vapor-Template | Sources/App/Controllers/API/LoginController.swift | 1 | 1580 | import Vapor
import Foundation
import BCrypt
import AuthProvider
import MySQL
final class LoginController: RouteCollection {
func build(_ builder: RouteBuilder) throws {
builder.version() { build in
build.post("login", handler: login)
}
}
//MARK: - POST /api/v1/login
func login(_ req: Request) throws -> ResponseRepresentable {
let invalidCredentials = Abort(.badRequest, reason: "Invalid credentials")
guard let json = req.json else { throw Abort.badRequest }
//TODO: - When Swift 4 is released add a generic subscript to `StructuredDataWrapper` so that `.rawValue` doesn't have to be used. See: https://github.com/apple/swift-evolution/blob/master/proposals/0148-generic-subscripts.md
guard let email = json[User.Field.email.rawValue]?.string else { throw Abort.badRequest }
guard let password = json[User.Field.password.rawValue]?.string else { throw Abort.badRequest }
guard let user = try User.makeQuery().filter(User.Field.email, email).first() else { throw invalidCredentials }
if try BCryptHasher().verify(password: password, matches: user.password) {
if try user.token() == nil {
let newToken = Token(token: UUID().uuidString, user_id: user.id!)
try newToken.save()
}
return try user.makeJSON()
} else {
throw invalidCredentials
}
}
}
//MARK: - EmptyInitializable
extension LoginController: EmptyInitializable { }
| mit |
sclark01/Swift_VIPER_Demo | vaporServer/Sources/App/main.swift | 1 | 598 | import Vapor
import Foundation
let drop = Droplet()
let service = PeopleService()
drop.get { req in
let lang = req.headers["Accept-Language"]?.string ?? "en"
return try drop.view.make("welcome", [
"message": Node.string(drop.localization[lang, "welcome", "title"])
])
}
drop.get("list") { req in
return service.getAllPeople()
}
drop.get("listAll") { req in
return service.getAllPeopleWithDetails()
}
drop.get("personByID") { req in
guard let id = req.data["id"]?.int else {
throw Abort.badRequest
}
return service.getPersonBy(id: id)
}
drop.run()
| mit |
PJayRushton/stats | Stats/AddGamesToCalendar.swift | 1 | 1689 | //
// AddGamesToCalendar.swift
// Stats
//
// Created by Parker Rushton on 8/15/17.
// Copyright © 2017 AppsByPJ. All rights reserved.
//
import Foundation
import EventKit
struct AddGamesToCalendar: Command {
var games: [Game]
init(_ games: [Game]) {
self.games = games
}
func execute(state: AppState, core: Core<AppState>) {
do {
try games.forEach { game in
let calendarEvent = game.calendarEvent()
try CalendarService.eventStore.save(calendarEvent, span: .thisEvent)
core.fire(command: UpdateGame(game, calendarId: calendarEvent.eventIdentifier))
}
} catch {
print("error saving event")
}
}
}
struct EditCalendarEventForGames: Command {
var games: [Game]
init(_ games: [Game]) {
self.games = games
}
func execute(state: AppState, core: Core<AppState>) {
games.forEach { game in
guard let calendarId = game.calendarId, let event = CalendarService.eventStore.event(withIdentifier: calendarId) else { return }
let updatedEvent = game.calendarEvent(from: event)
do {
try CalendarService.eventStore.save(updatedEvent, span: .thisEvent)
} catch {
print("error saving event to calendar")
}
}
}
}
extension EKEvent: Diffable {
func isSame(as other: EKEvent) -> Bool {
return startDate == other.startDate &&
location == other.location &&
calendar == other.calendar &&
endDate == other.endDate &&
title == other.title
}
}
| mit |
blockchain/My-Wallet-V3-iOS | Blockchain/DIKit/DIKit+Activity.swift | 1 | 1043 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import DIKit
import FeatureActivityDomain
import FeatureCardPaymentDomain
// MARK: - Blockchain Module
extension DependencyContainer {
static var blockchainActivity = module {
factory { () -> ActivityCardDataServiceAPI in
ActivityCardDataService(cardListService: DIKit.resolve())
}
}
}
final class ActivityCardDataService: ActivityCardDataServiceAPI {
private let cardListService: CardListServiceAPI
init(cardListService: CardListServiceAPI) {
self.cardListService = cardListService
}
func fetchCardDisplayName(for paymentMethodId: String) -> AnyPublisher<String?, Never> {
cardListService
.card(by: paymentMethodId)
.map { cardData in
guard let cardData = cardData else {
return nil
}
return "\(cardData.label) \(cardData.displaySuffix)"
}
.eraseToAnyPublisher()
}
}
| lgpl-3.0 |
nathan3o4/Top-Movies | Top Movies/Top MoviesUITests/Top_MoviesUITests.swift | 2 | 1254 | //
// Top_MoviesUITests.swift
// Top MoviesUITests
//
// Created by Nathan Ansel on 1/7/16.
// Copyright © 2016 Nathan Ansel. All rights reserved.
//
import XCTest
class Top_MoviesUITests: 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.
}
}
| apache-2.0 |
jaylyerly/XLForm | Examples/Swift/Examples/CustomRows/Rating/XLFormRatingCell.swift | 2 | 2165 | // XLFormRatingCell.swift
// XLForm ( https://github.com/xmartlabs/XLForm )
//
// Copyright (c) 2014-2015 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
let XLFormRowDescriptorTypeRate = "XLFormRowDescriptorTypeRate"
@objc
class XLFormRatingCell : XLFormBaseCell {
@IBOutlet weak var rateTitle: UILabel!
@IBOutlet weak var ratingView: XLRatingView!
override func configure() {
super.configure()
self.selectionStyle = UITableViewCellSelectionStyle.None
self.ratingView.addTarget(self, action: "rateChanged:", forControlEvents:UIControlEvents.ValueChanged)
}
override func update() {
super.update()
self.ratingView.value = self.rowDescriptor.value.floatValue
self.rateTitle.text = self.rowDescriptor.title
self.ratingView.alpha = self.rowDescriptor.isDisabled() ? 0.6 : 1
self.rateTitle.alpha = self.rowDescriptor.isDisabled() ? 0.6 : 1
}
//MARK: Events
func rateChanged(ratingView : XLRatingView){
self.rowDescriptor.value = ratingView.value
}
}
| mit |
jjacobson93/RethinkDBSwift | Sources/RethinkDB/Error.swift | 1 | 3832 | public enum ReqlError: Error {
case authError(String)
case compileError(String, [Any], [Any])
case cursorEmpty
case driverError(String)
case typeError(Any, String)
public var localizedDescription: String {
switch self {
case .authError(let e): return e
case .driverError(let e): return e
case .compileError(let e, let term, let backtrace):
let queryPrinter = QueryPrinter(root: term, backtrace: backtrace)
return "\(e)\n\(queryPrinter.printQuery())\n\(queryPrinter.printCarrots())"
case .cursorEmpty: return "Cursor is empty"
case .typeError(let value, let type): return "Cannot coerce value \(value) to suggested type \(type)."
}
}
}
public struct QueryPrinter {
let root: [Any]
let backtrace: [Any]
init(root: [Any], backtrace: [Any]) {
self.root = root
self.backtrace = backtrace
}
func printQuery() -> String {
return self.composeTerm(self.root)
}
func printCarrots() -> String {
return self.composeCarrots(self.root, self.backtrace)
}
func composeTerm(_ term: [Any]) -> String {
guard let typeValue = term[0] as? Int else {
return "EXPECTED INT, FOUND ARRAY: \(term[0])"
}
guard let termType = ReqlTerm(rawValue: typeValue), let termArgs = term[1] as? [Any] else {
return ""
}
let args = termArgs.map({ self.composeTerm($0) })
var optargs = [String: String]()
if term.count > 2, let dict = term[2] as? [String: Any] {
for (k, v) in dict {
optargs[k] = self.composeTerm(v)
}
}
return self.composeTerm(termType, args, optargs)
}
func composeTerm(_ term: Any) -> String {
if let term = term as? [Any] {
return self.composeTerm(term)
}
return "\(term)"
}
func composeTerm(_ termType: ReqlTerm, _ args: [String], _ optargs: [String: String]) -> String {
let term = termType.description
let argsString = args.joined(separator: ", ")
if optargs.isEmpty {
return "\(term)(\(argsString))"
}
return "\(term)(\(argsString), \(optargs))"
}
func composeCarrots(_ term: [Any], _ backtrace: [Any]) -> String {
guard let typeValue = term[0] as? Int, let termType = ReqlTerm(rawValue: typeValue), let termArgs = term[1] as? [Any] else {
return ""
}
if backtrace.isEmpty {
return String(repeating: "^", count: self.composeTerm(term).characters.count)
}
let currFrame = backtrace[0]
let args = termArgs.enumerated().map { (i, arg) -> String in
if let currFrameInt = currFrame as? Int64, Int(currFrameInt) == i {
return self.composeCarrots(arg, Array(backtrace[1..<backtrace.count]))//self.composeCarrots(arg, backtrace[1..<backtrace.count])
}
return self.composeTerm(arg)
}
var optargs = [String: String]()
if term.count > 2, let dict = term[2] as? [String: Any] {
for (k, v) in dict {
if let currFrameKey = currFrame as? String, currFrameKey == k {
optargs[k] = self.composeCarrots(v, Array(backtrace[1..<backtrace.count]))
} else {
optargs[k] = self.composeTerm(v)
}
}
}
return self.composeTerm(termType, args, optargs).characters.map({ (c: Character) -> String in
return c != "^" ? " " : "^"
}).joined()
}
func composeCarrots(_ term: Any, _ backtrace: [Any]) -> String {
return ""
}
}
| mit |
CD1212/Doughnut | Pods/FeedKit/Sources/FeedKit/Models/Atom/AtomFeed.swift | 2 | 8632 | //
// AtomFeed.swift
//
// Copyright (c) 2017 Nuno Manuel Dias
//
// 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
/// Data model for the XML DOM of the Atom Specification
/// See https://tools.ietf.org/html/rfc4287
///
/// The "atom:feed" element is the document (i.e., top-level) element of
/// an Atom Feed Document, acting as a container for metadata and data
/// associated with the feed. Its element children consist of metadata
/// elements followed by zero or more atom:entry child elements.
open class AtomFeed {
/// The "atom:title" element is a Text construct that conveys a human-
/// readable title for an entry or feed.
public var title: String?
/// The "atom:subtitle" element is a Text construct that conveys a human-
/// readable description or subtitle for a feed.
public var subtitle: AtomFeedSubtitle?
/// The "atom:link" element defines a reference from an entry or feed to
/// a Web resource. This specification assigns no meaning to the content
/// (if any) of this element.
public var links: [AtomFeedLink]?
/// The "atom:updated" element is a Date construct indicating the most
/// recent instant in time when an entry or feed was modified in a way
/// the publisher considers significant. Therefore, not all
/// modifications necessarily result in a changed atom:updated value.
public var updated: Date?
/// The "atom:category" element conveys information about a category
/// associated with an entry or feed. This specification assigns no
/// meaning to the content (if any) of this element.
public var categories: [AtomFeedCategory]?
/// The "atom:author" element is a Person construct that indicates the
/// author of the entry or feed.
///
/// If an atom:entry element does not contain atom:author elements, then
/// the atom:author elements of the contained atom:source element are
/// considered to apply. In an Atom Feed Document, the atom:author
/// elements of the containing atom:feed element are considered to apply
/// to the entry if there are no atom:author elements in the locations
/// described above.
public var authors: [AtomFeedAuthor]?
/// The "atom:contributor" element is a Person construct that indicates a
/// person or other entity who contributed to the entry or feed.
public var contributors: [AtomFeedContributor]?
/// The "atom:id" element conveys a permanent, universally unique
/// identifier for an entry or feed.
///
/// Its content MUST be an IRI, as defined by [RFC3987]. Note that the
/// definition of "IRI" excludes relative references. Though the IRI
/// might use a dereferencable scheme, Atom Processors MUST NOT assume it
/// can be dereferenced.
///
/// When an Atom Document is relocated, migrated, syndicated,
/// republished, exported, or imported, the content of its atom:id
/// element MUST NOT change. Put another way, an atom:id element
/// pertains to all instantiations of a particular Atom entry or feed;
/// revisions retain the same content in their atom:id elements. It is
/// suggested that the atom:id element be stored along with the
/// associated resource.
///
/// The content of an atom:id element MUST be created in a way that
/// assures uniqueness.
///
/// Because of the risk of confusion between IRIs that would be
/// equivalent if they were mapped to URIs and dereferenced, the
/// following normalization strategy SHOULD be applied when generating
/// atom:id elements:
///
/// - Provide the scheme in lowercase characters.
/// - Provide the host, if any, in lowercase characters.
/// - Only perform percent-encoding where it is essential.
/// - Use uppercase A through F characters when percent-encoding.
/// - Prevent dot-segments from appearing in paths.
/// - For schemes that define a default authority, use an empty
/// authority if the default is desired.
/// - For schemes that define an empty path to be equivalent to a path
/// of "/", use "/".
/// - For schemes that define a port, use an empty port if the default
/// is desired.
/// - Preserve empty fragment identifiers and queries.
/// - Ensure that all components of the IRI are appropriately character
/// normalized, e.g., by using NFC or NFKC.
public var id: String?
/// The "atom:generator" element's content identifies the agent used to
/// generate a feed, for debugging and other purposes.
///
/// The content of this element, when present, MUST be a string that is a
/// human-readable name for the generating agent. Entities such as
/// "&" and "<" represent their corresponding characters ("&" and
/// "<" respectively), not markup.
///
/// The atom:generator element MAY have a "uri" attribute whose value
/// MUST be an IRI reference [RFC3987]. When dereferenced, the resulting
/// URI (mapped from an IRI, if necessary) SHOULD produce a
/// representation that is relevant to that agent.
///
/// The atom:generator element MAY have a "version" attribute that
/// indicates the version of the generating agent.
public var generator: AtomFeedGenerator?
/// The "atom:icon" element's content is an IRI reference [RFC3987] that
/// identifies an image that provides iconic visual identification for a
/// feed.
///
/// The image SHOULD have an aspect ratio of one (horizontal) to one
/// (vertical) and SHOULD be suitable for presentation at a small size.
public var icon: String?
/// The "atom:logo" element's content is an IRI reference [RFC3987] that
/// identifies an image that provides visual identification for a feed.
///
/// The image SHOULD have an aspect ratio of 2 (horizontal) to 1
/// (vertical).
public var logo: String?
/// The "atom:rights" element is a Text construct that conveys
/// information about rights held in and over an entry or feed.
///
/// The atom:rights element SHOULD NOT be used to convey machine-readable
/// licensing information.
///
/// If an atom:entry element does not contain an atom:rights element,
/// then the atom:rights element of the containing atom:feed element, if
/// present, is considered to apply to the entry.
public var rights: String?
/// The "atom:entry" element represents an individual entry, acting as a
/// container for metadata and data associated with the entry. This
/// element can appear as a child of the atom:feed element, or it can
/// appear as the document (i.e., top-level) element of a stand-alone
/// Atom Entry Document.
public var entries: [AtomFeedEntry]?
}
// MARK: - Equatable
extension AtomFeed: Equatable {
public static func ==(lhs: AtomFeed, rhs: AtomFeed) -> Bool {
return
lhs.title == rhs.title &&
lhs.subtitle == rhs.subtitle &&
lhs.links == rhs.links &&
lhs.updated == rhs.updated &&
lhs.categories == rhs.categories &&
lhs.authors == rhs.authors &&
lhs.contributors == rhs.contributors &&
lhs.id == rhs.id &&
lhs.generator == rhs.generator &&
lhs.icon == rhs.icon &&
lhs.logo == rhs.logo &&
lhs.rights == rhs.rights &&
lhs.entries == rhs.entries
}
}
| gpl-3.0 |
wilfreddekok/Antidote | Antidote/ChatGenericFileCellModel.swift | 1 | 744 | // 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
class ChatGenericFileCellModel: ChatMovableDateCellModel {
enum State {
case WaitingConfirmation
case Loading
case Paused
case Cancelled
case Done
}
var state: State = .WaitingConfirmation
var fileName: String?
var fileSize: String?
var fileUTI: String?
var startLoadingHandle: (Void -> Void)?
var cancelHandle: (Void -> Void)?
var retryHandle: (Void -> Void)?
var pauseOrResumeHandle: (Void -> Void)?
var openHandle: (Void -> Void)?
}
| mpl-2.0 |
lorentey/swift | test/SILOptimizer/access_marker_verify_objc.swift | 8 | 4482 | // RUN: %target-swift-frontend -enforce-exclusivity=checked -import-objc-header %S/Inputs/access_marker_verify_objc.h -Onone -emit-silgen -swift-version 4 -parse-as-library %s | %FileCheck %s
// RUN: %target-swift-frontend -enable-verify-exclusivity -enforce-exclusivity=checked -import-objc-header %S/Inputs/access_marker_verify_objc.h -Onone -emit-sil -swift-version 4 -parse-as-library %s
// REQUIRES: asserts
// REQUIRES: OS=macosx
// Test the combination of SILGen + DiagnoseStaticExclusivity with verification.
//
// This augments access_marker_verify with tests that require ObjC or
// CoreFoundation.
import Foundation
// --- initializer `let` of CFString.
// The verifier should ignore this.
// CHECK_LABEL: sil private @globalinit{{.*}} : $@convention(c) () -> () {
// CHECK: bb0:
// CHECK: alloc_global @$s25access_marker_verify_objc12testCFStringC8cfStringSo0F3RefavpZ
// CHECK: [[GA:%.*]] = global_addr @$s25access_marker_verify_objc12testCFStringC8cfStringSo0F3RefavpZ : $*CFString
// CHECK-NOT: begin_access
// CHECK: store %{{.*}} to [init] [[GA]] : $*CFString
// CHECK: return %{{.*}} : $()
// CHECK-LABEL: } // end sil function 'globalinit{{.*}}'
class testCFString {
public static let cfString: CFString = "" as CFString
}
// --- objC method.
// The verifier should be able to handle a thunk of a block and ignore
// an incoming block argument.
@objc protocol HasBlock {
func block(_: (Int) -> Int)
}
class HasBlockImpl: HasBlock {
@objc func block(_: (Int) -> Int) {}
}
// CHECK-LABEL: sil hidden [thunk] [ossa] @$s25access_marker_verify_objc12HasBlockImplC5blockyyS2iXEFTo : $@convention(objc_method) (@convention(block) @noescape (Int) -> Int, HasBlockImpl) -> () {
// CHECK: bb0(%0 : @unowned $@convention(block) @noescape (Int) -> Int, %1 : @unowned $HasBlockImpl):
// CHECK: [[CP:%.*]] = copy_block %0 : $@convention(block) @noescape (Int) -> Int
// function_ref thunk for @callee_unowned @convention(block) (@unowned Int) -> (@unowned Int)
// CHECK: [[THUNK:%.*]] = function_ref @$sS2iIyByd_S2iIegyd_TR : $@convention(thin) (Int, @guaranteed @convention(block) @noescape (Int) -> Int) -> Int
// CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[CP]]) : $@convention(thin) (Int, @guaranteed @convention(block) @noescape (Int) -> Int) -> Int
// CHECK: [[CVT:%.*]] = convert_escape_to_noescape [not_guaranteed] [[PA]] : $@callee_guaranteed (Int) -> Int to $@noescape @callee_guaranteed (Int) -> Int
// CHECK: [[F:%.*]] = function_ref @$s25access_marker_verify_objc12HasBlockImplC5blockyyS2iXEF : $@convention(method) (@noescape @callee_guaranteed (Int) -> Int, @guaranteed HasBlockImpl) -> ()
// CHECK: %{{.*}} = apply [[F]]([[CVT]], %{{.*}}) : $@convention(method) (@noescape @callee_guaranteed (Int) -> Int, @guaranteed HasBlockImpl) -> ()
// CHECK: return %{{.*}} : $()
// CHECK-LABEL: } // end sil function '$s25access_marker_verify_objc12HasBlockImplC5blockyyS2iXEFTo'
// thunk for @callee_unowned @convention(block) (@unowned Int) -> (@unowned Int)
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$sS2iIyByd_S2iIegyd_TR : $@convention(thin) (Int, @guaranteed @convention(block) @noescape (Int) -> Int) -> Int {
// CHECK: bb0(%0 : $Int, %1 : @guaranteed $@convention(block) @noescape (Int) -> Int):
// CHECK: %{{.*}} = apply %1(%0) : $@convention(block) @noescape (Int) -> Int
// CHECK: return %{{.*}} : $Int
// CHECK-LABEL: } // end sil function '$sS2iIyByd_S2iIegyd_TR'
// --- C global.
// The verifier should ignore this access.
// CHECK-LABEL: sil hidden [ossa] @$s25access_marker_verify_objc14GlobalPropertyC14globalCFStringSo0H3RefavgZ : $@convention(method) (@thick GlobalProperty.Type) -> @owned CFString {
// CHECK: bb0(%0 : $@thick GlobalProperty.Type):
// CHECK: [[GA:%.*]] = global_addr @constCGlobal : $*Optional<CFString>
// CHECK: [[STR:%.*]] = load [copy] [[GA]] : $*Optional<CFString>
// CHECK: switch_enum [[STR]] : $Optional<CFString>, case #Optional.some!enumelt.1: [[SOMEBB:bb.*]], case #Optional.none!enumelt: bb{{.*}}
// CHECK: [[SOMEBB]]([[R:%.*]] : @owned $CFString):
// CHECK: return [[R]] : $CFString
// CHECK_LABEL: } // end sil function '$s25access_marker_verify_objc14GlobalPropertyC14globalCFStringSo0H3RefavgZ'
class GlobalProperty {
public class var globalCFString: CFString { return constCGlobal }
}
| apache-2.0 |
zane001/ZMTuan | ZMTuan/Controller/Home/RushViewController.swift | 1 | 4923 | //
// RushViewController.swift
// ZMTuan
//
// Created by zm on 4/17/16.
// Copyright © 2016 zm. All rights reserved.
// 名店抢购的ViewController
import UIKit
class RushViewController: UIViewController, UIWebViewDelegate {
var webView: UIWebView!
var activityView: UIActivityIndicatorView!
var titleLabel: UILabel!
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.hidesBottomBarWhenPushed = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.setNav()
self.initViews()
}
func setNav() {
let backView = UIView(frame: CGRectMake(0, 0, SCREEN_WIDTH, 64))
backView.backgroundColor = RGB(250, g: 250, b: 250)
self.view.addSubview(backView)
// 下划线
let lineView = UIView(frame: CGRectMake(0, 63.5, SCREEN_WIDTH, 0.5))
lineView.backgroundColor = RGB(192, g: 192, b: 192)
backView.addSubview(lineView)
// 返回按钮
let backBtn = UIButton(type: .Custom)
backBtn.frame = CGRectMake(10, 30, 23, 23)
backBtn.setImage(UIImage(named: "btn_backItem"), forState: UIControlState.Normal)
backBtn.addTarget(self, action: #selector(RushViewController.onBackBtn(_:)), forControlEvents: .TouchUpInside)
backView.addSubview(backBtn)
self.titleLabel = UILabel(frame: CGRectMake(SCREEN_WIDTH/2-80, 30, 160, 30))
self.titleLabel.textAlignment = NSTextAlignment.Center
backView.addSubview(self.titleLabel)
}
func initViews() {
self.webView = UIWebView(frame: CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64))
self.webView.delegate = self
self.webView.scalesPageToFit = true
self.view.addSubview(self.webView)
let delegate = UIApplication.sharedApplication().delegate as! AppDelegate
let url = "http://i.meituan.com/topic/mingdian?ci=1&f=iphone&msid=48E2B810-805D-4821-9CDD-D5C9E01BC98A2015-07-02-16-25124&token=p19ukJltGhla4y5Jryb1jgCdKjsAAAAAsgAAADHFD3UYGxaY2FlFPQXQj2wCyCrhhn7VVB-KpG_U3-clHlvsLM8JRrnZK35y8UU3DQ&userid=10086&utm_campaign=AgroupBgroupD100Fab_chunceshishuju__a__a___b1junglehomepagecatesort__b__leftflow___ab_gxhceshi__nostrategy__leftflow___ab_gxhceshi0202__b__a___ab_pindaochangsha__a__leftflow___ab_xinkeceshi__b__leftflow___ab_gxtest__gd__leftflow___ab_waimaiwending__a__a___ab_gxh_82__nostrategy__leftflow___i_group_5_2_deallist_poitype__d__d___ab_b_food_57_purepoilist_extinfo__a__a___ab_pindaoshenyang__a__leftflow___ab_pindaoquxincelue0630__b__b1___a20141120nanning__m1__leftflow___ab_i_group_5_3_poidetaildeallist__a__b___ab_waimaizhanshi__b__b1___ab_i_group_5_5_onsite__b__b___ab_i_group_5_6_searchkuang__a__leftflowGhomepage_bargainmiddle_30311731&utm_content=4B8C0B46F5B0527D55EA292904FD7E12E48FB7BEA8DF50BFE7828AF7F20BB08D&utm_medium=iphone&utm_source=AppStore&utm_term=5.7&uuid=4B8C0B46F5B0527D55EA292904FD7E12E48FB7BEA8DF50BFE7828AF7F20BB08D&version_name=5.7&lat=\(delegate.latitude)&lng=\(delegate.longitude)"
let request = NSURLRequest(URL: NSURL(string: url)!)
// 加载web页面,进入名店抢购页面后,继续点击,如果手机装有美团官方app,则跳转到美团官方app,否则不跳转
self.webView.loadRequest(request)
}
func onBackBtn(sender: UIGestureRecognizer) {
self.navigationController?.popViewControllerAnimated(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: UIWebViewDelegate
func webViewDidStartLoad(webView: UIWebView) {
print("开始加载WebView")
}
func webViewDidFinishLoad(webView: UIWebView) {
let title = webView.stringByEvaluatingJavaScriptFromString("document.title")
self.titleLabel.text = title
SVProgressHUD.dismiss()
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
print("加载WebView失败")
}
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
SVProgressHUD.showSuccessWithStatus("加载成功")
return true
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit |
sindanar/PDStrategy | Example/PDStrategy/PDStrategy/ScrollViewController.swift | 1 | 1327 | //
// ScrollViewController.swift
// PDStrategy
//
// Created by Pavel Deminov on 07/01/2018.
// Copyright © 2018 Pavel Deminov. All rights reserved.
//
import UIKit
class ScrollViewController: PDScrollViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func cellIdentifier(for indexPath: IndexPath) -> String {
guard let item = itemInfo(for: indexPath), let type = item.pdType as? ScrollControllerItemType else {
return super.cellIdentifier(for: indexPath)
}
switch type {
case .titleValue:
return TitleValueScrollCell.reuseIdentifier()
default:
return super.cellIdentifier(for: indexPath)
}
}
override func scrollView(_ scrollView: UIScrollView, didSelectItemAt indexPath: IndexPath) {
guard let item = itemInfo(for: indexPath) else {
return
}
//item.value = String(describing: indexPath)
//self.controller?.updateItem(at: indexPath)
self.dataSource?.removeItem(at: indexPath)
}
}
| mit |
dnevera/IMProcessing | IMProcessing/Classes/Utils/IMPImage+CGImage.swift | 1 | 499 | //
// IMPImage+CGImage.swift
// IMProcessing
//
// Created by denis svinarchuk on 16.12.15.
// Copyright © 2015 IMetalling. All rights reserved.
//
#if os(iOS)
import UIKit
#else
import Cocoa
extension IMPImage {
var CGImage:CGImageRef?{
get {
var imageRect:CGRect = CGRectMake(0, 0, self.size.width, self.size.height)
return self.CGImageForProposedRect(&imageRect, context: nil, hints: nil)
}
}
}
#endif
| mit |
zvonicek/ImageSlideshow | Example/Tests/Tests.swift | 3 | 720 | import UIKit
import XCTest
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| mit |
ECLabs/CareerUp | CareerUp/SettingSelectTableViewController.swift | 1 | 3117 | import UIKit
class SettingSelectTableViewController: UITableViewController {
var selectedIndex = 0
var loadDelay:NSTimer?
var loadedContent = -1;
var eventArray:[Event] = []
override func viewDidLoad() {
super.viewDidLoad()
EventHandler.sharedInstance().get()
}
func reloadTable(timer: NSTimer){
let loadingCount = EventHandler.sharedInstance().loadingCount
let reloaded = EventHandler.sharedInstance().reloaded
if reloaded {
loadedContent = -1
EventHandler.sharedInstance().reloaded = false
}
if loadedContent != 0 {
println("load \(loadingCount)")
self.tableView.reloadData()
loadedContent = loadingCount
loadDelay = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: "reloadTable:", userInfo: nil, repeats: false)
}
else {
loadDelay = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: "reloadTable:", userInfo: nil, repeats: false)
EventHandler.sharedInstance().count()
}
}
override func viewWillDisappear(animated: Bool) {
loadDelay?.invalidate()
}
override func viewDidAppear(animated: Bool) {
loadDelay = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: "reloadTable:", userInfo: nil, repeats: false)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func viewWillAppear(animated: Bool) {
self.tableView.reloadData()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
eventArray = EventHandler.sharedInstance().events + EventHandler.sharedInstance().localEvents
return eventArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
let setting = eventArray[indexPath.row]
cell.textLabel.text = setting.name
cell.detailTextLabel?.text = setting.details
return cell
}
override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
selectedIndex = indexPath.row as Int
return indexPath
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
let settingDetail: SettingsTableViewController = segue.destinationViewController as SettingsTableViewController
let selectedEvent = eventArray[selectedIndex]
settingDetail.eventSetting = selectedEvent
}
@IBAction func AddSettings(AnyObject) {
let event = Event()
event.name = "New Event"
EventHandler.sharedInstance().save(event)
self.tableView.reloadData()
}
}
| mit |
abertelrud/swift-package-manager | Tests/CommandsTests/PackageToolTests.swift | 2 | 138187 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2014-2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Basics
@testable import CoreCommands
@testable import Commands
import Foundation
import PackageGraph
import PackageLoading
import PackageModel
import SourceControl
import SPMTestSupport
import TSCBasic
import Workspace
import XCTest
final class PackageToolTests: CommandsTestCase {
@discardableResult
private func execute(
_ args: [String],
packagePath: AbsolutePath? = nil,
env: EnvironmentVariables? = nil
) throws -> (stdout: String, stderr: String) {
var environment = env ?? [:]
// don't ignore local packages when caching
environment["SWIFTPM_TESTS_PACKAGECACHE"] = "1"
return try SwiftPMProduct.SwiftPackage.execute(args, packagePath: packagePath, env: environment)
}
func testNoParameters() throws {
let stdout = try execute([]).stdout
XCTAssertMatch(stdout, .contains("USAGE: swift package"))
}
func testUsage() throws {
let stdout = try execute(["-help"]).stdout
XCTAssertMatch(stdout, .contains("USAGE: swift package"))
}
func testSeeAlso() throws {
let stdout = try execute(["--help"]).stdout
XCTAssertMatch(stdout, .contains("SEE ALSO: swift build, swift run, swift test"))
}
func testVersion() throws {
let stdout = try execute(["--version"]).stdout
XCTAssertMatch(stdout, .contains("Swift Package Manager"))
}
func testInitOverview() throws {
let stdout = try execute(["init", "--help"]).stdout
XCTAssertMatch(stdout, .contains("OVERVIEW: Initialize a new package"))
}
func testInitUsage() throws {
let stdout = try execute(["init", "--help"]).stdout
XCTAssertMatch(stdout, .contains("USAGE: swift package init <options>"))
}
func testInitOptionsHelp() throws {
let stdout = try execute(["init", "--help"]).stdout
XCTAssertMatch(stdout, .contains("OPTIONS:"))
}
func testPlugin() throws {
XCTAssertThrowsCommandExecutionError(try execute(["plugin"])) { error in
XCTAssertMatch(error.stderr, .contains("error: Missing expected plugin command"))
}
}
func testUnknownOption() throws {
XCTAssertThrowsCommandExecutionError(try execute(["--foo"])) { error in
XCTAssertMatch(error.stderr, .contains("error: Unknown option '--foo'"))
}
}
func testUnknownSubommand() throws {
try fixture(name: "Miscellaneous/ExeTest") { fixturePath in
XCTAssertThrowsCommandExecutionError(try execute(["foo"], packagePath: fixturePath)) { error in
XCTAssertMatch(error.stderr, .contains("error: Unknown subcommand or plugin name 'foo'"))
}
}
}
func testNetrc() throws {
try fixture(name: "DependencyResolution/External/XCFramework") { fixturePath in
// --enable-netrc flag
try self.execute(["resolve", "--enable-netrc"], packagePath: fixturePath)
// --disable-netrc flag
try self.execute(["resolve", "--disable-netrc"], packagePath: fixturePath)
// --enable-netrc and --disable-netrc flags
XCTAssertThrowsError(
try self.execute(["resolve", "--enable-netrc", "--disable-netrc"], packagePath: fixturePath)
) { error in
XCTAssertMatch(String(describing: error), .contains("Value to be set with flag '--disable-netrc' had already been set with flag '--enable-netrc'"))
}
}
}
func testNetrcFile() throws {
try fixture(name: "DependencyResolution/External/XCFramework") { fixturePath in
let fs = localFileSystem
let netrcPath = fixturePath.appending(component: ".netrc")
try fs.writeFileContents(netrcPath) { stream in
stream <<< "machine mymachine.labkey.org login [email protected] password mypassword"
}
// valid .netrc file path
try execute(["resolve", "--netrc-file", netrcPath.pathString], packagePath: fixturePath)
// valid .netrc file path with --disable-netrc option
XCTAssertThrowsError(
try execute(["resolve", "--netrc-file", netrcPath.pathString, "--disable-netrc"], packagePath: fixturePath)
) { error in
XCTAssertMatch(String(describing: error), .contains("'--disable-netrc' and '--netrc-file' are mutually exclusive"))
}
// invalid .netrc file path
XCTAssertThrowsError(
try execute(["resolve", "--netrc-file", "/foo"], packagePath: fixturePath)
) { error in
XCTAssertMatch(String(describing: error), .contains("Did not find .netrc file at /foo."))
}
// invalid .netrc file path with --disable-netrc option
XCTAssertThrowsError(
try execute(["resolve", "--netrc-file", "/foo", "--disable-netrc"], packagePath: fixturePath)
) { error in
XCTAssertMatch(String(describing: error), .contains("'--disable-netrc' and '--netrc-file' are mutually exclusive"))
}
}
}
func testEnableDisableCache() throws {
try fixture(name: "DependencyResolution/External/Simple") { fixturePath in
let packageRoot = fixturePath.appending(component: "Bar")
let repositoriesPath = packageRoot.appending(components: ".build", "repositories")
let cachePath = fixturePath.appending(component: "cache")
let repositoriesCachePath = cachePath.appending(component: "repositories")
do {
// Remove .build and cache folder
_ = try execute(["reset"], packagePath: packageRoot)
try localFileSystem.removeFileTree(cachePath)
try self.execute(["resolve", "--enable-dependency-cache", "--cache-path", cachePath.pathString], packagePath: packageRoot)
// we have to check for the prefix here since the hash value changes because spm sees the `prefix`
// directory `/var/...` as `/private/var/...`.
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesPath).contains { $0.hasPrefix("Foo-") })
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesCachePath).contains { $0.hasPrefix("Foo-") })
// Remove .build folder
_ = try execute(["reset"], packagePath: packageRoot)
// Perform another cache this time from the cache
_ = try execute(["resolve", "--enable-dependency-cache", "--cache-path", cachePath.pathString], packagePath: packageRoot)
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesPath).contains { $0.hasPrefix("Foo-") })
// Remove .build and cache folder
_ = try execute(["reset"], packagePath: packageRoot)
try localFileSystem.removeFileTree(cachePath)
// Perform another fetch
_ = try execute(["resolve", "--enable-dependency-cache", "--cache-path", cachePath.pathString], packagePath: packageRoot)
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesPath).contains { $0.hasPrefix("Foo-") })
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesCachePath).contains { $0.hasPrefix("Foo-") })
}
do {
// Remove .build and cache folder
_ = try execute(["reset"], packagePath: packageRoot)
try localFileSystem.removeFileTree(cachePath)
try self.execute(["resolve", "--disable-dependency-cache", "--cache-path", cachePath.pathString], packagePath: packageRoot)
// we have to check for the prefix here since the hash value changes because spm sees the `prefix`
// directory `/var/...` as `/private/var/...`.
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesPath).contains { $0.hasPrefix("Foo-") })
XCTAssertFalse(localFileSystem.exists(repositoriesCachePath))
}
do {
// Remove .build and cache folder
_ = try execute(["reset"], packagePath: packageRoot)
try localFileSystem.removeFileTree(cachePath)
let (_, _) = try self.execute(["resolve", "--enable-dependency-cache", "--cache-path", cachePath.pathString], packagePath: packageRoot)
// we have to check for the prefix here since the hash value changes because spm sees the `prefix`
// directory `/var/...` as `/private/var/...`.
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesPath).contains { $0.hasPrefix("Foo-") })
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesCachePath).contains { $0.hasPrefix("Foo-") })
// Remove .build folder
_ = try execute(["reset"], packagePath: packageRoot)
// Perform another cache this time from the cache
_ = try execute(["resolve", "--enable-dependency-cache", "--cache-path", cachePath.pathString], packagePath: packageRoot)
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesPath).contains { $0.hasPrefix("Foo-") })
// Remove .build and cache folder
_ = try execute(["reset"], packagePath: packageRoot)
try localFileSystem.removeFileTree(cachePath)
// Perform another fetch
_ = try execute(["resolve", "--enable-dependency-cache", "--cache-path", cachePath.pathString], packagePath: packageRoot)
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesPath).contains { $0.hasPrefix("Foo-") })
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesCachePath).contains { $0.hasPrefix("Foo-") })
}
do {
// Remove .build and cache folder
_ = try execute(["reset"], packagePath: packageRoot)
try localFileSystem.removeFileTree(cachePath)
let (_, _) = try self.execute(["resolve", "--disable-dependency-cache", "--cache-path", cachePath.pathString], packagePath: packageRoot)
// we have to check for the prefix here since the hash value changes because spm sees the `prefix`
// directory `/var/...` as `/private/var/...`.
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesPath).contains { $0.hasPrefix("Foo-") })
XCTAssertFalse(localFileSystem.exists(repositoriesCachePath))
}
}
}
func testResolve() throws {
try fixture(name: "DependencyResolution/External/Simple") { fixturePath in
let packageRoot = fixturePath.appending(component: "Bar")
// Check that `resolve` works.
_ = try execute(["resolve"], packagePath: packageRoot)
let path = try SwiftPMProduct.packagePath(for: "Foo", packageRoot: packageRoot)
XCTAssertEqual(try GitRepository(path: path).getTags(), ["1.2.3"])
}
}
func testUpdate() throws {
try fixture(name: "DependencyResolution/External/Simple") { fixturePath in
let packageRoot = fixturePath.appending(component: "Bar")
// Perform an initial fetch.
_ = try execute(["resolve"], packagePath: packageRoot)
var path = try SwiftPMProduct.packagePath(for: "Foo", packageRoot: packageRoot)
XCTAssertEqual(try GitRepository(path: path).getTags(), ["1.2.3"])
// Retag the dependency, and update.
let repo = GitRepository(path: fixturePath.appending(component: "Foo"))
try repo.tag(name: "1.2.4")
_ = try execute(["update"], packagePath: packageRoot)
// We shouldn't assume package path will be same after an update so ask again for it.
path = try SwiftPMProduct.packagePath(for: "Foo", packageRoot: packageRoot)
XCTAssertEqual(try GitRepository(path: path).getTags(), ["1.2.3", "1.2.4"])
}
}
func testCache() throws {
try fixture(name: "DependencyResolution/External/Simple") { fixturePath in
let packageRoot = fixturePath.appending(component: "Bar")
let repositoriesPath = packageRoot.appending(components: ".build", "repositories")
let cachePath = fixturePath.appending(component: "cache")
let repositoriesCachePath = cachePath.appending(component: "repositories")
// Perform an initial fetch and populate the cache
_ = try execute(["resolve", "--cache-path", cachePath.pathString], packagePath: packageRoot)
// we have to check for the prefix here since the hash value changes because spm sees the `prefix`
// directory `/var/...` as `/private/var/...`.
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesPath).contains { $0.hasPrefix("Foo-") })
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesCachePath).contains { $0.hasPrefix("Foo-") })
// Remove .build folder
_ = try execute(["reset"], packagePath: packageRoot)
// Perform another cache this time from the cache
_ = try execute(["resolve", "--cache-path", cachePath.pathString], packagePath: packageRoot)
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesPath).contains { $0.hasPrefix("Foo-") })
// Remove .build and cache folder
_ = try execute(["reset"], packagePath: packageRoot)
try localFileSystem.removeFileTree(cachePath)
// Perform another fetch
_ = try execute(["resolve", "--cache-path", cachePath.pathString], packagePath: packageRoot)
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesPath).contains { $0.hasPrefix("Foo-") })
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesCachePath).contains { $0.hasPrefix("Foo-") })
}
}
func testDescribe() throws {
try fixture(name: "Miscellaneous/ExeTest") { fixturePath in
// Generate the JSON description.
let jsonResult = try SwiftPMProduct.SwiftPackage.executeProcess(["describe", "--type=json"], packagePath: fixturePath)
let jsonOutput = try jsonResult.utf8Output()
let json = try JSON(bytes: ByteString(encodingAsUTF8: jsonOutput))
// Check that tests don't appear in the product memberships.
XCTAssertEqual(json["name"]?.string, "ExeTest")
let jsonTarget0 = try XCTUnwrap(json["targets"]?.array?[0])
XCTAssertNil(jsonTarget0["product_memberships"])
let jsonTarget1 = try XCTUnwrap(json["targets"]?.array?[1])
XCTAssertEqual(jsonTarget1["product_memberships"]?.array?[0].stringValue, "Exe")
}
try fixture(name: "CFamilyTargets/SwiftCMixed") { fixturePath in
// Generate the JSON description.
let jsonResult = try SwiftPMProduct.SwiftPackage.executeProcess(["describe", "--type=json"], packagePath: fixturePath)
let jsonOutput = try jsonResult.utf8Output()
let json = try JSON(bytes: ByteString(encodingAsUTF8: jsonOutput))
// Check that the JSON description contains what we expect it to.
XCTAssertEqual(json["name"]?.string, "SwiftCMixed")
XCTAssertMatch(json["path"]?.string, .prefix("/"))
XCTAssertMatch(json["path"]?.string, .suffix("/" + fixturePath.basename))
XCTAssertEqual(json["targets"]?.array?.count, 3)
let jsonTarget0 = try XCTUnwrap(json["targets"]?.array?[0])
XCTAssertEqual(jsonTarget0["name"]?.stringValue, "SeaLib")
XCTAssertEqual(jsonTarget0["c99name"]?.stringValue, "SeaLib")
XCTAssertEqual(jsonTarget0["type"]?.stringValue, "library")
XCTAssertEqual(jsonTarget0["module_type"]?.stringValue, "ClangTarget")
let jsonTarget1 = try XCTUnwrap(json["targets"]?.array?[1])
XCTAssertEqual(jsonTarget1["name"]?.stringValue, "SeaExec")
XCTAssertEqual(jsonTarget1["c99name"]?.stringValue, "SeaExec")
XCTAssertEqual(jsonTarget1["type"]?.stringValue, "executable")
XCTAssertEqual(jsonTarget1["module_type"]?.stringValue, "SwiftTarget")
XCTAssertEqual(jsonTarget1["product_memberships"]?.array?[0].stringValue, "SeaExec")
let jsonTarget2 = try XCTUnwrap(json["targets"]?.array?[2])
XCTAssertEqual(jsonTarget2["name"]?.stringValue, "CExec")
XCTAssertEqual(jsonTarget2["c99name"]?.stringValue, "CExec")
XCTAssertEqual(jsonTarget2["type"]?.stringValue, "executable")
XCTAssertEqual(jsonTarget2["module_type"]?.stringValue, "ClangTarget")
XCTAssertEqual(jsonTarget2["product_memberships"]?.array?[0].stringValue, "CExec")
// Generate the text description.
let textResult = try SwiftPMProduct.SwiftPackage.executeProcess(["describe", "--type=text"], packagePath: fixturePath)
let textOutput = try textResult.utf8Output()
let textChunks = textOutput.components(separatedBy: "\n").reduce(into: [""]) { chunks, line in
// Split the text into chunks based on presence or absence of leading whitespace.
if line.hasPrefix(" ") == chunks[chunks.count-1].hasPrefix(" ") {
chunks[chunks.count-1].append(line + "\n")
}
else {
chunks.append(line + "\n")
}
}.filter{ !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
// Check that the text description contains what we expect it to.
// FIXME: This is a bit inelegant, but any errors are easy to reason about.
let textChunk0 = try XCTUnwrap(textChunks[0])
XCTAssertMatch(textChunk0, .contains("Name: SwiftCMixed"))
XCTAssertMatch(textChunk0, .contains("Path: /"))
XCTAssertMatch(textChunk0, .contains("/" + fixturePath.basename + "\n"))
XCTAssertMatch(textChunk0, .contains("Tools version: 4.2"))
XCTAssertMatch(textChunk0, .contains("Products:"))
let textChunk1 = try XCTUnwrap(textChunks[1])
XCTAssertMatch(textChunk1, .contains("Name: SeaExec"))
XCTAssertMatch(textChunk1, .contains("Type:\n Executable"))
XCTAssertMatch(textChunk1, .contains("Targets:\n SeaExec"))
let textChunk2 = try XCTUnwrap(textChunks[2])
XCTAssertMatch(textChunk2, .contains("Name: CExec"))
XCTAssertMatch(textChunk2, .contains("Type:\n Executable"))
XCTAssertMatch(textChunk2, .contains("Targets:\n CExec"))
let textChunk3 = try XCTUnwrap(textChunks[3])
XCTAssertMatch(textChunk3, .contains("Targets:"))
let textChunk4 = try XCTUnwrap(textChunks[4])
XCTAssertMatch(textChunk4, .contains("Name: SeaLib"))
XCTAssertMatch(textChunk4, .contains("C99name: SeaLib"))
XCTAssertMatch(textChunk4, .contains("Type: library"))
XCTAssertMatch(textChunk4, .contains("Module type: ClangTarget"))
XCTAssertMatch(textChunk4, .contains("Path: Sources/SeaLib"))
XCTAssertMatch(textChunk4, .contains("Sources:\n Foo.c"))
let textChunk5 = try XCTUnwrap(textChunks[5])
XCTAssertMatch(textChunk5, .contains("Name: SeaExec"))
XCTAssertMatch(textChunk5, .contains("C99name: SeaExec"))
XCTAssertMatch(textChunk5, .contains("Type: executable"))
XCTAssertMatch(textChunk5, .contains("Module type: SwiftTarget"))
XCTAssertMatch(textChunk5, .contains("Path: Sources/SeaExec"))
XCTAssertMatch(textChunk5, .contains("Sources:\n main.swift"))
let textChunk6 = try XCTUnwrap(textChunks[6])
XCTAssertMatch(textChunk6, .contains("Name: CExec"))
XCTAssertMatch(textChunk6, .contains("C99name: CExec"))
XCTAssertMatch(textChunk6, .contains("Type: executable"))
XCTAssertMatch(textChunk6, .contains("Module type: ClangTarget"))
XCTAssertMatch(textChunk6, .contains("Path: Sources/CExec"))
XCTAssertMatch(textChunk6, .contains("Sources:\n main.c"))
}
try fixture(name: "DependencyResolution/External/Simple/Bar") { fixturePath in
// Generate the JSON description.
let jsonResult = try SwiftPMProduct.SwiftPackage.executeProcess(["describe", "--type=json"], packagePath: fixturePath)
let jsonOutput = try jsonResult.utf8Output()
let json = try JSON(bytes: ByteString(encodingAsUTF8: jsonOutput))
// Check that product dependencies and memberships are as expected.
XCTAssertEqual(json["name"]?.string, "Bar")
let jsonTarget = try XCTUnwrap(json["targets"]?.array?[0])
XCTAssertEqual(jsonTarget["product_memberships"]?.array?[0].stringValue, "Bar")
XCTAssertEqual(jsonTarget["product_dependencies"]?.array?[0].stringValue, "Foo")
XCTAssertNil(jsonTarget["target_dependencies"])
}
}
func testDescribePackageUsingPlugins() throws {
try fixture(name: "Miscellaneous/Plugins/MySourceGenPlugin") { fixturePath in
// Generate the JSON description.
let result = try SwiftPMProduct.SwiftPackage.executeProcess(["describe", "--type=json"], packagePath: fixturePath)
XCTAssert(result.exitStatus == .terminated(code: 0), "`swift-package describe` failed: \(String(describing: try? result.utf8stderrOutput()))")
let json = try JSON(bytes: ByteString(encodingAsUTF8: result.utf8Output()))
// Check the contents of the JSON.
XCTAssertEqual(try XCTUnwrap(json["name"]).string, "MySourceGenPlugin")
let targetsArray = try XCTUnwrap(json["targets"]?.array)
let buildToolPluginTarget = try XCTUnwrap(targetsArray.first{ $0["name"]?.string == "MySourceGenBuildToolPlugin" }?.dictionary)
XCTAssertEqual(buildToolPluginTarget["module_type"]?.string, "PluginTarget")
XCTAssertEqual(buildToolPluginTarget["plugin_capability"]?.dictionary?["type"]?.string, "buildTool")
let prebuildPluginTarget = try XCTUnwrap(targetsArray.first{ $0["name"]?.string == "MySourceGenPrebuildPlugin" }?.dictionary)
XCTAssertEqual(prebuildPluginTarget["module_type"]?.string, "PluginTarget")
XCTAssertEqual(prebuildPluginTarget["plugin_capability"]?.dictionary?["type"]?.string, "buildTool")
}
}
func testDumpPackage() throws {
try fixture(name: "DependencyResolution/External/Complex") { fixturePath in
let packageRoot = fixturePath.appending(component: "app")
let (dumpOutput, _) = try execute(["dump-package"], packagePath: packageRoot)
let json = try JSON(bytes: ByteString(encodingAsUTF8: dumpOutput))
guard case let .dictionary(contents) = json else { XCTFail("unexpected result"); return }
guard case let .string(name)? = contents["name"] else { XCTFail("unexpected result"); return }
guard case let .array(platforms)? = contents["platforms"] else { XCTFail("unexpected result"); return }
XCTAssertEqual(name, "Dealer")
XCTAssertEqual(platforms, [
.dictionary([
"platformName": .string("macos"),
"version": .string("10.12"),
"options": .array([])
]),
.dictionary([
"platformName": .string("ios"),
"version": .string("10.0"),
"options": .array([])
]),
.dictionary([
"platformName": .string("tvos"),
"version": .string("11.0"),
"options": .array([])
]),
.dictionary([
"platformName": .string("watchos"),
"version": .string("5.0"),
"options": .array([])
]),
])
}
}
// Returns symbol graph with or without pretty printing.
private func symbolGraph(atPath path: AbsolutePath, withPrettyPrinting: Bool, file: StaticString = #file, line: UInt = #line) throws -> Data? {
let tool = try SwiftTool.createSwiftToolForTest(options: GlobalOptions.parse(["--package-path", path.pathString]))
let symbolGraphExtractorPath = try tool.getDestinationToolchain().getSymbolGraphExtract()
let arguments = withPrettyPrinting ? ["dump-symbol-graph", "--pretty-print"] : ["dump-symbol-graph"]
_ = try SwiftPMProduct.SwiftPackage.executeProcess(arguments, packagePath: path, env: ["SWIFT_SYMBOLGRAPH_EXTRACT": symbolGraphExtractorPath.pathString])
let enumerator = try XCTUnwrap(FileManager.default.enumerator(at: URL(fileURLWithPath: path.pathString), includingPropertiesForKeys: nil), file: file, line: line)
var symbolGraphURL: URL?
for case let url as URL in enumerator where url.lastPathComponent == "Bar.symbols.json" {
symbolGraphURL = url
break
}
let symbolGraphData = try Data(contentsOf: XCTUnwrap(symbolGraphURL, file: file, line: line))
// Double check that it's a valid JSON
XCTAssertNoThrow(try JSONSerialization.jsonObject(with: symbolGraphData), file: file, line: line)
return symbolGraphData
}
func testDumpSymbolGraphCompactFormatting() throws {
// Depending on how the test is running, the `swift-symbolgraph-extract` tool might be unavailable.
try XCTSkipIf((try? UserToolchain.default.getSymbolGraphExtract()) == nil, "skipping test because the `swift-symbolgraph-extract` tools isn't available")
try fixture(name: "DependencyResolution/Internal/Simple") { fixturePath in
let compactGraphData = try XCTUnwrap(symbolGraph(atPath: fixturePath, withPrettyPrinting: false))
let compactJSONText = try XCTUnwrap(String(data: compactGraphData, encoding: .utf8))
XCTAssertEqual(compactJSONText.components(separatedBy: .newlines).count, 1)
}
}
func testDumpSymbolGraphPrettyFormatting() throws {
// Depending on how the test is running, the `swift-symbolgraph-extract` tool might be unavailable.
try XCTSkipIf((try? UserToolchain.default.getSymbolGraphExtract()) == nil, "skipping test because the `swift-symbolgraph-extract` tools isn't available")
try fixture(name: "DependencyResolution/Internal/Simple") { fixturePath in
let prettyGraphData = try XCTUnwrap(symbolGraph(atPath: fixturePath, withPrettyPrinting: true))
let prettyJSONText = try XCTUnwrap(String(data: prettyGraphData, encoding: .utf8))
XCTAssertGreaterThan(prettyJSONText.components(separatedBy: .newlines).count, 1)
}
}
func testShowDependencies() throws {
try fixture(name: "DependencyResolution/External/Complex") { fixturePath in
let packageRoot = fixturePath.appending(component: "app")
let textOutput = try SwiftPMProduct.SwiftPackage.executeProcess(["show-dependencies", "--format=text"], packagePath: packageRoot).utf8Output()
XCTAssert(textOutput.contains("[email protected]"))
let jsonOutput = try SwiftPMProduct.SwiftPackage.executeProcess(["show-dependencies", "--format=json"], packagePath: packageRoot).utf8Output()
let json = try JSON(bytes: ByteString(encodingAsUTF8: jsonOutput))
guard case let .dictionary(contents) = json else { XCTFail("unexpected result"); return }
guard case let .string(name)? = contents["name"] else { XCTFail("unexpected result"); return }
XCTAssertEqual(name, "Dealer")
guard case let .string(path)? = contents["path"] else { XCTFail("unexpected result"); return }
XCTAssertEqual(try resolveSymlinks(try AbsolutePath(validating: path)), try resolveSymlinks(packageRoot))
}
}
func testShowDependencies_dotFormat_sr12016() throws {
// Confirm that SR-12016 is resolved.
// See https://bugs.swift.org/browse/SR-12016
let fileSystem = InMemoryFileSystem(emptyFiles: [
"/PackageA/Sources/TargetA/main.swift",
"/PackageB/Sources/TargetB/B.swift",
"/PackageC/Sources/TargetC/C.swift",
"/PackageD/Sources/TargetD/D.swift",
])
let manifestA = Manifest.createRootManifest(
name: "PackageA",
path: .init(path: "/PackageA"),
toolsVersion: .v5_3,
dependencies: [
.fileSystem(path: .init(path: "/PackageB")),
.fileSystem(path: .init(path: "/PackageC")),
],
products: [
try .init(name: "exe", type: .executable, targets: ["TargetA"])
],
targets: [
try .init(name: "TargetA", dependencies: ["PackageB", "PackageC"])
]
)
let manifestB = Manifest.createFileSystemManifest(
name: "PackageB",
path: .init(path: "/PackageB"),
toolsVersion: .v5_3,
dependencies: [
.fileSystem(path: .init(path: "/PackageC")),
.fileSystem(path: .init(path: "/PackageD")),
],
products: [
try .init(name: "PackageB", type: .library(.dynamic), targets: ["TargetB"])
],
targets: [
try .init(name: "TargetB", dependencies: ["PackageC", "PackageD"])
]
)
let manifestC = Manifest.createFileSystemManifest(
name: "PackageC",
path: .init(path: "/PackageC"),
toolsVersion: .v5_3,
dependencies: [
.fileSystem(path: .init(path: "/PackageD")),
],
products: [
try .init(name: "PackageC", type: .library(.dynamic), targets: ["TargetC"])
],
targets: [
try .init(name: "TargetC", dependencies: ["PackageD"])
]
)
let manifestD = Manifest.createFileSystemManifest(
name: "PackageD",
path: .init(path: "/PackageD"),
toolsVersion: .v5_3,
products: [
try .init(name: "PackageD", type: .library(.dynamic), targets: ["TargetD"])
],
targets: [
try .init(name: "TargetD")
]
)
let observability = ObservabilitySystem.makeForTesting()
let graph = try loadPackageGraph(
fileSystem: fileSystem,
manifests: [manifestA, manifestB, manifestC, manifestD],
observabilityScope: observability.topScope
)
XCTAssertNoDiagnostics(observability.diagnostics)
let output = BufferedOutputByteStream()
SwiftPackageTool.ShowDependencies.dumpDependenciesOf(rootPackage: graph.rootPackages[0], mode: .dot, on: output)
let dotFormat = output.bytes.description
var alreadyPutOut: Set<Substring> = []
for line in dotFormat.split(whereSeparator: { $0.isNewline }) {
if alreadyPutOut.contains(line) {
XCTFail("Same line was already put out: \(line)")
}
alreadyPutOut.insert(line)
}
let expectedLines: [Substring] = [
#""/PackageA" [label="packagea\n/PackageA\nunspecified"]"#,
#""/PackageB" [label="packageb\n/PackageB\nunspecified"]"#,
#""/PackageC" [label="packagec\n/PackageC\nunspecified"]"#,
#""/PackageD" [label="packaged\n/PackageD\nunspecified"]"#,
#""/PackageA" -> "/PackageB""#,
#""/PackageA" -> "/PackageC""#,
#""/PackageB" -> "/PackageC""#,
#""/PackageB" -> "/PackageD""#,
#""/PackageC" -> "/PackageD""#,
]
for expectedLine in expectedLines {
XCTAssertTrue(alreadyPutOut.contains(expectedLine),
"Expected line is not found: \(expectedLine)")
}
}
func testShowDependencies_redirectJsonOutput() throws {
try testWithTemporaryDirectory { tmpPath in
let fs = localFileSystem
let root = tmpPath.appending(components: "root")
let dep = tmpPath.appending(components: "dep")
// Create root package.
try fs.writeFileContents(root.appending(components: "Sources", "root", "main.swift")) { $0 <<< "" }
try fs.writeFileContents(root.appending(component: "Package.swift")) {
$0 <<< """
// swift-tools-version:4.2
import PackageDescription
let package = Package(
name: "root",
dependencies: [.package(url: "../dep", from: "1.0.0")],
targets: [.target(name: "root", dependencies: ["dep"])]
)
"""
}
// Create dependency.
try fs.writeFileContents(dep.appending(components: "Sources", "dep", "lib.swift")) { $0 <<< "" }
try fs.writeFileContents(dep.appending(component: "Package.swift")) {
$0 <<< """
// swift-tools-version:4.2
import PackageDescription
let package = Package(
name: "dep",
products: [.library(name: "dep", targets: ["dep"])],
targets: [.target(name: "dep")]
)
"""
}
do {
let depGit = GitRepository(path: dep)
try depGit.create()
try depGit.stageEverything()
try depGit.commit()
try depGit.tag(name: "1.0.0")
}
let resultPath = root.appending(component: "result.json")
_ = try execute(["show-dependencies", "--format", "json", "--output-path", resultPath.pathString ], packagePath: root)
XCTAssertFileExists(resultPath)
let jsonOutput: Data = try fs.readFileContents(resultPath)
let json = try JSON(data: jsonOutput)
XCTAssertEqual(json["name"]?.string, "root")
XCTAssertEqual(json["dependencies"]?[0]?["name"]?.string, "dep")
}
}
func testInitEmpty() throws {
try testWithTemporaryDirectory { tmpPath in
let fs = localFileSystem
let path = tmpPath.appending(component: "Foo")
try fs.createDirectory(path)
_ = try execute(["init", "--type", "empty"], packagePath: path)
XCTAssertFileExists(path.appending(component: "Package.swift"))
XCTAssertEqual(try fs.getDirectoryContents(path.appending(component: "Sources")), [])
XCTAssertEqual(try fs.getDirectoryContents(path.appending(component: "Tests")), [])
}
}
func testInitExecutable() throws {
try testWithTemporaryDirectory { tmpPath in
let fs = localFileSystem
let path = tmpPath.appending(component: "Foo")
try fs.createDirectory(path)
_ = try execute(["init", "--type", "executable"], packagePath: path)
let manifest = path.appending(component: "Package.swift")
let contents: String = try localFileSystem.readFileContents(manifest)
let version = InitPackage.newPackageToolsVersion
let versionSpecifier = "\(version.major).\(version.minor)"
XCTAssertMatch(contents, .prefix("// swift-tools-version:\(version < .v5_4 ? "" : " ")\(versionSpecifier)\n"))
XCTAssertFileExists(manifest)
XCTAssertEqual(try fs.getDirectoryContents(path.appending(component: "Sources").appending(component: "Foo")), ["Foo.swift"])
XCTAssertEqual(try fs.getDirectoryContents(path.appending(component: "Tests")).sorted(), ["FooTests"])
}
}
func testInitLibrary() throws {
try testWithTemporaryDirectory { tmpPath in
let fs = localFileSystem
let path = tmpPath.appending(component: "Foo")
try fs.createDirectory(path)
_ = try execute(["init"], packagePath: path)
XCTAssertFileExists(path.appending(component: "Package.swift"))
XCTAssertEqual(try fs.getDirectoryContents(path.appending(component: "Sources").appending(component: "Foo")), ["Foo.swift"])
XCTAssertEqual(try fs.getDirectoryContents(path.appending(component: "Tests")).sorted(), ["FooTests"])
}
}
func testInitCustomNameExecutable() throws {
try testWithTemporaryDirectory { tmpPath in
let fs = localFileSystem
let path = tmpPath.appending(component: "Foo")
try fs.createDirectory(path)
_ = try execute(["init", "--name", "CustomName", "--type", "executable"], packagePath: path)
let manifest = path.appending(component: "Package.swift")
let contents: String = try localFileSystem.readFileContents(manifest)
let version = InitPackage.newPackageToolsVersion
let versionSpecifier = "\(version.major).\(version.minor)"
XCTAssertMatch(contents, .prefix("// swift-tools-version:\(version < .v5_4 ? "" : " ")\(versionSpecifier)\n"))
XCTAssertFileExists(manifest)
XCTAssertEqual(try fs.getDirectoryContents(path.appending(component: "Sources").appending(component: "CustomName")), ["CustomName.swift"])
XCTAssertEqual(try fs.getDirectoryContents(path.appending(component: "Tests")).sorted(), ["CustomNameTests"])
}
}
func testPackageEditAndUnedit() throws {
try fixture(name: "Miscellaneous/PackageEdit") { fixturePath in
let fooPath = fixturePath.appending(component: "foo")
func build() throws -> (stdout: String, stderr: String) {
return try SwiftPMProduct.SwiftBuild.execute([], packagePath: fooPath)
}
// Put bar and baz in edit mode.
_ = try SwiftPMProduct.SwiftPackage.execute(["edit", "bar", "--branch", "bugfix"], packagePath: fooPath)
_ = try SwiftPMProduct.SwiftPackage.execute(["edit", "baz", "--branch", "bugfix"], packagePath: fooPath)
// Path to the executable.
let exec = [fooPath.appending(components: ".build", try UserToolchain.default.triple.platformBuildPathComponent(), "debug", "foo").pathString]
// We should see it now in packages directory.
let editsPath = fooPath.appending(components: "Packages", "bar")
XCTAssertDirectoryExists(editsPath)
let bazEditsPath = fooPath.appending(components: "Packages", "baz")
XCTAssertDirectoryExists(bazEditsPath)
// Removing baz externally should just emit an warning and not a build failure.
try localFileSystem.removeFileTree(bazEditsPath)
// Do a modification in bar and build.
try localFileSystem.writeFileContents(editsPath.appending(components: "Sources", "bar.swift"), bytes: "public let theValue = 88888\n")
let (_, stderr) = try build()
XCTAssertMatch(stderr, .contains("dependency 'baz' was being edited but is missing; falling back to original checkout"))
// We should be able to see that modification now.
XCTAssertEqual(try TSCBasic.Process.checkNonZeroExit(arguments: exec), "88888\n")
// The branch of edited package should be the one we provided when putting it in edit mode.
let editsRepo = GitRepository(path: editsPath)
XCTAssertEqual(try editsRepo.currentBranch(), "bugfix")
// It shouldn't be possible to unedit right now because of uncommited changes.
do {
_ = try SwiftPMProduct.SwiftPackage.execute(["unedit", "bar"], packagePath: fooPath)
XCTFail("Unexpected unedit success")
} catch {}
try editsRepo.stageEverything()
try editsRepo.commit()
// It shouldn't be possible to unedit right now because of unpushed changes.
do {
_ = try SwiftPMProduct.SwiftPackage.execute(["unedit", "bar"], packagePath: fooPath)
XCTFail("Unexpected unedit success")
} catch {}
// Push the changes.
try editsRepo.push(remote: "origin", branch: "bugfix")
// We should be able to unedit now.
_ = try SwiftPMProduct.SwiftPackage.execute(["unedit", "bar"], packagePath: fooPath)
// Test editing with a path i.e. ToT development.
let bazTot = fixturePath.appending(component: "tot")
try SwiftPMProduct.SwiftPackage.execute(["edit", "baz", "--path", bazTot.pathString], packagePath: fooPath)
XCTAssertTrue(localFileSystem.exists(bazTot))
XCTAssertTrue(localFileSystem.isSymlink(bazEditsPath))
// Edit a file in baz ToT checkout.
let bazTotPackageFile = bazTot.appending(component: "Package.swift")
let stream = BufferedOutputByteStream()
stream <<< (try localFileSystem.readFileContents(bazTotPackageFile)) <<< "\n// Edited."
try localFileSystem.writeFileContents(bazTotPackageFile, bytes: stream.bytes)
// Unediting baz will remove the symlink but not the checked out package.
try SwiftPMProduct.SwiftPackage.execute(["unedit", "baz"], packagePath: fooPath)
XCTAssertTrue(localFileSystem.exists(bazTot))
XCTAssertFalse(localFileSystem.isSymlink(bazEditsPath))
// Check that on re-editing with path, we don't make a new clone.
try SwiftPMProduct.SwiftPackage.execute(["edit", "baz", "--path", bazTot.pathString], packagePath: fooPath)
XCTAssertTrue(localFileSystem.isSymlink(bazEditsPath))
XCTAssertEqual(try localFileSystem.readFileContents(bazTotPackageFile), stream.bytes)
}
}
func testPackageClean() throws {
try fixture(name: "DependencyResolution/External/Simple") { fixturePath in
let packageRoot = fixturePath.appending(component: "Bar")
// Build it.
XCTAssertBuilds(packageRoot)
let buildPath = packageRoot.appending(component: ".build")
let binFile = buildPath.appending(components: try UserToolchain.default.triple.platformBuildPathComponent(), "debug", "Bar")
XCTAssertFileExists(binFile)
XCTAssert(localFileSystem.isDirectory(buildPath))
// Clean, and check for removal of the build directory but not Packages.
_ = try execute(["clean"], packagePath: packageRoot)
XCTAssertNoSuchPath(binFile)
// Clean again to ensure we get no error.
_ = try execute(["clean"], packagePath: packageRoot)
}
}
func testPackageReset() throws {
try fixture(name: "DependencyResolution/External/Simple") { fixturePath in
let packageRoot = fixturePath.appending(component: "Bar")
// Build it.
XCTAssertBuilds(packageRoot)
let buildPath = packageRoot.appending(component: ".build")
let binFile = buildPath.appending(components: try UserToolchain.default.triple.platformBuildPathComponent(), "debug", "Bar")
XCTAssertFileExists(binFile)
XCTAssert(localFileSystem.isDirectory(buildPath))
// Clean, and check for removal of the build directory but not Packages.
_ = try execute(["clean"], packagePath: packageRoot)
XCTAssertNoSuchPath(binFile)
XCTAssertFalse(try localFileSystem.getDirectoryContents(buildPath.appending(component: "repositories")).isEmpty)
// Fully clean.
_ = try execute(["reset"], packagePath: packageRoot)
XCTAssertFalse(localFileSystem.isDirectory(buildPath))
// Test that we can successfully run reset again.
_ = try execute(["reset"], packagePath: packageRoot)
}
}
func testPinningBranchAndRevision() throws {
try fixture(name: "Miscellaneous/PackageEdit") { fixturePath in
let fooPath = fixturePath.appending(component: "foo")
@discardableResult
func execute(_ args: String..., printError: Bool = true) throws -> String {
return try SwiftPMProduct.SwiftPackage.execute([] + args, packagePath: fooPath).stdout
}
try execute("update")
let pinsFile = fooPath.appending(component: "Package.resolved")
XCTAssertFileExists(pinsFile)
// Update bar repo.
let barPath = fixturePath.appending(component: "bar")
let barRepo = GitRepository(path: barPath)
try barRepo.checkout(newBranch: "YOLO")
let yoloRevision = try barRepo.getCurrentRevision()
// Try to pin bar at a branch.
do {
try execute("resolve", "bar", "--branch", "YOLO")
let pinsStore = try PinsStore(pinsFile: pinsFile, workingDirectory: fixturePath, fileSystem: localFileSystem, mirrors: .init())
let state = PinsStore.PinState.branch(name: "YOLO", revision: yoloRevision.identifier)
let identity = PackageIdentity(path: barPath)
XCTAssertEqual(pinsStore.pinsMap[identity]?.state, state)
}
// Try to pin bar at a revision.
do {
try execute("resolve", "bar", "--revision", yoloRevision.identifier)
let pinsStore = try PinsStore(pinsFile: pinsFile, workingDirectory: fixturePath, fileSystem: localFileSystem, mirrors: .init())
let state = PinsStore.PinState.revision(yoloRevision.identifier)
let identity = PackageIdentity(path: barPath)
XCTAssertEqual(pinsStore.pinsMap[identity]?.state, state)
}
// Try to pin bar at a bad revision.
do {
try execute("resolve", "bar", "--revision", "xxxxx")
XCTFail()
} catch {}
}
}
func testPinning() throws {
try fixture(name: "Miscellaneous/PackageEdit") { fixturePath in
let fooPath = fixturePath.appending(component: "foo")
func build() throws -> String {
return try SwiftPMProduct.SwiftBuild.execute([], packagePath: fooPath).stdout
}
let exec = [fooPath.appending(components: ".build", try UserToolchain.default.triple.platformBuildPathComponent(), "debug", "foo").pathString]
// Build and check.
_ = try build()
XCTAssertEqual(try TSCBasic.Process.checkNonZeroExit(arguments: exec).spm_chomp(), "\(5)")
// Get path to bar checkout.
let barPath = try SwiftPMProduct.packagePath(for: "bar", packageRoot: fooPath)
// Checks the content of checked out bar.swift.
func checkBar(_ value: Int, file: StaticString = #file, line: UInt = #line) throws {
let contents: String = try localFileSystem.readFileContents(barPath.appending(components:"Sources", "bar.swift"))
XCTAssertTrue(contents.spm_chomp().hasSuffix("\(value)"), file: file, line: line)
}
// We should see a pin file now.
let pinsFile = fooPath.appending(component: "Package.resolved")
XCTAssertFileExists(pinsFile)
// Test pins file.
do {
let pinsStore = try PinsStore(pinsFile: pinsFile, workingDirectory: fixturePath, fileSystem: localFileSystem, mirrors: .init())
XCTAssertEqual(pinsStore.pins.map{$0}.count, 2)
for pkg in ["bar", "baz"] {
let path = try SwiftPMProduct.packagePath(for: pkg, packageRoot: fooPath)
let pin = pinsStore.pinsMap[PackageIdentity(path: path)]!
XCTAssertEqual(pin.packageRef.identity, PackageIdentity(path: path))
guard case .localSourceControl(let path) = pin.packageRef.kind, path.pathString.hasSuffix(pkg) else {
return XCTFail("invalid pin location \(path)")
}
switch pin.state {
case .version(let version, revision: _):
XCTAssertEqual(version, "1.2.3")
default:
XCTFail("invalid pin state")
}
}
}
@discardableResult
func execute(_ args: String...) throws -> String {
return try SwiftPMProduct.SwiftPackage.execute([] + args, packagePath: fooPath).stdout
}
// Try to pin bar.
do {
try execute("resolve", "bar")
let pinsStore = try PinsStore(pinsFile: pinsFile, workingDirectory: fixturePath, fileSystem: localFileSystem, mirrors: .init())
let identity = PackageIdentity(path: barPath)
switch pinsStore.pinsMap[identity]?.state {
case .version(let version, revision: _):
XCTAssertEqual(version, "1.2.3")
default:
XCTFail("invalid pin state")
}
}
// Update bar repo.
do {
let barPath = fixturePath.appending(component: "bar")
let barRepo = GitRepository(path: barPath)
try localFileSystem.writeFileContents(barPath.appending(components: "Sources", "bar.swift"), bytes: "public let theValue = 6\n")
try barRepo.stageEverything()
try barRepo.commit()
try barRepo.tag(name: "1.2.4")
}
// Running package update with --repin should update the package.
do {
try execute("update")
try checkBar(6)
}
// We should be able to revert to a older version.
do {
try execute("resolve", "bar", "--version", "1.2.3")
let pinsStore = try PinsStore(pinsFile: pinsFile, workingDirectory: fixturePath, fileSystem: localFileSystem, mirrors: .init())
let identity = PackageIdentity(path: barPath)
switch pinsStore.pinsMap[identity]?.state {
case .version(let version, revision: _):
XCTAssertEqual(version, "1.2.3")
default:
XCTFail("invalid pin state")
}
try checkBar(5)
}
// Try pinning a dependency which is in edit mode.
do {
try execute("edit", "bar", "--branch", "bugfix")
XCTAssertThrowsCommandExecutionError(try execute("resolve", "bar")) { error in
XCTAssertMatch(error.stderr, .contains("error: edited dependency 'bar' can't be resolved"))
}
try execute("unedit", "bar")
}
}
}
func testOnlyUseVersionsFromResolvedFileFetchesWithExistingState() throws {
func writeResolvedFile(packageDir: AbsolutePath, repositoryURL: String, revision: String, version: String) throws {
try localFileSystem.writeFileContents(packageDir.appending(component: "Package.resolved")) {
$0 <<< """
{
"object": {
"pins": [
{
"package": "library",
"repositoryURL": "\(repositoryURL)",
"state": {
"branch": null,
"revision": "\(revision)",
"version": "\(version)"
}
}
]
},
"version": 1
}
"""
}
}
try testWithTemporaryDirectory { tmpPath in
let packageDir = tmpPath.appending(components: "library")
try localFileSystem.writeFileContents(packageDir.appending(component: "Package.swift")) {
$0 <<< """
// swift-tools-version:5.0
import PackageDescription
let package = Package(
name: "library",
products: [ .library(name: "library", targets: ["library"]) ],
targets: [ .target(name: "library") ]
)
"""
}
try localFileSystem.writeFileContents(packageDir.appending(components: "Sources", "library", "library.swift")) {
$0 <<< """
public func Foo() { }
"""
}
let depGit = GitRepository(path: packageDir)
try depGit.create()
try depGit.stageEverything()
try depGit.commit()
try depGit.tag(name: "1.0.0")
let initialRevision = try depGit.revision(forTag: "1.0.0")
let repositoryURL = "file://\(packageDir.pathString)"
let clientDir = tmpPath.appending(components: "client")
try localFileSystem.writeFileContents(clientDir.appending(component: "Package.swift")) {
$0 <<< """
// swift-tools-version:5.0
import PackageDescription
let package = Package(
name: "client",
dependencies: [ .package(url: "\(repositoryURL)", from: "1.0.0") ],
targets: [ .target(name: "client", dependencies: [ "library" ]) ]
)
"""
}
try localFileSystem.writeFileContents(clientDir.appending(components: "Sources", "client", "main.swift")) {
$0 <<< """
print("hello")
"""
}
// Initial resolution with clean state.
try writeResolvedFile(packageDir: clientDir, repositoryURL: repositoryURL, revision: initialRevision, version: "1.0.0")
_ = try execute(["resolve", "--only-use-versions-from-resolved-file"], packagePath: clientDir)
// Make a change to the dependency and tag a new version.
try localFileSystem.writeFileContents(packageDir.appending(components: "Sources", "library", "library.swift")) {
$0 <<< """
public func Best() { }
"""
}
try depGit.stageEverything()
try depGit.commit()
try depGit.tag(name: "1.0.1")
let updatedRevision = try depGit.revision(forTag: "1.0.1")
// Require new version but re-use existing state that hasn't fetched the latest revision, yet.
try writeResolvedFile(packageDir: clientDir, repositoryURL: repositoryURL, revision: updatedRevision, version: "1.0.1")
_ = try execute(["resolve", "--only-use-versions-from-resolved-file"], packagePath: clientDir)
}
}
func testSymlinkedDependency() throws {
try testWithTemporaryDirectory { path in
let fs = localFileSystem
let root = path.appending(components: "root")
let dep = path.appending(components: "dep")
let depSym = path.appending(components: "depSym")
// Create root package.
try fs.writeFileContents(root.appending(components: "Sources", "root", "main.swift")) { $0 <<< "" }
try fs.writeFileContents(root.appending(component: "Package.swift")) {
$0 <<< """
// swift-tools-version:4.2
import PackageDescription
let package = Package(
name: "root",
dependencies: [.package(url: "../depSym", from: "1.0.0")],
targets: [.target(name: "root", dependencies: ["dep"])]
)
"""
}
// Create dependency.
try fs.writeFileContents(dep.appending(components: "Sources", "dep", "lib.swift")) { $0 <<< "" }
try fs.writeFileContents(dep.appending(component: "Package.swift")) {
$0 <<< """
// swift-tools-version:4.2
import PackageDescription
let package = Package(
name: "dep",
products: [.library(name: "dep", targets: ["dep"])],
targets: [.target(name: "dep")]
)
"""
}
do {
let depGit = GitRepository(path: dep)
try depGit.create()
try depGit.stageEverything()
try depGit.commit()
try depGit.tag(name: "1.0.0")
}
// Create symlink to the dependency.
try fs.createSymbolicLink(depSym, pointingAt: dep, relative: false)
_ = try execute(["resolve"], packagePath: root)
}
}
func testMirrorConfig() throws {
try testWithTemporaryDirectory { fixturePath in
let fs = localFileSystem
let packageRoot = fixturePath.appending(component: "Foo")
let configOverride = fixturePath.appending(component: "configoverride")
let configFile = Workspace.DefaultLocations.mirrorsConfigurationFile(forRootPackage: packageRoot)
fs.createEmptyFiles(at: packageRoot, files:
"/Sources/Foo/Foo.swift",
"/Tests/FooTests/FooTests.swift",
"/Package.swift",
"anchor"
)
// Test writing.
var (stdout, stderr) = try execute(["config", "set-mirror", "--package-url", "https://github.com/foo/bar", "--mirror-url", "https://mygithub.com/foo/bar"], packagePath: packageRoot)
XCTAssertMatch(stderr, .contains("warning: '--package-url' option is deprecated; use '--original-url' instead"))
try execute(["config", "set-mirror", "--original-url", "[email protected]:apple/swift-package-manager.git", "--mirror-url", "[email protected]:foo/swift-package-manager.git"], packagePath: packageRoot)
XCTAssertTrue(fs.isFile(configFile))
// Test env override.
try execute(["config", "set-mirror", "--original-url", "https://github.com/foo/bar", "--mirror-url", "https://mygithub.com/foo/bar"], packagePath: packageRoot, env: ["SWIFTPM_MIRROR_CONFIG": configOverride.pathString])
XCTAssertTrue(fs.isFile(configOverride))
let content: String = try fs.readFileContents(configOverride)
XCTAssertMatch(content, .contains("mygithub"))
// Test reading.
(stdout, stderr) = try execute(["config", "get-mirror", "--package-url", "https://github.com/foo/bar"], packagePath: packageRoot)
XCTAssertEqual(stdout.spm_chomp(), "https://mygithub.com/foo/bar")
XCTAssertMatch(stderr, .contains("warning: '--package-url' option is deprecated; use '--original-url' instead"))
(stdout, _) = try execute(["config", "get-mirror", "--original-url", "[email protected]:apple/swift-package-manager.git"], packagePath: packageRoot)
XCTAssertEqual(stdout.spm_chomp(), "[email protected]:foo/swift-package-manager.git")
func check(stderr: String, _ block: () throws -> ()) {
XCTAssertThrowsCommandExecutionError(try block()) { error in
XCTAssertMatch(stderr, .contains(stderr))
}
}
check(stderr: "not found\n") {
try execute(["config", "get-mirror", "--original-url", "foo"], packagePath: packageRoot)
}
// Test deletion.
(_, stderr) = try execute(["config", "unset-mirror", "--package-url", "https://github.com/foo/bar"], packagePath: packageRoot)
XCTAssertMatch(stderr, .contains("warning: '--package-url' option is deprecated; use '--original-url' instead"))
try execute(["config", "unset-mirror", "--original-url", "[email protected]:foo/swift-package-manager.git"], packagePath: packageRoot)
check(stderr: "not found\n") {
try execute(["config", "get-mirror", "--original-url", "https://github.com/foo/bar"], packagePath: packageRoot)
}
check(stderr: "not found\n") {
try execute(["config", "get-mirror", "--original-url", "[email protected]:apple/swift-package-manager.git"], packagePath: packageRoot)
}
check(stderr: "error: Mirror not found for 'foo'\n") {
try execute(["config", "unset-mirror", "--original-url", "foo"], packagePath: packageRoot)
}
}
}
func testPackageLoadingCommandPathResilience() throws {
#if !os(macOS)
try XCTSkipIf(true, "skipping on non-macOS")
#endif
try fixture(name: "ValidLayouts/SingleModule") { fixturePath in
try testWithTemporaryDirectory { tmpdir in
// Create fake `xcrun` and `sandbox-exec` commands.
let fakeBinDir = tmpdir
for fakeCmdName in ["xcrun", "sandbox-exec"] {
let fakeCmdPath = fakeBinDir.appending(component: fakeCmdName)
try localFileSystem.writeFileContents(fakeCmdPath, body: { stream in
stream <<< """
#!/bin/sh
echo "wrong \(fakeCmdName) invoked"
exit 1
"""
})
try localFileSystem.chmod(.executable, path: fakeCmdPath)
}
// Invoke `swift-package`, passing in the overriding `PATH` environment variable.
let packageRoot = fixturePath.appending(component: "Library")
let patchedPATH = fakeBinDir.pathString + ":" + ProcessInfo.processInfo.environment["PATH"]!
let result = try SwiftPMProduct.SwiftPackage.executeProcess(["dump-package"], packagePath: packageRoot, env: ["PATH": patchedPATH])
let textOutput = try result.utf8Output() + result.utf8stderrOutput()
// Check that the wrong tools weren't invoked. We can't just check the exit code because of fallbacks.
XCTAssertNoMatch(textOutput, .contains("wrong xcrun invoked"))
XCTAssertNoMatch(textOutput, .contains("wrong sandbox-exec invoked"))
}
}
}
func testBuildToolPlugin() throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try testWithTemporaryDirectory { tmpPath in
// Create a sample package with a library target and a plugin.
let packageDir = tmpPath.appending(components: "MyPackage")
try localFileSystem.writeFileContents(packageDir.appending(component: "Package.swift")) {
$0 <<< """
// swift-tools-version: 5.5
import PackageDescription
let package = Package(
name: "MyPackage",
targets: [
.target(
name: "MyLibrary",
plugins: [
"MyPlugin",
]
),
.plugin(
name: "MyPlugin",
capability: .buildTool()
),
]
)
"""
}
try localFileSystem.writeFileContents(packageDir.appending(components: "Sources", "MyLibrary", "library.swift")) {
$0 <<< """
public func Foo() { }
"""
}
try localFileSystem.writeFileContents(packageDir.appending(components: "Sources", "MyLibrary", "library.foo")) {
$0 <<< """
a file with a filename suffix handled by the plugin
"""
}
try localFileSystem.writeFileContents(packageDir.appending(components: "Sources", "MyLibrary", "library.bar")) {
$0 <<< """
a file with a filename suffix not handled by the plugin
"""
}
try localFileSystem.writeFileContents(packageDir.appending(components: "Plugins", "MyPlugin", "plugin.swift")) {
$0 <<< """
import PackagePlugin
import Foundation
@main
struct MyBuildToolPlugin: BuildToolPlugin {
func createBuildCommands(
context: PluginContext,
target: Target
) throws -> [Command] {
// Expect the initial working directory for build tool plugins is the package directory.
guard FileManager.default.currentDirectoryPath == context.package.directory.string else {
throw "expected initial working directory ‘\\(FileManager.default.currentDirectoryPath)’"
}
// Check that the package display name is what we expect.
guard context.package.displayName == "MyPackage" else {
throw "expected display name to be ‘MyPackage’ but found ‘\\(context.package.displayName)’"
}
// Create and return a build command that uses all the `.foo` files in the target as inputs, so they get counted as having been handled.
let fooFiles = (target as? SourceModuleTarget)?.sourceFiles.compactMap{ $0.path.extension == "foo" ? $0.path : nil } ?? []
return [ .buildCommand(displayName: "A command", executable: Path("/bin/echo"), arguments: fooFiles, inputFiles: fooFiles) ]
}
}
extension String : Error {}
"""
}
// Invoke it, and check the results.
let result = try SwiftPMProduct.SwiftBuild.executeProcess([], packagePath: packageDir)
let output = try result.utf8Output() + result.utf8stderrOutput()
XCTAssertEqual(result.exitStatus, .terminated(code: 0), "output: \(output)")
XCTAssert(output.contains("Build complete!"))
// We expect a warning about `library.bar` but not about `library.foo`.
let stderrOutput = try result.utf8stderrOutput()
XCTAssertMatch(stderrOutput, .contains("found 1 file(s) which are unhandled"))
XCTAssertNoMatch(stderrOutput, .contains("Sources/MyLibrary/library.foo"))
XCTAssertMatch(stderrOutput, .contains("Sources/MyLibrary/library.bar"))
}
}
func testBuildToolPluginFailure() throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try testWithTemporaryDirectory { tmpPath in
// Create a sample package with a library target and a plugin.
let packageDir = tmpPath.appending(components: "MyPackage")
try localFileSystem.createDirectory(packageDir, recursive: true)
try localFileSystem.writeFileContents(packageDir.appending(component: "Package.swift"), string: """
// swift-tools-version: 5.6
import PackageDescription
let package = Package(
name: "MyPackage",
targets: [
.target(
name: "MyLibrary",
plugins: [
"MyPlugin",
]
),
.plugin(
name: "MyPlugin",
capability: .buildTool()
),
]
)
"""
)
let myLibraryTargetDir = packageDir.appending(components: "Sources", "MyLibrary")
try localFileSystem.createDirectory(myLibraryTargetDir, recursive: true)
try localFileSystem.writeFileContents(myLibraryTargetDir.appending(component: "library.swift"), string: """
public func Foo() { }
"""
)
let myPluginTargetDir = packageDir.appending(components: "Plugins", "MyPlugin")
try localFileSystem.createDirectory(myPluginTargetDir, recursive: true)
try localFileSystem.writeFileContents(myPluginTargetDir.appending(component: "plugin.swift"), string: """
import PackagePlugin
import Foundation
@main
struct MyBuildToolPlugin: BuildToolPlugin {
func createBuildCommands(
context: PluginContext,
target: Target
) throws -> [Command] {
print("This is text from the plugin")
throw "This is an error from the plugin"
return []
}
}
extension String : Error {}
"""
)
// Invoke it, and check the results.
let result = try SwiftPMProduct.SwiftBuild.executeProcess(["-v"], packagePath: packageDir)
let output = try result.utf8Output() + result.utf8stderrOutput()
XCTAssertNotEqual(result.exitStatus, .terminated(code: 0), "output: \(output)")
XCTAssertMatch(output, .contains("This is text from the plugin"))
XCTAssertMatch(output, .contains("error: This is an error from the plugin"))
XCTAssertMatch(output, .contains("Build complete!"))
}
}
func testArchiveSource() throws {
try fixture(name: "DependencyResolution/External/Simple") { fixturePath in
let packageRoot = fixturePath.appending(component: "Bar")
// Running without arguments or options
do {
let result = try SwiftPMProduct.SwiftPackage.executeProcess(["archive-source"], packagePath: packageRoot)
XCTAssertEqual(result.exitStatus, .terminated(code: 0))
let stdoutOutput = try result.utf8Output()
XCTAssert(stdoutOutput.contains("Created Bar.zip"), #"actual: "\#(stdoutOutput)""#)
// Running without arguments or options again, overwriting existing archive
do {
let result = try SwiftPMProduct.SwiftPackage.executeProcess(["archive-source"], packagePath: packageRoot)
XCTAssertEqual(result.exitStatus, .terminated(code: 0))
let stdoutOutput = try result.utf8Output()
XCTAssert(stdoutOutput.contains("Created Bar.zip"), #"actual: "\#(stdoutOutput)""#)
}
}
// Runnning with output as absolute path within package root
do {
let destination = packageRoot.appending(component: "Bar-1.2.3.zip")
let result = try SwiftPMProduct.SwiftPackage.executeProcess(["archive-source", "--output", destination.pathString], packagePath: packageRoot)
XCTAssertEqual(result.exitStatus, .terminated(code: 0))
let stdoutOutput = try result.utf8Output()
XCTAssert(stdoutOutput.contains("Created Bar-1.2.3.zip"), #"actual: "\#(stdoutOutput)""#)
}
// Running with output is outside the package root
try withTemporaryDirectory { tempDirectory in
let destination = tempDirectory.appending(component: "Bar-1.2.3.zip")
let result = try SwiftPMProduct.SwiftPackage.executeProcess(["archive-source", "--output", destination.pathString], packagePath: packageRoot)
XCTAssertEqual(result.exitStatus, .terminated(code: 0))
let stdoutOutput = try result.utf8Output()
XCTAssert(stdoutOutput.hasPrefix("Created /"), #"actual: "\#(stdoutOutput)""#)
XCTAssert(stdoutOutput.contains("Bar-1.2.3.zip"), #"actual: "\#(stdoutOutput)""#)
}
// Running without arguments or options in non-package directory
do {
let result = try SwiftPMProduct.SwiftPackage.executeProcess(["archive-source"], packagePath: fixturePath)
XCTAssertEqual(result.exitStatus, .terminated(code: 1))
let stderrOutput = try result.utf8stderrOutput()
XCTAssert(stderrOutput.contains("error: Could not find Package.swift in this directory or any of its parent directories."), #"actual: "\#(stderrOutput)""#)
}
// Runnning with output as absolute path to existing directory
do {
let destination = AbsolutePath.root
let result = try SwiftPMProduct.SwiftPackage.executeProcess(["archive-source", "--output", destination.pathString], packagePath: packageRoot)
XCTAssertEqual(result.exitStatus, .terminated(code: 1))
let stderrOutput = try result.utf8stderrOutput()
XCTAssert(
stderrOutput.contains("error: Couldn’t create an archive:"),
#"actual: "\#(stderrOutput)""#
)
}
}
}
func testCommandPlugin() throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try testWithTemporaryDirectory { tmpPath in
// Create a sample package with a library target, a plugin, and a local tool. It depends on a sample package which also has a tool.
let packageDir = tmpPath.appending(components: "MyPackage")
try localFileSystem.writeFileContents(packageDir.appending(components: "Package.swift")) {
$0 <<< """
// swift-tools-version: 5.6
import PackageDescription
let package = Package(
name: "MyPackage",
dependencies: [
.package(name: "HelperPackage", path: "VendoredDependencies/HelperPackage")
],
targets: [
.target(
name: "MyLibrary",
dependencies: [
.product(name: "HelperLibrary", package: "HelperPackage")
]
),
.plugin(
name: "MyPlugin",
capability: .command(
intent: .custom(verb: "mycmd", description: "What is mycmd anyway?")
),
dependencies: [
.target(name: "LocalBuiltTool"),
.target(name: "LocalBinaryTool"),
.product(name: "RemoteBuiltTool", package: "HelperPackage")
]
),
.binaryTarget(
name: "LocalBinaryTool",
path: "Binaries/LocalBinaryTool.artifactbundle"
),
.executableTarget(
name: "LocalBuiltTool"
)
]
)
"""
}
try localFileSystem.writeFileContents(packageDir.appending(components: "Sources", "MyLibrary", "library.swift")) {
$0 <<< """
public func Foo() { }
"""
}
try localFileSystem.writeFileContents(packageDir.appending(components: "Sources", "MyLibrary", "test.docc")) {
$0 <<< """
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "https://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleName</key>
<string>sample</string>
</dict>
"""
}
let hostTriple = try UserToolchain(destination: .hostDestination()).triple
let hostTripleString = hostTriple.isDarwin() ? hostTriple.tripleString(forPlatformVersion: "") : hostTriple.tripleString
try localFileSystem.writeFileContents(packageDir.appending(components: "Binaries", "LocalBinaryTool.artifactbundle", "info.json")) {
$0 <<< """
{ "schemaVersion": "1.0",
"artifacts": {
"LocalBinaryTool": {
"type": "executable",
"version": "1.2.3",
"variants": [
{ "path": "LocalBinaryTool.sh",
"supportedTriples": ["\(hostTripleString)"]
},
]
}
}
}
"""
}
try localFileSystem.writeFileContents(packageDir.appending(components: "Sources", "LocalBuiltTool", "main.swift")) {
$0 <<< """
print("Hello")
"""
}
try localFileSystem.writeFileContents(packageDir.appending(components: "Plugins", "MyPlugin", "plugin.swift")) {
$0 <<< """
import PackagePlugin
import Foundation
@main
struct MyCommandPlugin: CommandPlugin {
func performCommand(
context: PluginContext,
arguments: [String]
) throws {
print("This is MyCommandPlugin.")
// Print out the initial working directory so we can check it in the test.
print("Initial working directory: \\(FileManager.default.currentDirectoryPath)")
// Check that we can find a binary-provided tool in the same package.
print("Looking for LocalBinaryTool...")
let localBinaryTool = try context.tool(named: "LocalBinaryTool")
print("... found it at \\(localBinaryTool.path)")
// Check that we can find a source-built tool in the same package.
print("Looking for LocalBuiltTool...")
let localBuiltTool = try context.tool(named: "LocalBuiltTool")
print("... found it at \\(localBuiltTool.path)")
// Check that we can find a source-built tool in another package.
print("Looking for RemoteBuiltTool...")
let remoteBuiltTool = try context.tool(named: "RemoteBuiltTool")
print("... found it at \\(remoteBuiltTool.path)")
// Check that we can find a tool in the toolchain.
print("Looking for swiftc...")
let swiftc = try context.tool(named: "swiftc")
print("... found it at \\(swiftc.path)")
// Check that we can find a standard tool.
print("Looking for sed...")
let sed = try context.tool(named: "sed")
print("... found it at \\(sed.path)")
// Extract the `--target` arguments.
var argExtractor = ArgumentExtractor(arguments)
let targetNames = argExtractor.extractOption(named: "target")
let targets = try context.package.targets(named: targetNames)
// Print out the source files so that we can check them.
if let sourceFiles = (targets.first{ $0.name == "MyLibrary" } as? SourceModuleTarget)?.sourceFiles {
for file in sourceFiles {
print(" \\(file.path): \\(file.type)")
}
}
}
}
"""
}
// Create the sample vendored dependency package.
try localFileSystem.writeFileContents(packageDir.appending(components: "VendoredDependencies", "HelperPackage", "Package.swift")) {
$0 <<< """
// swift-tools-version: 5.5
import PackageDescription
let package = Package(
name: "HelperPackage",
products: [
.library(
name: "HelperLibrary",
targets: ["HelperLibrary"]
),
.executable(
name: "RemoteBuiltTool",
targets: ["RemoteBuiltTool"]
),
],
targets: [
.target(
name: "HelperLibrary"
),
.executableTarget(
name: "RemoteBuiltTool"
),
]
)
"""
}
try localFileSystem.writeFileContents(packageDir.appending(components: "VendoredDependencies", "HelperPackage", "Sources", "HelperLibrary", "library.swift")) {
$0 <<< """
public func Bar() { }
"""
}
try localFileSystem.writeFileContents(packageDir.appending(components: "VendoredDependencies", "HelperPackage", "Sources", "RemoteBuiltTool", "main.swift")) {
$0 <<< """
print("Hello")
"""
}
// Check that we can invoke the plugin with the "plugin" subcommand.
do {
let result = try SwiftPMProduct.SwiftPackage.executeProcess(["plugin", "mycmd"], packagePath: packageDir)
let output = try result.utf8Output() + result.utf8stderrOutput()
XCTAssertEqual(result.exitStatus, .terminated(code: 0), "output: \(output)")
XCTAssertMatch(output, .contains("This is MyCommandPlugin."))
}
// Check that we can also invoke it without the "plugin" subcommand.
do {
let result = try SwiftPMProduct.SwiftPackage.executeProcess(["mycmd"], packagePath: packageDir)
let output = try result.utf8Output() + result.utf8stderrOutput()
XCTAssertEqual(result.exitStatus, .terminated(code: 0), "output: \(output)")
XCTAssertMatch(output, .contains("This is MyCommandPlugin."))
}
// Testing listing the available command plugins.
do {
let result = try SwiftPMProduct.SwiftPackage.executeProcess(["plugin", "--list"], packagePath: packageDir)
let output = try result.utf8Output() + result.utf8stderrOutput()
XCTAssertEqual(result.exitStatus, .terminated(code: 0), "output: \(output)")
XCTAssertMatch(output, .contains("‘mycmd’ (plugin ‘MyPlugin’ in package ‘MyPackage’)"))
}
// Check that we get the expected error if trying to invoke a plugin with the wrong name.
do {
let result = try SwiftPMProduct.SwiftPackage.executeProcess(["my-nonexistent-cmd"], packagePath: packageDir)
let output = try result.utf8Output() + result.utf8stderrOutput()
XCTAssertNotEqual(result.exitStatus, .terminated(code: 0), "output: \(output)")
XCTAssertMatch(output, .contains("error: Unknown subcommand or plugin name 'my-nonexistent-cmd'"))
}
// Check that the .docc file was properly vended to the plugin.
do {
let result = try SwiftPMProduct.SwiftPackage.executeProcess(["mycmd", "--target", "MyLibrary"], packagePath: packageDir)
let output = try result.utf8Output() + result.utf8stderrOutput()
XCTAssertEqual(result.exitStatus, .terminated(code: 0), "output: \(output)")
XCTAssertMatch(output, .contains("Sources/MyLibrary/library.swift: source"))
XCTAssertMatch(output, .contains("Sources/MyLibrary/test.docc: unknown"))
}
// Check that the initial working directory is what we expected.
do {
let workingDirectory = FileManager.default.currentDirectoryPath
let result = try SwiftPMProduct.SwiftPackage.executeProcess(["mycmd"], packagePath: packageDir)
let output = try result.utf8Output() + result.utf8stderrOutput()
XCTAssertEqual(result.exitStatus, .terminated(code: 0), "output: \(output)")
XCTAssertMatch(output, .contains("Initial working directory: \(workingDirectory)"))
}
}
}
func testCommandPluginPermissions() throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try testWithTemporaryDirectory { tmpPath in
// Create a sample package with a library target and a plugin.
let packageDir = tmpPath.appending(components: "MyPackage")
try localFileSystem.writeFileContents(packageDir.appending(components: "Package.swift")) {
$0 <<< """
// swift-tools-version: 5.6
import PackageDescription
import Foundation
let package = Package(
name: "MyPackage",
targets: [
.target(
name: "MyLibrary"
),
.plugin(
name: "MyPlugin",
capability: .command(
intent: .custom(verb: "PackageScribbler", description: "Help description"),
// We use an environment here so we can control whether we declare the permission.
permissions: ProcessInfo.processInfo.environment["DECLARE_PACKAGE_WRITING_PERMISSION"] == "1"
? [.writeToPackageDirectory(reason: "For testing purposes")]
: []
)
),
]
)
"""
}
try localFileSystem.writeFileContents(packageDir.appending(components: "Sources", "MyLibrary", "library.swift")) {
$0 <<< """
public func Foo() { }
"""
}
try localFileSystem.writeFileContents(packageDir.appending(components: "Plugins", "MyPlugin", "plugin.swift")) {
$0 <<< """
import PackagePlugin
import Foundation
@main
struct MyCommandPlugin: CommandPlugin {
func performCommand(
context: PluginContext,
arguments: [String]
) throws {
// Check that we can write to the package directory.
print("Trying to write to the package directory...")
guard FileManager.default.createFile(atPath: context.package.directory.appending("Foo").string, contents: Data("Hello".utf8)) else {
throw "Couldn’t create file at path \\(context.package.directory.appending("Foo"))"
}
print("... successfully created it")
}
}
extension String: Error {}
"""
}
// Check that we get an error if the plugin needs permission but if we don't give it to them. Note that sandboxing is only currently supported on macOS.
#if os(macOS)
do {
let result = try SwiftPMProduct.SwiftPackage.executeProcess(["plugin", "PackageScribbler"], packagePath: packageDir, env: ["DECLARE_PACKAGE_WRITING_PERMISSION": "1"])
XCTAssertNotEqual(result.exitStatus, .terminated(code: 0))
XCTAssertNoMatch(try result.utf8Output(), .contains("successfully created it"))
XCTAssertMatch(try result.utf8stderrOutput(), .contains("error: Plugin ‘MyPlugin’ wants permission to write to the package directory."))
XCTAssertMatch(try result.utf8stderrOutput(), .contains("Stated reason: “For testing purposes”."))
XCTAssertMatch(try result.utf8stderrOutput(), .contains("Use `--allow-writing-to-package-directory` to allow this."))
}
#endif
// Check that we don't get an error (and also are allowed to write to the package directory) if we pass `--allow-writing-to-package-directory`.
do {
let result = try SwiftPMProduct.SwiftPackage.executeProcess(["plugin", "--allow-writing-to-package-directory", "PackageScribbler"], packagePath: packageDir, env: ["DECLARE_PACKAGE_WRITING_PERMISSION": "1"])
XCTAssertEqual(result.exitStatus, .terminated(code: 0))
XCTAssertMatch(try result.utf8Output(), .contains("successfully created it"))
XCTAssertNoMatch(try result.utf8stderrOutput(), .contains("error: Couldn’t create file at path"))
}
// Check that we get an error if the plugin doesn't declare permission but tries to write anyway. Note that sandboxing is only currently supported on macOS.
#if os(macOS)
do {
let result = try SwiftPMProduct.SwiftPackage.executeProcess(["plugin", "PackageScribbler"], packagePath: packageDir, env: ["DECLARE_PACKAGE_WRITING_PERMISSION": "0"])
XCTAssertNotEqual(result.exitStatus, .terminated(code: 0))
XCTAssertNoMatch(try result.utf8Output(), .contains("successfully created it"))
XCTAssertMatch(try result.utf8stderrOutput(), .contains("error: Couldn’t create file at path"))
}
#endif
}
}
func testCommandPluginSymbolGraphCallbacks() throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
// Depending on how the test is running, the `swift-symbolgraph-extract` tool might be unavailable.
try XCTSkipIf((try? UserToolchain.default.getSymbolGraphExtract()) == nil, "skipping test because the `swift-symbolgraph-extract` tools isn't available")
try testWithTemporaryDirectory { tmpPath in
// Create a sample package with a library, and executable, and a plugin.
let packageDir = tmpPath.appending(components: "MyPackage")
try localFileSystem.writeFileContents(packageDir.appending(components: "Package.swift")) {
$0 <<< """
// swift-tools-version: 5.6
import PackageDescription
let package = Package(
name: "MyPackage",
targets: [
.target(
name: "MyLibrary"
),
.executableTarget(
name: "MyCommand",
dependencies: ["MyLibrary"]
),
.plugin(
name: "MyPlugin",
capability: .command(
intent: .documentationGeneration()
)
),
]
)
"""
}
try localFileSystem.writeFileContents(packageDir.appending(components: "Sources", "MyLibrary", "library.swift")) {
$0 <<< """
public func GetGreeting() -> String { return "Hello" }
"""
}
try localFileSystem.writeFileContents(packageDir.appending(components: "Sources", "MyCommand", "main.swift")) {
$0 <<< """
import MyLibrary
print("\\(GetGreeting()), World!")
"""
}
try localFileSystem.writeFileContents(packageDir.appending(components: "Plugins", "MyPlugin", "plugin.swift")) {
$0 <<< """
import PackagePlugin
import Foundation
@main
struct MyCommandPlugin: CommandPlugin {
func performCommand(
context: PluginContext,
arguments: [String]
) throws {
// Ask for and print out the symbol graph directory for each target.
var argExtractor = ArgumentExtractor(arguments)
let targetNames = argExtractor.extractOption(named: "target")
let targets = targetNames.isEmpty
? context.package.targets
: try context.package.targets(named: targetNames)
for target in targets {
let symbolGraph = try packageManager.getSymbolGraph(for: target,
options: .init(minimumAccessLevel: .public))
print("\\(target.name): \\(symbolGraph.directoryPath)")
}
}
}
"""
}
// Check that if we don't pass any target, we successfully get symbol graph information for all targets in the package, and at different paths.
do {
let result = try SwiftPMProduct.SwiftPackage.executeProcess(["generate-documentation"], packagePath: packageDir)
let output = try result.utf8Output() + result.utf8stderrOutput()
XCTAssertEqual(result.exitStatus, .terminated(code: 0), "output: \(output)")
XCTAssertMatch(output, .and(.contains("MyLibrary:"), .contains("mypackage/MyLibrary")))
XCTAssertMatch(output, .and(.contains("MyCommand:"), .contains("mypackage/MyCommand")))
}
// Check that if we pass a target, we successfully get symbol graph information for just the target we asked for.
do {
let result = try SwiftPMProduct.SwiftPackage.executeProcess(["generate-documentation", "--target", "MyLibrary"], packagePath: packageDir)
let output = try result.utf8Output() + result.utf8stderrOutput()
XCTAssertEqual(result.exitStatus, .terminated(code: 0), "output: \(output)")
XCTAssertMatch(output, .and(.contains("MyLibrary:"), .contains("mypackage/MyLibrary")))
XCTAssertNoMatch(output, .and(.contains("MyCommand:"), .contains("mypackage/MyCommand")))
}
}
}
func testCommandPluginBuildingCallbacks() throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try testWithTemporaryDirectory { tmpPath in
// Create a sample package with a library, an executable, and a command plugin.
let packageDir = tmpPath.appending(components: "MyPackage")
try localFileSystem.createDirectory(packageDir, recursive: true)
try localFileSystem.writeFileContents(packageDir.appending(components: "Package.swift"), string: """
// swift-tools-version: 5.6
import PackageDescription
let package = Package(
name: "MyPackage",
products: [
.library(
name: "MyAutomaticLibrary",
targets: ["MyLibrary"]
),
.library(
name: "MyStaticLibrary",
type: .static,
targets: ["MyLibrary"]
),
.library(
name: "MyDynamicLibrary",
type: .dynamic,
targets: ["MyLibrary"]
),
.executable(
name: "MyExecutable",
targets: ["MyExecutable"]
),
],
targets: [
.target(
name: "MyLibrary"
),
.executableTarget(
name: "MyExecutable",
dependencies: ["MyLibrary"]
),
.plugin(
name: "MyPlugin",
capability: .command(
intent: .custom(verb: "my-build-tester", description: "Help description")
)
),
]
)
"""
)
let myPluginTargetDir = packageDir.appending(components: "Plugins", "MyPlugin")
try localFileSystem.createDirectory(myPluginTargetDir, recursive: true)
try localFileSystem.writeFileContents(myPluginTargetDir.appending(component: "plugin.swift"), string: """
import PackagePlugin
@main
struct MyCommandPlugin: CommandPlugin {
func performCommand(
context: PluginContext,
arguments: [String]
) throws {
// Extract the plugin arguments.
var argExtractor = ArgumentExtractor(arguments)
let productNames = argExtractor.extractOption(named: "product")
if productNames.count != 1 {
throw "Expected exactly one product name, but had: \\(productNames.joined(separator: ", "))"
}
let products = try context.package.products(named: productNames)
let printCommands = (argExtractor.extractFlag(named: "print-commands") > 0)
let release = (argExtractor.extractFlag(named: "release") > 0)
if let unextractedArgs = argExtractor.unextractedOptionsOrFlags.first {
throw "Unknown option: \\(unextractedArgs)"
}
let positionalArgs = argExtractor.remainingArguments
if !positionalArgs.isEmpty {
throw "Unexpected extra arguments: \\(positionalArgs)"
}
do {
var parameters = PackageManager.BuildParameters()
parameters.configuration = release ? .release : .debug
parameters.logging = printCommands ? .verbose : .concise
parameters.otherSwiftcFlags = ["-DEXTRA_SWIFT_FLAG"]
let result = try packageManager.build(.product(products[0].name), parameters: parameters)
print("succeeded: \\(result.succeeded)")
for artifact in result.builtArtifacts {
print("artifact-path: \\(artifact.path.string)")
print("artifact-kind: \\(artifact.kind)")
}
print("log:\\n\\(result.logText)")
}
catch {
print("error from the plugin host: \\(error)")
}
}
}
extension String: Error {}
"""
)
let myLibraryTargetDir = packageDir.appending(components: "Sources", "MyLibrary")
try localFileSystem.createDirectory(myLibraryTargetDir, recursive: true)
try localFileSystem.writeFileContents(myLibraryTargetDir.appending(component: "library.swift"), string: """
public func GetGreeting() -> String { return "Hello" }
"""
)
let myExecutableTargetDir = packageDir.appending(components: "Sources", "MyExecutable")
try localFileSystem.createDirectory(myExecutableTargetDir, recursive: true)
try localFileSystem.writeFileContents(myExecutableTargetDir.appending(component: "main.swift"), string: """
import MyLibrary
print("\\(GetGreeting()), World!")
"""
)
// Invoke the plugin with parameters choosing a verbose build of MyExecutable for debugging.
do {
let result = try SwiftPMProduct.SwiftPackage.executeProcess(["my-build-tester", "--product", "MyExecutable", "--print-commands"], packagePath: packageDir)
let output = try result.utf8Output() + result.utf8stderrOutput()
XCTAssertEqual(result.exitStatus, .terminated(code: 0), "output: \(output)")
XCTAssertMatch(output, .contains("Building for debugging..."))
XCTAssertNoMatch(output, .contains("Building for production..."))
XCTAssertMatch(output, .contains("-module-name MyExecutable"))
XCTAssertMatch(output, .contains("-DEXTRA_SWIFT_FLAG"))
XCTAssertMatch(output, .contains("Build complete!"))
XCTAssertMatch(output, .contains("succeeded: true"))
XCTAssertMatch(output, .and(.contains("artifact-path:"), .contains("debug/MyExecutable")))
XCTAssertMatch(output, .and(.contains("artifact-kind:"), .contains("executable")))
}
// Invoke the plugin with parameters choosing a concise build of MyExecutable for release.
do {
let result = try SwiftPMProduct.SwiftPackage.executeProcess(["my-build-tester", "--product", "MyExecutable", "--release"], packagePath: packageDir)
let output = try result.utf8Output() + result.utf8stderrOutput()
XCTAssertEqual(result.exitStatus, .terminated(code: 0), "output: \(output)")
XCTAssertMatch(output, .contains("Building for production..."))
XCTAssertNoMatch(output, .contains("Building for debug..."))
XCTAssertNoMatch(output, .contains("-module-name MyExecutable"))
XCTAssertMatch(output, .contains("Build complete!"))
XCTAssertMatch(output, .contains("succeeded: true"))
XCTAssertMatch(output, .and(.contains("artifact-path:"), .contains("release/MyExecutable")))
XCTAssertMatch(output, .and(.contains("artifact-kind:"), .contains("executable")))
}
// Invoke the plugin with parameters choosing a verbose build of MyStaticLibrary for release.
do {
let result = try SwiftPMProduct.SwiftPackage.executeProcess(["my-build-tester", "--product", "MyStaticLibrary", "--print-commands", "--release"], packagePath: packageDir)
let output = try result.utf8Output() + result.utf8stderrOutput()
XCTAssertEqual(result.exitStatus, .terminated(code: 0), "output: \(output)")
XCTAssertMatch(output, .contains("Building for production..."))
XCTAssertNoMatch(output, .contains("Building for debug..."))
XCTAssertNoMatch(output, .contains("-module-name MyLibrary"))
XCTAssertMatch(output, .contains("Build complete!"))
XCTAssertMatch(output, .contains("succeeded: true"))
XCTAssertMatch(output, .and(.contains("artifact-path:"), .contains("release/libMyStaticLibrary.")))
XCTAssertMatch(output, .and(.contains("artifact-kind:"), .contains("staticLibrary")))
}
// Invoke the plugin with parameters choosing a verbose build of MyDynamicLibrary for release.
do {
let result = try SwiftPMProduct.SwiftPackage.executeProcess(["my-build-tester", "--product", "MyDynamicLibrary", "--print-commands", "--release"], packagePath: packageDir)
let output = try result.utf8Output() + result.utf8stderrOutput()
XCTAssertEqual(result.exitStatus, .terminated(code: 0), "output: \(output)")
XCTAssertMatch(output, .contains("Building for production..."))
XCTAssertNoMatch(output, .contains("Building for debug..."))
XCTAssertNoMatch(output, .contains("-module-name MyLibrary"))
XCTAssertMatch(output, .contains("Build complete!"))
XCTAssertMatch(output, .contains("succeeded: true"))
XCTAssertMatch(output, .and(.contains("artifact-path:"), .contains("release/libMyDynamicLibrary.")))
XCTAssertMatch(output, .and(.contains("artifact-kind:"), .contains("dynamicLibrary")))
}
}
}
func testCommandPluginTestingCallbacks() throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
// Depending on how the test is running, the `llvm-profdata` and `llvm-cov` tool might be unavailable.
try XCTSkipIf((try? UserToolchain.default.getLLVMProf()) == nil, "skipping test because the `llvm-profdata` tool isn't available")
try XCTSkipIf((try? UserToolchain.default.getLLVMCov()) == nil, "skipping test because the `llvm-cov` tool isn't available")
try testWithTemporaryDirectory { tmpPath in
// Create a sample package with a library, a command plugin, and a couple of tests.
let packageDir = tmpPath.appending(components: "MyPackage")
try localFileSystem.createDirectory(packageDir, recursive: true)
try localFileSystem.writeFileContents(packageDir.appending(components: "Package.swift"), string: """
// swift-tools-version: 5.6
import PackageDescription
let package = Package(
name: "MyPackage",
targets: [
.target(
name: "MyLibrary"
),
.plugin(
name: "MyPlugin",
capability: .command(
intent: .custom(verb: "my-test-tester", description: "Help description")
)
),
.testTarget(
name: "MyBasicTests"
),
.testTarget(
name: "MyExtendedTests"
),
]
)
"""
)
let myPluginTargetDir = packageDir.appending(components: "Plugins", "MyPlugin")
try localFileSystem.createDirectory(myPluginTargetDir, recursive: true)
try localFileSystem.writeFileContents(myPluginTargetDir.appending(component: "plugin.swift"), string: """
import PackagePlugin
@main
struct MyCommandPlugin: CommandPlugin {
func performCommand(
context: PluginContext,
arguments: [String]
) throws {
do {
let result = try packageManager.test(.filtered(["MyBasicTests"]), parameters: .init(enableCodeCoverage: true))
assert(result.succeeded == true)
assert(result.testTargets.count == 1)
assert(result.testTargets[0].name == "MyBasicTests")
assert(result.testTargets[0].testCases.count == 2)
assert(result.testTargets[0].testCases[0].name == "MyBasicTests.TestSuite1")
assert(result.testTargets[0].testCases[0].tests.count == 2)
assert(result.testTargets[0].testCases[0].tests[0].name == "testBooleanInvariants")
assert(result.testTargets[0].testCases[0].tests[1].result == .succeeded)
assert(result.testTargets[0].testCases[0].tests[1].name == "testNumericalInvariants")
assert(result.testTargets[0].testCases[0].tests[1].result == .succeeded)
assert(result.testTargets[0].testCases[1].name == "MyBasicTests.TestSuite2")
assert(result.testTargets[0].testCases[1].tests.count == 1)
assert(result.testTargets[0].testCases[1].tests[0].name == "testStringInvariants")
assert(result.testTargets[0].testCases[1].tests[0].result == .succeeded)
assert(result.codeCoverageDataFile?.extension == "json")
}
catch {
print("error from the plugin host: \\(error)")
}
}
}
"""
)
let myLibraryTargetDir = packageDir.appending(components: "Sources", "MyLibrary")
try localFileSystem.createDirectory(myLibraryTargetDir, recursive: true)
try localFileSystem.writeFileContents(myLibraryTargetDir.appending(component: "library.swift"), string: """
public func Foo() { }
"""
)
let myBasicTestsTargetDir = packageDir.appending(components: "Tests", "MyBasicTests")
try localFileSystem.createDirectory(myBasicTestsTargetDir, recursive: true)
try localFileSystem.writeFileContents(myBasicTestsTargetDir.appending(component: "Test1.swift"), string: """
import XCTest
class TestSuite1: XCTestCase {
func testBooleanInvariants() throws {
XCTAssertEqual(true || true, true)
}
func testNumericalInvariants() throws {
XCTAssertEqual(1 + 1, 2)
}
}
"""
)
try localFileSystem.writeFileContents(myBasicTestsTargetDir.appending(component: "Test2.swift"), string: """
import XCTest
class TestSuite2: XCTestCase {
func testStringInvariants() throws {
XCTAssertEqual("" + "", "")
}
}
"""
)
let myExtendedTestsTargetDir = packageDir.appending(components: "Tests", "MyExtendedTests")
try localFileSystem.createDirectory(myExtendedTestsTargetDir, recursive: true)
try localFileSystem.writeFileContents(myExtendedTestsTargetDir.appending(component: "Test3.swift"), string: """
import XCTest
class TestSuite3: XCTestCase {
func testArrayInvariants() throws {
XCTAssertEqual([] + [], [])
}
func testImpossibilities() throws {
XCTFail("no can do")
}
}
"""
)
// Check basic usage with filtering and code coverage. The plugin itself asserts a bunch of values.
do {
let result = try SwiftPMProduct.SwiftPackage.executeProcess(["my-test-tester"], packagePath: packageDir)
let output = try result.utf8Output() + result.utf8stderrOutput()
print(output)
XCTAssertEqual(result.exitStatus, .terminated(code: 0), "output: \(output)")
}
// We'll add checks for various error conditions here in a future commit.
}
}
func testPluginAPIs() throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try testWithTemporaryDirectory { tmpPath in
// Create a sample package with a plugin to test various parts of the API.
let packageDir = tmpPath.appending(components: "MyPackage")
try localFileSystem.createDirectory(packageDir, recursive: true)
try localFileSystem.writeFileContents(packageDir.appending(component: "Package.swift"), string: """
// swift-tools-version: 5.6
import PackageDescription
let package = Package(
name: "MyPackage",
dependencies: [
.package(name: "HelperPackage", path: "VendoredDependencies/HelperPackage")
],
targets: [
.target(
name: "FirstTarget",
dependencies: [
]
),
.target(
name: "SecondTarget",
dependencies: [
"FirstTarget",
]
),
.target(
name: "ThirdTarget",
dependencies: [
"FirstTarget",
]
),
.target(
name: "FourthTarget",
dependencies: [
"SecondTarget",
"ThirdTarget",
.product(name: "HelperLibrary", package: "HelperPackage"),
]
),
.executableTarget(
name: "FifthTarget",
dependencies: [
"FirstTarget",
"ThirdTarget",
]
),
.testTarget(
name: "TestTarget",
dependencies: [
"SecondTarget",
]
),
.plugin(
name: "PrintTargetDependencies",
capability: .command(
intent: .custom(verb: "print-target-dependencies", description: "Plugin that prints target dependencies; argument is name of target")
)
),
]
)
""")
let firstTargetDir = packageDir.appending(components: "Sources", "FirstTarget")
try localFileSystem.createDirectory(firstTargetDir, recursive: true)
try localFileSystem.writeFileContents(firstTargetDir.appending(component: "library.swift"), string: """
public func FirstFunc() { }
""")
let secondTargetDir = packageDir.appending(components: "Sources", "SecondTarget")
try localFileSystem.createDirectory(secondTargetDir, recursive: true)
try localFileSystem.writeFileContents(secondTargetDir.appending(component: "library.swift"), string: """
public func SecondFunc() { }
""")
let thirdTargetDir = packageDir.appending(components: "Sources", "ThirdTarget")
try localFileSystem.createDirectory(thirdTargetDir, recursive: true)
try localFileSystem.writeFileContents(thirdTargetDir.appending(component: "library.swift"), string: """
public func ThirdFunc() { }
""")
let fourthTargetDir = packageDir.appending(components: "Sources", "FourthTarget")
try localFileSystem.createDirectory(fourthTargetDir, recursive: true)
try localFileSystem.writeFileContents(fourthTargetDir.appending(component: "library.swift"), string: """
public func FourthFunc() { }
""")
let fifthTargetDir = packageDir.appending(components: "Sources", "FifthTarget")
try localFileSystem.createDirectory(fifthTargetDir, recursive: true)
try localFileSystem.writeFileContents(fifthTargetDir.appending(component: "main.swift"), string: """
@main struct MyExec {
func run() throws {}
}
""")
let testTargetDir = packageDir.appending(components: "Tests", "TestTarget")
try localFileSystem.createDirectory(testTargetDir, recursive: true)
try localFileSystem.writeFileContents(testTargetDir.appending(component: "tests.swift"), string: """
import XCTest
class MyTestCase: XCTestCase {
}
""")
let pluginTargetTargetDir = packageDir.appending(components: "Plugins", "PrintTargetDependencies")
try localFileSystem.createDirectory(pluginTargetTargetDir, recursive: true)
try localFileSystem.writeFileContents(pluginTargetTargetDir.appending(component: "plugin.swift"), string: """
import PackagePlugin
@main struct PrintTargetDependencies: CommandPlugin {
func performCommand(
context: PluginContext,
arguments: [String]
) throws {
// Print names of the recursive dependencies of the given target.
var argExtractor = ArgumentExtractor(arguments)
guard let targetName = argExtractor.extractOption(named: "target").first else {
throw "No target argument provided"
}
guard let target = try? context.package.targets(named: [targetName]).first else {
throw "No target found with the name '\\(targetName)'"
}
print("Recursive dependencies of '\\(target.name)': \\(target.recursiveTargetDependencies.map(\\.name))")
let execProducts = context.package.products(ofType: ExecutableProduct.self)
print("execProducts: \\(execProducts.map{ $0.name })")
let swiftTargets = context.package.targets(ofType: SwiftSourceModuleTarget.self)
print("swiftTargets: \\(swiftTargets.map{ $0.name })")
let swiftSources = swiftTargets.flatMap{ $0.sourceFiles(withSuffix: ".swift") }
print("swiftSources: \\(swiftSources.map{ $0.path.lastComponent })")
if let target = target as? SourceModuleTarget {
print("Module kind of '\\(target.name)': \\(target.kind)")
}
}
}
extension String: Error {}
""")
// Create a separate vendored package so that we can test dependencies across products in other packages.
let helperPackageDir = packageDir.appending(components: "VendoredDependencies", "HelperPackage")
try localFileSystem.createDirectory(helperPackageDir, recursive: true)
try localFileSystem.writeFileContents(helperPackageDir.appending(component: "Package.swift"), string: """
// swift-tools-version: 5.6
import PackageDescription
let package = Package(
name: "HelperPackage",
products: [
.library(
name: "HelperLibrary",
targets: ["HelperLibrary"])
],
targets: [
.target(
name: "HelperLibrary",
path: ".")
]
)
""")
try localFileSystem.writeFileContents(helperPackageDir.appending(component: "library.swift"), string: """
public func Foo() { }
""")
// Check that a target doesn't include itself in its recursive dependencies.
do {
let result = try SwiftPMProduct.SwiftPackage.executeProcess(["print-target-dependencies", "--target", "SecondTarget"], packagePath: packageDir)
let output = try result.utf8Output() + result.utf8stderrOutput()
XCTAssertEqual(result.exitStatus, .terminated(code: 0), "output: \(output)")
XCTAssertMatch(output, .contains("Recursive dependencies of 'SecondTarget': [\"FirstTarget\"]"))
XCTAssertMatch(output, .contains("Module kind of 'SecondTarget': generic"))
}
// Check that targets are not included twice in recursive dependencies.
do {
let result = try SwiftPMProduct.SwiftPackage.executeProcess(["print-target-dependencies", "--target", "ThirdTarget"], packagePath: packageDir)
let output = try result.utf8Output() + result.utf8stderrOutput()
XCTAssertEqual(result.exitStatus, .terminated(code: 0), "output: \(output)")
XCTAssertMatch(output, .contains("Recursive dependencies of 'ThirdTarget': [\"FirstTarget\"]"))
XCTAssertMatch(output, .contains("Module kind of 'ThirdTarget': generic"))
}
// Check that product dependencies work in recursive dependencies.
do {
let result = try SwiftPMProduct.SwiftPackage.executeProcess(["print-target-dependencies", "--target", "FourthTarget"], packagePath: packageDir)
let output = try result.utf8Output() + result.utf8stderrOutput()
XCTAssertEqual(result.exitStatus, .terminated(code: 0), "output: \(output)")
XCTAssertMatch(output, .contains("Recursive dependencies of 'FourthTarget': [\"FirstTarget\", \"SecondTarget\", \"ThirdTarget\", \"HelperLibrary\"]"))
XCTAssertMatch(output, .contains("Module kind of 'FourthTarget': generic"))
}
// Check some of the other utility APIs.
do {
let result = try SwiftPMProduct.SwiftPackage.executeProcess(["print-target-dependencies", "--target", "FifthTarget"], packagePath: packageDir)
let output = try result.utf8Output() + result.utf8stderrOutput()
XCTAssertEqual(result.exitStatus, .terminated(code: 0), "output: \(output)")
XCTAssertMatch(output, .contains("execProducts: [\"FifthTarget\"]"))
XCTAssertMatch(output, .contains("swiftTargets: [\"ThirdTarget\", \"TestTarget\", \"SecondTarget\", \"FourthTarget\", \"FirstTarget\", \"FifthTarget\"]"))
XCTAssertMatch(output, .contains("swiftSources: [\"library.swift\", \"tests.swift\", \"library.swift\", \"library.swift\", \"library.swift\", \"main.swift\"]"))
XCTAssertMatch(output, .contains("Module kind of 'FifthTarget': executable"))
}
// Check a test target.
do {
let result = try SwiftPMProduct.SwiftPackage.executeProcess(["print-target-dependencies", "--target", "TestTarget"], packagePath: packageDir)
let output = try result.utf8Output() + result.utf8stderrOutput()
XCTAssertEqual(result.exitStatus, .terminated(code: 0), "output: \(output)")
XCTAssertMatch(output, .contains("Recursive dependencies of 'TestTarget': [\"FirstTarget\", \"SecondTarget\"]"))
XCTAssertMatch(output, .contains("Module kind of 'TestTarget': test"))
}
}
}
func testPluginCompilationBeforeBuilding() throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try testWithTemporaryDirectory { tmpPath in
// Create a sample package with a couple of plugins a other targets and products.
let packageDir = tmpPath.appending(components: "MyPackage")
try localFileSystem.createDirectory(packageDir, recursive: true)
try localFileSystem.writeFileContents(packageDir.appending(components: "Package.swift"), string: """
// swift-tools-version: 5.6
import PackageDescription
let package = Package(
name: "MyPackage",
products: [
.library(
name: "MyLibrary",
targets: ["MyLibrary"]
),
.executable(
name: "MyExecutable",
targets: ["MyExecutable"]
),
],
targets: [
.target(
name: "MyLibrary"
),
.executableTarget(
name: "MyExecutable",
dependencies: ["MyLibrary"]
),
.plugin(
name: "MyBuildToolPlugin",
capability: .buildTool()
),
.plugin(
name: "MyCommandPlugin",
capability: .command(
intent: .custom(verb: "my-build-tester", description: "Help description")
)
),
]
)
"""
)
let myLibraryTargetDir = packageDir.appending(components: "Sources", "MyLibrary")
try localFileSystem.createDirectory(myLibraryTargetDir, recursive: true)
try localFileSystem.writeFileContents(myLibraryTargetDir.appending(component: "library.swift"), string: """
public func GetGreeting() -> String { return "Hello" }
"""
)
let myExecutableTargetDir = packageDir.appending(components: "Sources", "MyExecutable")
try localFileSystem.createDirectory(myExecutableTargetDir, recursive: true)
try localFileSystem.writeFileContents(myExecutableTargetDir.appending(component: "main.swift"), string: """
import MyLibrary
print("\\(GetGreeting()), World!")
"""
)
let myBuildToolPluginTargetDir = packageDir.appending(components: "Plugins", "MyBuildToolPlugin")
try localFileSystem.createDirectory(myBuildToolPluginTargetDir, recursive: true)
try localFileSystem.writeFileContents(myBuildToolPluginTargetDir.appending(component: "plugin.swift"), string: """
import PackagePlugin
@main struct MyBuildToolPlugin: BuildToolPlugin {
func createBuildCommands(
context: PluginContext,
target: Target
) throws -> [Command] {
return []
}
}
"""
)
let myCommandPluginTargetDir = packageDir.appending(components: "Plugins", "MyCommandPlugin")
try localFileSystem.createDirectory(myCommandPluginTargetDir, recursive: true)
try localFileSystem.writeFileContents(myCommandPluginTargetDir.appending(component: "plugin.swift"), string: """
import PackagePlugin
@main struct MyCommandPlugin: CommandPlugin {
func performCommand(
context: PluginContext,
arguments: [String]
) throws {
}
}
"""
)
// Check that building without options compiles both plugins and that the build proceeds.
do {
let result = try SwiftPMProduct.SwiftBuild.executeProcess([], packagePath: packageDir)
let output = try result.utf8Output() + result.utf8stderrOutput()
XCTAssertEqual(result.exitStatus, .terminated(code: 0), "output: \(output)")
XCTAssertMatch(output, .contains("Compiling plugin MyBuildToolPlugin"))
XCTAssertMatch(output, .contains("Compiling plugin MyCommandPlugin"))
XCTAssertMatch(output, .contains("Building for debugging..."))
}
// Check that building just one of them just compiles that plugin and doesn't build anything else.
do {
let result = try SwiftPMProduct.SwiftBuild.executeProcess(["--target", "MyCommandPlugin"], packagePath: packageDir)
let output = try result.utf8Output() + result.utf8stderrOutput()
XCTAssertEqual(result.exitStatus, .terminated(code: 0), "output: \(output)")
XCTAssertNoMatch(output, .contains("Compiling plugin MyBuildToolPlugin"))
XCTAssertMatch(output, .contains("Compiling plugin MyCommandPlugin"))
XCTAssertNoMatch(output, .contains("Building for debugging..."))
}
// Deliberately break the command plugin.
try localFileSystem.writeFileContents(myCommandPluginTargetDir.appending(component: "plugin.swift"), string: """
import PackagePlugin
@main struct MyCommandPlugin: CommandPlugin {
func performCommand(
context: PluginContext,
arguments: [String]
) throws {
this is an error
}
}
"""
)
// Check that building stops after compiling the plugin and doesn't proceed.
// Run this test a number of times to try to catch any race conditions.
for _ in 1...5 {
let result = try SwiftPMProduct.SwiftBuild.executeProcess([], packagePath: packageDir)
let output = try result.utf8Output() + result.utf8stderrOutput()
XCTAssertNotEqual(result.exitStatus, .terminated(code: 0), "output: \(output)")
XCTAssertMatch(output, .contains("Compiling plugin MyBuildToolPlugin"))
XCTAssertMatch(output, .contains("Compiling plugin MyCommandPlugin"))
#if false // sometimes this line isn't emitted; being investigated in https://bugs.swift.org/browse/SR-15831
XCTAssertMatch(output, .contains("MyCommandPlugin/plugin.swift:7:19: error: consecutive statements on a line must be separated by ';'"))
#endif
XCTAssertNoMatch(output, .contains("Building for debugging..."))
}
}
}
func testSinglePluginTarget() throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try testWithTemporaryDirectory { tmpPath in
// Create a sample package with a library target and a plugin.
let packageDir = tmpPath.appending(components: "MyPackage")
try localFileSystem.createDirectory(packageDir, recursive: true)
try localFileSystem.writeFileContents(packageDir.appending(component: "Package.swift"), string: """
// swift-tools-version: 5.7
import PackageDescription
let package = Package(
name: "MyPackage",
products: [
.plugin(name: "Foo", targets: ["Foo"])
],
dependencies: [
],
targets: [
.plugin(
name: "Foo",
capability: .command(
intent: .custom(verb: "Foo", description: "Plugin example"),
permissions: []
)
)
]
)
""")
let myPluginTargetDir = packageDir.appending(components: "Plugins", "Foo")
try localFileSystem.createDirectory(myPluginTargetDir, recursive: true)
try localFileSystem.writeFileContents(myPluginTargetDir.appending(component: "plugin.swift"), string: """
import PackagePlugin
@main struct FooPlugin: BuildToolPlugin {
func createBuildCommands(
context: PluginContext,
target: Target
) throws -> [Command] { }
}
""")
// Load a workspace from the package.
let observability = ObservabilitySystem.makeForTesting()
let workspace = try Workspace(
fileSystem: localFileSystem,
forRootPackage: packageDir,
customManifestLoader: ManifestLoader(toolchain: UserToolchain.default),
delegate: MockWorkspaceDelegate()
)
// Load the root manifest.
let rootInput = PackageGraphRootInput(packages: [packageDir], dependencies: [])
let rootManifests = try tsc_await {
workspace.loadRootManifests(
packages: rootInput.packages,
observabilityScope: observability.topScope,
completion: $0
)
}
XCTAssert(rootManifests.count == 1, "\(rootManifests)")
// Load the package graph.
let _ = try workspace.loadPackageGraph(rootInput: rootInput, observabilityScope: observability.topScope)
XCTAssertNoDiagnostics(observability.diagnostics)
}
}
}
| apache-2.0 |
somedev/DribbbleAPI | Sources/DribbbleAPI/Models/DBTeam.swift | 1 | 2963 | //
// DBTeam.swift
// DribbbleAPI
//
// Created by Eduard Panasiuk on 11/6/16.
// Copyright © 2016 somedev. All rights reserved.
//
import Foundation
public struct DBTeam {
public let id: String
public let name: String
public let username: String
public let htmlURL: URL?
public let avatarUrl: URL?
public let bio: String
public let location: String
public let links: [DBLink]?
public let bucketsCount: UInt
public let commentsReceivedCount: UInt
public let followersCount: UInt
public let followingsCount: UInt
public let likesCount: UInt
public let likesReceived_count: UInt
public let projectsCount: UInt
public let reboundsReceivedCount: UInt
public let shotsСount: UInt
public let canUpload: Bool
public let type: String
public let isPro: Bool
public let created: Date
public let updated: Date
}
// MARK: - custom initializer
extension DBTeam {
public init?(dictionary: [String: Any] = [:]) {
guard let id: String = dictionary.JSONValueForKey("id") else {
return nil
}
self.id = id
name = dictionary.JSONValueForKey("name") ?? ""
username = dictionary.JSONValueForKey("username") ?? ""
avatarUrl = dictionary.JSONValueForKey("avatar_url")
htmlURL = dictionary.JSONValueForKey("html_url")
bio = dictionary.JSONValueForKey("bio") ?? ""
location = dictionary.JSONValueForKey("location") ?? ""
bucketsCount = dictionary.JSONValueForKey("buckets_count") ?? 0
commentsReceivedCount = dictionary.JSONValueForKey("comments_received_count") ?? 0
followersCount = dictionary.JSONValueForKey("followers_count") ?? 0
followingsCount = dictionary.JSONValueForKey("followings_count") ?? 0
likesCount = dictionary.JSONValueForKey("likes_count") ?? 0
likesReceived_count = dictionary.JSONValueForKey("likes_received_count") ?? 0
projectsCount = dictionary.JSONValueForKey("projects_count") ?? 0
reboundsReceivedCount = dictionary.JSONValueForKey("rebounds_received_count") ?? 0
shotsСount = dictionary.JSONValueForKey("shots_count") ?? 0
canUpload = dictionary.JSONValueForKey("can_upload_shot") ?? false
type = dictionary.JSONValueForKey("type") ?? ""
isPro = dictionary.JSONValueForKey("pro") ?? false
created = dictionary.JSONValueForKey("created_at") ?? Date()
updated = dictionary.JSONValueForKey("updated_at") ?? Date()
if let linksDict = dictionary["links"] as? [String: String] {
links = DBLink.links(from: linksDict)
} else {
links = nil
}
}
}
// MARK: - JSONValueType
extension DBTeam: JSONValueType {
public static func JSONValue(_ object: Any) -> DBTeam? {
guard let dict = object as? [String: Any],
let team = DBTeam(dictionary: dict) else { return nil }
return team
}
}
| mit |
Pluto-Y/SwiftyEcharts | SwiftyEchartsTest_iOS/ToolboxSpec.swift | 1 | 36917 | //
// ToolboxSpec.swift
// SwiftyEcharts
//
// Created by Pluto Y on 13/08/2017.
// Copyright © 2017 com.pluto-y. All rights reserved.
//
import Quick
import Nimble
@testable import SwiftyEcharts
class ToolboxSpec: QuickSpec {
override func spec() {
describe("For Toolbox.Feature.SaveAsImage.Type") {
let pngString = "png"
let jpegString = "jpeg"
let pngType = Toolbox.Feature.SaveAsImage.Type.png
let jpegType = Toolbox.Feature.SaveAsImage.Type.jpeg
it("needs to check the enum case jsonString") {
expect(pngType.jsonString).to(equal(pngString.jsonString))
expect(jpegType.jsonString).to(equal(jpegString.jsonString))
}
}
let colorIconStyleContentValue = Color.rgba(128, 128, 128, 0.3)
let borderColorIconStyleContentValue = Color.hexColor("#abcdef")
let borderWidthIconStyleContentValue: Float = 8.427
let borderTypeIconStyleContentValue = LineType.solid
let shadowBlurIconStyleContentValue: Float = 87234.23872
let shadowColorIconStyleContentValue = Color.array([Color.red, Color.hexColor("#2746ff"), Color.rgba(0, 0, 128, 0.77)])
let shadowOffsetXIconStyleContentValue: Float = 85.34874
let shadowOffsetYIconStyleContentValue: Float = 0.88873
let opacityIconStyleContentValue: Float = 0.74623
let textPositionIconStyleContentValue = Position.top
let textAlignIconStyleContentValue = Align.right
let iconStyleContent = Toolbox.IconStyleContent()
iconStyleContent.color = colorIconStyleContentValue
iconStyleContent.borderColor = borderColorIconStyleContentValue
iconStyleContent.borderWidth = borderWidthIconStyleContentValue
iconStyleContent.borderType = borderTypeIconStyleContentValue
iconStyleContent.shadowBlur = shadowBlurIconStyleContentValue
iconStyleContent.shadowColor = shadowColorIconStyleContentValue
iconStyleContent.shadowOffsetX = shadowOffsetXIconStyleContentValue
iconStyleContent.shadowOffsetY = shadowOffsetYIconStyleContentValue
iconStyleContent.opacity = opacityIconStyleContentValue
iconStyleContent.textPosition = textPositionIconStyleContentValue
iconStyleContent.textAlign = textAlignIconStyleContentValue
describe("For Toolbox.IconStyleContent") {
it("needs to check the jsonString") {
let resultDic: [String: Jsonable] = [
"color": colorIconStyleContentValue,
"borderColor": borderColorIconStyleContentValue,
"borderWidth": borderWidthIconStyleContentValue,
"borderType": borderTypeIconStyleContentValue,
"shadowBlur": shadowBlurIconStyleContentValue,
"shadowColor": shadowColorIconStyleContentValue,
"shadowOffsetX": shadowOffsetXIconStyleContentValue,
"shadowOffsetY": shadowOffsetYIconStyleContentValue,
"opacity": opacityIconStyleContentValue,
"textPosition": textPositionIconStyleContentValue,
"textAlign": textAlignIconStyleContentValue
]
expect(iconStyleContent.jsonString).to(equal(resultDic.jsonString))
}
it("needs to check the Enumable") {
let iconStyleContentByEnums = Toolbox.IconStyleContent(
.color(colorIconStyleContentValue),
.borderColor(borderColorIconStyleContentValue),
.borderWidth(borderWidthIconStyleContentValue),
.borderType(borderTypeIconStyleContentValue),
.shadowBlur(shadowBlurIconStyleContentValue),
.shadowColor(shadowColorIconStyleContentValue),
.shadowOffsetX(shadowOffsetXIconStyleContentValue),
.shadowOffsetY(shadowOffsetYIconStyleContentValue),
.opacity(opacityIconStyleContentValue),
.textPosition(textPositionIconStyleContentValue),
.textAlign(textAlignIconStyleContentValue)
)
expect(iconStyleContentByEnums.jsonString).to(equal(iconStyleContentByEnums.jsonString))
}
}
let normalIconStyleValue = iconStyleContent
let emphasisIconStyleValue = Toolbox.IconStyleContent(
.opacity(0.47623),
.color(Color.yellow),
.borderWidth(8745.28374),
.textAlign(Align.left),
.textPosition(Position.left)
)
let iconStyle = Toolbox.IconStyle()
iconStyle.normal = normalIconStyleValue
iconStyle.emphasis = emphasisIconStyleValue
describe("For IconStyle") {
it("needs to check the jsonString") {
let resultDic: [String: Jsonable] = [
"normal": normalIconStyleValue,
"emphasis": emphasisIconStyleValue
]
expect(iconStyle.jsonString).to(equal(resultDic.jsonString))
}
it("needs to check the Enumable") {
let iconStyleByEnums = Toolbox.IconStyle(
.normal(normalIconStyleValue),
.emphasis(emphasisIconStyleValue)
)
expect(iconStyleByEnums.jsonString).to(equal(iconStyle.jsonString))
}
}
let typeSaveAsImageValue = Toolbox.Feature.SaveAsImage.Type.jpeg
let nameSaveAsImageValue = "saveAsImageNameValue"
let backgroundColorSaveAsImageValue = Color.hexColor("#873abc")
let excludeComponentsSaveAsImageValue: [String] = ["excludeComponent1", "excludeComponent2"]
let showSaveAsImageValue = false
let titleSaveAsImageValue = "saveAsImageTitleValue"
let iconSaveAsImageValue = "saveAsImageIconValue"
let iconStyleSaveAsImageValue = iconStyle
let pixelRatioSaveAsImageValue: Float = 2
let saveAsImage = Toolbox.Feature.SaveAsImage()
saveAsImage.type = typeSaveAsImageValue
saveAsImage.name = nameSaveAsImageValue
saveAsImage.backgroundColor = backgroundColorSaveAsImageValue
saveAsImage.excludeComponents = excludeComponentsSaveAsImageValue
saveAsImage.show = showSaveAsImageValue
saveAsImage.title = titleSaveAsImageValue
saveAsImage.icon = iconSaveAsImageValue
saveAsImage.iconStyle = iconStyleSaveAsImageValue
saveAsImage.pixelRatio = pixelRatioSaveAsImageValue
describe("For Toolbox.Feature.SaveAsImage") {
it("needs to check the jsonString") {
let resultDic: [String: Jsonable] = [
"type": typeSaveAsImageValue,
"name": nameSaveAsImageValue,
"backgroundColor": backgroundColorSaveAsImageValue,
"excludeComponents": excludeComponentsSaveAsImageValue,
"show": showSaveAsImageValue,
"title": titleSaveAsImageValue,
"icon": iconSaveAsImageValue,
"iconStyle": iconStyleSaveAsImageValue,
"pixelRatio": pixelRatioSaveAsImageValue
]
expect(saveAsImage.jsonString).to(equal(resultDic.jsonString))
}
it("needs to check the Enumable") {
let saveAsImageByEnums = Toolbox.Feature.SaveAsImage(
.type(typeSaveAsImageValue),
.name(nameSaveAsImageValue),
.backgroundColor(backgroundColorSaveAsImageValue),
.excludeComponents(excludeComponentsSaveAsImageValue),
.show(showSaveAsImageValue),
.title(titleSaveAsImageValue),
.icon(iconSaveAsImageValue),
.iconStyle(iconStyleSaveAsImageValue),
.pixelRatio(pixelRatioSaveAsImageValue)
)
expect(saveAsImageByEnums.jsonString).to(equal(saveAsImage.jsonString))
}
}
let showRestoreValue = false
let titleRestoreValue = "restoreTitleValue"
let iconRestoreValue = "restoreIconValue"
let iconStyleRestoreValue = Toolbox.IconStyle(
.emphasis(Toolbox.IconStyleContent(
.color(Color.hexColor("#77fba7")),
.textPosition(Position.top),
.shadowBlur(7.2736)
))
)
let restore = Toolbox.Feature.Restore()
restore.show = showRestoreValue
restore.title = titleRestoreValue
restore.icon = iconRestoreValue
restore.iconStyle = iconStyleRestoreValue
describe("For Toolbox.Feature.Restore") {
it("needs to check the jsonString") {
let resultDic: [String: Jsonable] = [
"show": showRestoreValue,
"title": titleRestoreValue,
"icon": iconRestoreValue,
"iconStyle": iconStyleRestoreValue
]
expect(restore.jsonString).to(equal(resultDic.jsonString))
}
it("needs to check the Enumable") {
let restoreByEnums = Toolbox.Feature.Restore(
.show(showRestoreValue),
.title(titleRestoreValue),
.icon(iconRestoreValue),
.iconStyle(iconStyleRestoreValue)
)
expect(restoreByEnums.jsonString).to(equal(restore.jsonString))
}
}
let showDataViewValue = true
let titleDataViewValue = "dataViewTitleValue"
let iconDataViewValue = "dataViewIconValue"
let iconStyleDataViewValue = Toolbox.IconStyle(
.normal(Toolbox.IconStyleContent(
.borderWidth(0.00001),
.opacity(0.99999999),
.shadowOffsetY(100.01),
.shadowOffsetX(999.0001)
))
)
let readOnlyDataViewValue = false
let langDataViewValue: [String] = ["数据视图", "关闭", "刷新"]
let backgroundColorDataViewValue = Color.array([Color.hexColor("#123abc"), Color.red, rgba(200, 19, 67, 0.888888)])
let textareaColorDataViewValue = Color.hexColor("#667788")
let textareaBorderColorDataViewValue = Color.rgb(99, 100, 101)
let textColorDataViewValue = Color.red
let buttonColorDataViewValue = Color.auto
let buttonTextColorDataViewValue = rgba(0, 0, 0, 0)
let dataView = Toolbox.Feature.DataView()
dataView.show = showDataViewValue
dataView.title = titleDataViewValue
dataView.icon = iconDataViewValue
dataView.iconStyle = iconStyleDataViewValue
dataView.readOnly = readOnlyDataViewValue
dataView.lang = langDataViewValue
dataView.backgroundColor = backgroundColorDataViewValue
dataView.textareaColor = textareaColorDataViewValue
dataView.textareaBorderColor = textareaBorderColorDataViewValue
dataView.textColor = textColorDataViewValue
dataView.buttonColor = buttonColorDataViewValue
dataView.buttonTextColor = buttonTextColorDataViewValue
describe("For ToolboxFeature.DataView") {
it("needs to check the jsonString") {
let resultDic: [String: Jsonable] = [
"show": showDataViewValue,
"title": titleDataViewValue,
"icon": iconDataViewValue,
"iconStyle": iconStyleDataViewValue,
"readOnly": readOnlyDataViewValue,
"lang": langDataViewValue,
"backgroundColor": backgroundColorDataViewValue,
"textareaColor": textareaColorDataViewValue,
"textareaBorderColor": textareaBorderColorDataViewValue,
"textColor": textColorDataViewValue,
"buttonColor": buttonColorDataViewValue,
"buttonTextColor": buttonTextColorDataViewValue
]
expect(dataView.jsonString).to(equal(resultDic.jsonString))
}
it("needs to check the Enumable") {
let dataViewByEnums = Toolbox.Feature.DataView(
.show(showDataViewValue),
.title(titleDataViewValue),
.icon(iconDataViewValue),
.iconStyle(iconStyleDataViewValue),
.readOnly(readOnlyDataViewValue),
.lang(langDataViewValue),
.backgroundColor(backgroundColorDataViewValue),
.textareaColor(textareaColorDataViewValue),
.textareaBorderColor(textareaBorderColorDataViewValue),
.textColor(textColorDataViewValue),
.buttonColor(buttonColorDataViewValue),
.buttonTextColor(buttonTextColorDataViewValue)
)
expect(dataViewByEnums.jsonString).to(equal(dataView.jsonString))
}
}
describe("For Toolbox.Feature.DataZoom.AxisIndexSelector") {
let trueValue = true
let falseValue = false
let allString = "all"
let noneString = "none"
let intValue: UInt = UInt.max
let arrayValue: [UInt] = [UInt.min, 0, 255, 8, 89]
let trueAxisIndexSelector = Toolbox.Feature.DataZoom.AxisIndexSelector.bool(trueValue)
let falseAxisIndexSelector = Toolbox.Feature.DataZoom.AxisIndexSelector.bool(falseValue)
let intAxisIndexSelector = Toolbox.Feature.DataZoom.AxisIndexSelector.int(intValue)
let arrayAxisIndexSelector = Toolbox.Feature.DataZoom.AxisIndexSelector.array(arrayValue)
it("needs to check the enum case jsonString") {
expect(trueAxisIndexSelector.jsonString).to(equal(allString.jsonString))
expect(falseAxisIndexSelector.jsonString).to(equal(noneString.jsonString))
expect(intAxisIndexSelector.jsonString).to(equal(intValue.jsonString))
expect(arrayAxisIndexSelector.jsonString).to(equal(arrayValue.jsonString))
}
it("needs to check the ExpressibleByBooleanLiteral, ExpressibleByIntegerLiteral, ExpressibleByArrayLiteral") {
let trueLiteral: Toolbox.Feature.DataZoom.AxisIndexSelector = true
let falseLiteral: Toolbox.Feature.DataZoom.AxisIndexSelector = false
let intLiteral: Toolbox.Feature.DataZoom.AxisIndexSelector = 18446744073709551615
let arrayLiteral: Toolbox.Feature.DataZoom.AxisIndexSelector = [UInt.min, UInt(0), UInt(255), UInt(8), UInt(89)]
expect(trueLiteral.jsonString).to(equal(trueAxisIndexSelector.jsonString))
expect(falseLiteral.jsonString).to(equal(falseAxisIndexSelector.jsonString))
expect(intLiteral.jsonString).to(equal(intAxisIndexSelector.jsonString))
expect(arrayLiteral.jsonString).to(equal(arrayAxisIndexSelector.jsonString))
}
}
let zoomTitleValue = "dataZoomTitleZoomValue"
let backTitleValue = "dataZoomTitleBackValue"
let title = Toolbox.Feature.DataZoom.Title()
title.zoom = zoomTitleValue
title.back = backTitleValue
describe("For Toolbox.Feature.DataZoom.Title") {
it("needs to check the jsonString") {
let resultDic: [String: Jsonable] = [
"zoom": zoomTitleValue,
"back": backTitleValue
]
expect(title.jsonString).to(equal(resultDic.jsonString))
}
it("needs to check the Enumable") {
let titleByEnums = Toolbox.Feature.DataZoom.Title(
.zoom(zoomTitleValue),
.back(backTitleValue)
)
expect(titleByEnums.jsonString).to(equal(title.jsonString))
}
}
let zoomIconValue = "dataZoomIconZoomValue"
let backIconValue = "dataZoomIconBackValue"
let icon = Toolbox.Feature.DataZoom.Icon()
icon.zoom = zoomIconValue
icon.back = backIconValue
describe("For Toolbox.Feature.DataZoom.Icon") {
it("needs to check the jsonString") {
let resultDic: [String: Jsonable] = [
"zoom": zoomIconValue,
"back": backIconValue
]
expect(icon.jsonString).to(equal(resultDic.jsonString))
}
it("needs to check the Enumable") {
let iconByEnums = Toolbox.Feature.DataZoom.Icon(
.zoom(zoomIconValue),
.back(backIconValue)
)
expect(iconByEnums.jsonString).to(equal(icon.jsonString))
}
}
let showDataZoomValue = false
let titleDataZoomValue = title
let iconDataZoomValue = icon
let iconStyleDataZoomValue = Toolbox.IconStyle(
.emphasis(Toolbox.IconStyleContent(
.opacity(0.576),
.color(Color.auto),
.borderType(LineType.dashed)
))
)
let xAxisIndexDataZoomValue = Toolbox.Feature.DataZoom.AxisIndexSelector.bool(false)
let yAxisIndexDataZoomValue = Toolbox.Feature.DataZoom.AxisIndexSelector.int(77)
let dataZoom = Toolbox.Feature.DataZoom()
dataZoom.show = showDataZoomValue
dataZoom.title = titleDataZoomValue
dataZoom.icon = iconDataZoomValue
dataZoom.iconStyle = iconStyleDataZoomValue
dataZoom.xAxisIndex = xAxisIndexDataZoomValue
dataZoom.yAxisIndex = yAxisIndexDataZoomValue
describe("For Toolbox.Feature.DataZoom") {
it("needs to check the jsonString") {
let resultDic: [String: Jsonable] = [
"show": showDataZoomValue,
"title": titleDataZoomValue,
"icon": iconDataZoomValue,
"iconStyle": iconStyleDataZoomValue,
"xAxisIndex": xAxisIndexDataZoomValue,
"yAxisIndex": yAxisIndexDataZoomValue
]
expect(dataZoom.jsonString).to(equal(resultDic.jsonString))
}
it("needs to check the Enumable") {
let dataZoomByEnums = Toolbox.Feature.DataZoom(
.show(showDataZoomValue),
.title(titleDataZoomValue),
.icon(iconDataZoomValue),
.iconStyle(iconStyleDataZoomValue),
.xAxisIndex(xAxisIndexDataZoomValue),
.yAxisIndex(yAxisIndexDataZoomValue)
)
expect(dataZoomByEnums.jsonString).to(equal(dataZoom.jsonString))
}
}
describe("For Toolbox.Feature.MagicType.Type") {
let lineString = "line"
let barString = "bar"
let stackString = "stack"
let tiledString = "tiled"
let lineType = Toolbox.Feature.MagicType.Type.line
let barType = Toolbox.Feature.MagicType.Type.bar
let stackType = Toolbox.Feature.MagicType.Type.stack
let tiledType = Toolbox.Feature.MagicType.Type.tiled
it("needs to check the enum case jsonString") {
expect(lineType.jsonString).to(equal(lineString.jsonString))
expect(barType.jsonString).to(equal(barString.jsonString))
expect(stackType.jsonString).to(equal(stackString.jsonString))
expect(tiledType.jsonString).to(equal(tiledString.jsonString))
}
}
let lineTitleValue = "magicTypeTitleLineValue"
let barTitleValue = "magicTypeTitleBarValue"
let stackTitleValue = "magicTypeTitleStatckValue"
let tiledTitleValue = "magicTypeTitleTiledValue"
let magicTypeTitle = Toolbox.Feature.MagicType.Title()
magicTypeTitle.line = lineTitleValue
magicTypeTitle.bar = barTitleValue
magicTypeTitle.stack = stackTitleValue
magicTypeTitle.tiled = tiledTitleValue
describe("For Toolbox.Feature.MagicType.Title") {
it("needs to check the jsonString") {
let resultDic: [String: Jsonable] = [
"line": lineTitleValue,
"bar": barTitleValue,
"stack": stackTitleValue,
"tiled": tiledTitleValue
]
expect(magicTypeTitle.jsonString).to(equal(resultDic.jsonString))
}
it("needs to check the Enumable") {
let magicTypeTitleByEnums = Toolbox.Feature.MagicType.Title(
.line(lineTitleValue),
.bar(barTitleValue),
.stack(stackTitleValue),
.tiled(tiledTitleValue)
)
expect(magicTypeTitleByEnums.jsonString).to(equal(magicTypeTitle.jsonString))
}
}
let lineIconValue = "magicTypeIconLineValue"
let barIconValue = "magicTypeIconBarValue"
let stackIconValue = "magicTypeIconStatckValue"
let tiledIconValue = "magicTypeIconTiledValue"
let magicTypeIcon = Toolbox.Feature.MagicType.Icon()
magicTypeIcon.line = lineIconValue
magicTypeIcon.bar = barIconValue
magicTypeIcon.stack = stackIconValue
magicTypeIcon.tiled = tiledIconValue
describe("For Toolbox.Feature.MagicType.Icon") {
it("needs to check the jsonString") {
let resultDic: [String: Jsonable] = [
"line": lineIconValue,
"bar": barIconValue,
"stack": stackIconValue,
"tiled": tiledIconValue
]
expect(magicTypeIcon.jsonString).to(equal(resultDic.jsonString))
}
it("needs to check the Enumable") {
let magicTypeIconByEnums = Toolbox.Feature.MagicType.Icon(
.line(lineIconValue),
.bar(barIconValue),
.stack(stackIconValue),
.tiled(tiledIconValue)
)
expect(magicTypeIconByEnums.jsonString).to(equal(magicTypeIcon.jsonString))
}
}
let showMagicTypeValue = true
let typeMagicTypeValue = [Toolbox.Feature.MagicType.Type.line, Toolbox.Feature.MagicType.Type.bar, Toolbox.Feature.MagicType.Type.stack, Toolbox.Feature.MagicType.Type.tiled]
let titleMagicTypeValue = magicTypeTitle
let iconMaigcTypeValue = magicTypeIcon
let magicType = Toolbox.Feature.MagicType()
magicType.show = showMagicTypeValue
magicType.type = typeMagicTypeValue
magicType.title = titleMagicTypeValue
magicType.icon = iconMaigcTypeValue
describe("For Toolbox.Feature.MagicType") {
it("needs to check the jsonString") {
let resultDic: [String: Jsonable] = [
"show": showMagicTypeValue,
"type": typeMagicTypeValue,
"title": titleMagicTypeValue,
"icon": iconMaigcTypeValue
]
expect(magicType.jsonString).to(equal(resultDic.jsonString))
}
it("needs to check the Enumable") {
let magicTypeByEnums = Toolbox.Feature.MagicType(
.show(showMagicTypeValue),
.type(typeMagicTypeValue),
.title(titleMagicTypeValue),
.icon(iconMaigcTypeValue)
)
expect(magicTypeByEnums.jsonString).to(equal(magicType.jsonString))
}
}
describe("For Toolbox.Feature.Brush.Type") {
let rectString = "rect"
let polygonString = "polygon"
let lineXString = "lineX"
let lineYString = "lineY"
let keepString = "keep"
let clearString = "clear"
let rectBrush = Toolbox.Feature.Brush.Type.rect
let polygonBrush = Toolbox.Feature.Brush.Type.polygon
let lineXBrush = Toolbox.Feature.Brush.Type.lineX
let lineYBrush = Toolbox.Feature.Brush.Type.lineY
let keepBrush = Toolbox.Feature.Brush.Type.keep
let clearBrush = Toolbox.Feature.Brush.Type.clear
it("needs to check enum case jsonString") {
expect(rectBrush.jsonString).to(equal(rectString.jsonString))
expect(polygonBrush.jsonString).to(equal(polygonString.jsonString))
expect(lineXBrush.jsonString).to(equal(lineXString.jsonString))
expect(lineYBrush.jsonString).to(equal(lineYString.jsonString))
expect(keepBrush.jsonString).to(equal(keepString.jsonString))
expect(clearBrush.jsonString).to(equal(clearString.jsonString))
}
}
let rectBrushIconValue = "brushIconRectValue"
let polygonBrushIconValue = "brushIconPolygonValue"
let lineXBrushIconValue = "brushIconLineXValue"
let lineYBrushIconValue = "brushIconLineYValue"
let keepBrushIconValue = "brushIconKeepValue"
let clearBrushIconValue = "brushIconClearValue"
let brushIcon = Toolbox.Feature.Brush.Icon()
brushIcon.rect = rectBrushIconValue
brushIcon.polygon = polygonBrushIconValue
brushIcon.lineX = lineXBrushIconValue
brushIcon.lineY = lineYBrushIconValue
brushIcon.keep = keepBrushIconValue
brushIcon.clear = clearBrushIconValue
describe("For Toolbox.Feature.Brush.Icon") {
it("needs to check the jsonString") {
let resultDic: [String: Jsonable] = [
"rect": rectBrushIconValue,
"polygon": polygonBrushIconValue,
"lineX": lineXBrushIconValue,
"lineY": lineYBrushIconValue,
"keep": keepBrushIconValue,
"clear": clearBrushIconValue
]
expect(brushIcon.jsonString).to(equal(resultDic.jsonString))
}
it("needs to check the Enumable") {
let brushIconByEnums = Toolbox.Feature.Brush.Icon(
.rect(rectBrushIconValue),
.polygon(polygonBrushIconValue),
.lineX(lineXBrushIconValue),
.lineY(lineYBrushIconValue),
.keep(keepBrushIconValue),
.clear(clearBrushIconValue)
)
expect(brushIconByEnums.jsonString).to(equal(brushIcon.jsonString))
}
}
let rectBrushTitleValue = "brushTitleRectValue"
let polygonBrushTitleValue = "brushTitlePolygonValue"
let lineXBrushTitleValue = "brushTitleLineXValue"
let lineYBrushTitleValue = "brushTitleLineYValue"
let keepBrushTitleValue = "brushTitleKeepValue"
let clearBrushTitleValue = "brushTitleClearValue"
let brushTitle = Toolbox.Feature.Brush.Title()
brushTitle.rect = rectBrushTitleValue
brushTitle.polygon = polygonBrushTitleValue
brushTitle.lineX = lineXBrushTitleValue
brushTitle.lineY = lineYBrushTitleValue
brushTitle.keep = keepBrushTitleValue
brushTitle.clear = clearBrushTitleValue
describe("For Toolbox.Feature.Brush.Title") {
it("needs to check the jsonString") {
let resultDic: [String: Jsonable] = [
"rect": rectBrushTitleValue,
"polygon": polygonBrushTitleValue,
"lineX": lineXBrushTitleValue,
"lineY": lineYBrushTitleValue,
"keep": keepBrushTitleValue,
"clear": clearBrushTitleValue
]
expect(brushTitle.jsonString).to(equal(resultDic.jsonString))
}
it("needs to check the Enumable") {
let brushTitleByEnums = Toolbox.Feature.Brush.Title(
.rect(rectBrushTitleValue),
.polygon(polygonBrushTitleValue),
.lineX(lineXBrushTitleValue),
.lineY(lineYBrushTitleValue),
.keep(keepBrushTitleValue),
.clear(clearBrushTitleValue)
)
expect(brushTitleByEnums.jsonString).to(equal(brushTitle.jsonString))
}
}
let typeBrushValue = [Toolbox.Feature.Brush.Type.rect, Toolbox.Feature.Brush.Type.polygon, Toolbox.Feature.Brush.Type.lineX, Toolbox.Feature.Brush.Type.lineY, Toolbox.Feature.Brush.Type.keep, Toolbox.Feature.Brush.Type.clear]
let iconBrushValue = brushIcon
let titleBrushValue = brushTitle
let brush = Toolbox.Feature.Brush()
brush.type = typeBrushValue
brush.icon = iconBrushValue
brush.title = titleBrushValue
describe("For Toolbox.Feature.Brush") {
it("needs to check the jsonString") {
let resultDic: [String: Jsonable] = [
"type": typeBrushValue,
"icon": iconBrushValue,
"title": titleBrushValue
]
expect(brush.jsonString).to(equal(resultDic.jsonString))
}
it("needs to check the Enumable") {
let brushByEnums = Toolbox.Feature.Brush(
.type(typeBrushValue),
.icon(iconBrushValue),
.title(titleBrushValue)
)
expect(brushByEnums.jsonString).to(equal(brush.jsonString))
}
}
let saveAsImageFeatureValue = saveAsImage
let restoreFeatureValue = restore
let dataViewFeatureValue = dataView
let dataZoomFeatureValue = dataZoom
let magicTypeFeatureValue = magicType
let brushFeatureValue = brush
let feature = Toolbox.Feature()
feature.saveAsImage = saveAsImageFeatureValue
feature.restore = restoreFeatureValue
feature.dataView = dataViewFeatureValue
feature.dataZoom = dataZoomFeatureValue
feature.magicType = magicTypeFeatureValue
feature.brush = brushFeatureValue
describe("For Toolbox.Feature") {
it("needs to check the jsonString") {
let resultDic: [String: Jsonable] = [
"saveAsImage": saveAsImageFeatureValue,
"restore": restoreFeatureValue,
"dataView": dataViewFeatureValue,
"dataZoom": dataZoomFeatureValue,
"magicType": magicTypeFeatureValue,
"brush": brushFeatureValue
]
expect(feature.jsonString).to(equal(resultDic.jsonString))
}
it("needs to check the Enumable") {
let featureByEnums = Toolbox.Feature(
.saveAsImage(saveAsImageFeatureValue),
.restore(restoreFeatureValue),
.dataView(dataViewFeatureValue),
.dataZoom(dataZoomFeatureValue),
.magicType(magicTypeFeatureValue),
.brush(brushFeatureValue)
)
expect(featureByEnums.jsonString).to(equal(feature.jsonString))
}
}
describe("For Toolbox") {
let showValue = false
let orientValue = Orient.vertical
let itemSizeValue: Float = 0.57236
let itemGapValue: Float = 85.347
let showTitleValue = true
let featureValue = feature
let iconStyleValue = Toolbox.IconStyle()
let zlevelValue: Float = 10
let zValue: Float = -1
let leftValue = Position.right
let rightValue = Position.left
let topValue = Position.bottom
let bottomValue = Position.top
let widthValue: Float = 100
let heightValue: Float = 8.34764
let toolbox = Toolbox()
toolbox.show = showValue
toolbox.orient = orientValue
toolbox.itemSize = itemSizeValue
toolbox.itemGap = itemGapValue
toolbox.showTitle = showTitleValue
toolbox.feature = featureValue
toolbox.iconStyle = iconStyleValue
toolbox.zlevel = zlevelValue
toolbox.z = zValue
toolbox.left = leftValue
toolbox.top = topValue
toolbox.right = rightValue
toolbox.bottom = bottomValue
toolbox.width = widthValue
toolbox.height = heightValue
it("needs to check the jsonString") {
let resultDic: [String: Jsonable] = [
"show": showValue,
"orient": orientValue,
"itemSize": itemSizeValue,
"itemGap": itemGapValue,
"showTitle": showTitleValue,
"feature": featureValue,
"iconStyle": iconStyleValue,
"zlevel": zlevelValue,
"z": zValue,
"left": leftValue,
"top": topValue,
"right": rightValue,
"bottom": bottomValue,
"width": widthValue,
"height": heightValue
]
expect(toolbox.jsonString).to(equal(resultDic.jsonString))
}
it("needs to check the Enumable") {
let toolboxByEnums = Toolbox(
.show(showValue),
.orient(orientValue),
.itemSize(itemSizeValue),
.itemGap(itemGapValue),
.showTitle(showTitleValue),
.feature(featureValue),
.iconStyle(iconStyleValue),
.zlevel(zlevelValue),
.z(zValue),
.left(leftValue),
.top(topValue),
.right(rightValue),
.bottom(bottomValue),
.width(widthValue),
.height(heightValue)
)
expect(toolboxByEnums.jsonString).to(equal(toolbox.jsonString))
}
}
context("For the action of Toolbox") {
describe("For ToolboxRestoreAction") {
let typeValue = EchartsActionType.restore
let restoreAction = ToolboxRestoreAction()
it("needs to check the typeValue") {
expect(restoreAction.type.jsonString).to(equal(typeValue.jsonString))
}
it("needs to check the jsonString") {
let resultDic: [String: Jsonable] = [
"type": typeValue
]
expect(restoreAction.jsonString).to(equal(resultDic.jsonString))
}
}
}
}
}
| mit |
KazmaStudio/Feeding | CODE/iOS/Feeding/Feeding/ArticleListModel.swift | 1 | 668 | //
// ArticleListModel.swift
// Feeding
//
// Created by zhaochenjun on 2017/5/8.
// Copyright © 2017年 com.kazmastudio. All rights reserved.
//
import Foundation
class ArticleListModel: NSObject {
var articleType: String = CELL_ARTICLE_LIST_TYPE_A
var imageList: Array<String> = []
var title: String = STRING_EMPTY
var authorInfo: AuthorInfoModel = AuthorInfoModel()
var targeted = false
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
override init() {
super.init()
}
init(dict: [String: AnyObject]) {
super.init()
self.setValuesForKeys(dict)
}
}
| mit |
attackFromCat/LivingTVDemo | LivingTVDemo/LivingTVDemo/Classes/Home/Controller/GameViewController.swift | 1 | 4966 | //
// GameViewController.swift
// LivingTVDemo
//
// Created by 李翔 on 2017/1/9.
// Copyright © 2017年 Lee Xiang. All rights reserved.
//
import UIKit
private let kEdgeMargin : CGFloat = 10
private let kItemW : CGFloat = (kScreenW - 2 * kEdgeMargin) / 3
private let kItemH : CGFloat = kItemW * 6 / 5
private let kHeaderViewH : CGFloat = 50
private let kGameViewH : CGFloat = 90
private let kGameCellID = "kGameCellID"
private let kHeaderViewID = "kHeaderViewID"
class GameViewController: LoadingViewController {
// MARK: 懒加载属性
fileprivate lazy var gameVM : GameViewModel = GameViewModel()
fileprivate lazy var collectionView : UICollectionView = {[unowned self] in
// 1.创建布局
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kItemW, height: kItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.sectionInset = UIEdgeInsets(top: 0, left: kEdgeMargin, bottom: 0, right: kEdgeMargin)
layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH)
// 2.创建UICollectionView
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
collectionView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID)
collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
collectionView.dataSource = self
return collectionView
}()
fileprivate lazy var topHeaderView : CollectionHeaderView = {
let headerView = CollectionHeaderView.collectionHeaderView()
headerView.frame = CGRect(x: 0, y: -(kHeaderViewH + kGameViewH), width: kScreenW, height: kHeaderViewH)
headerView.iconImageView.image = UIImage(named: "Img_orange")
headerView.titleLabel.text = "常见"
headerView.moreBtn.isHidden = true
return headerView
}()
fileprivate lazy var gameView : RecommendGameView = {
let gameView = RecommendGameView.recommendGameView()
gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenW, height: kGameViewH)
return gameView
}()
// MARK: 系统回调
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadData()
}
}
// MARK:- 设置UI界面
extension GameViewController {
override func setupUI() {
// 0.给ContentView进行赋值
contentView = collectionView
// 1.添加UICollectionView
view.addSubview(collectionView)
// 2.添加顶部的HeaderView
collectionView.addSubview(topHeaderView)
// 3.将常用游戏的View,添加到collectionView中
collectionView.addSubview(gameView)
// 设置collectionView的内边距
collectionView.contentInset = UIEdgeInsets(top: kHeaderViewH + kGameViewH, left: 0, bottom: 0, right: 0)
super.setupUI()
}
}
// MARK:- 请求数据
extension GameViewController {
fileprivate func loadData() {
gameVM.loadAllGameData {
// 1.展示全部游戏
self.collectionView.reloadData()
// 2.展示常用游戏
self.gameView.groups = Array(self.gameVM.games[0..<10])
// 3.数据请求完成
self.loadDataFinished()
}
}
}
// MARK:- 遵守UICollectionView的数据源&代理
extension GameViewController : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return gameVM.games.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// 1.获取cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionGameCell
cell.baseGame = gameVM.games[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
// 1.取出HeaderView
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView
// 2.给HeaderView设置属性
headerView.titleLabel.text = "全部"
headerView.iconImageView.image = UIImage(named: "Img_orange")
headerView.moreBtn.isHidden = true
return headerView
}
}
| mit |
remobjects/ElementsSamples | Silver/All/SharedUI/SharedUI.Shared/AppDelegate.swift | 1 | 276 | class AppDelegate {
public private(set) var mainWindowController: MainWindowController!
public func start() {
//
// this is the cross-platform entry point for the app
//
mainWindowController = MainWindowController()
mainWindowController.showWindow(nil)
}
} | mit |
apple/swift-corelibs-foundation | Darwin/Foundation-swiftoverlay/NSPredicate.swift | 1 | 856 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 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
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
extension NSPredicate {
// + (NSPredicate *)predicateWithFormat:(NSString *)predicateFormat, ...;
public
convenience init(format predicateFormat: __shared String, _ args: CVarArg...) {
let va_args = getVaList(args)
self.init(format: predicateFormat, arguments: va_args)
}
}
| apache-2.0 |
h-n-y/BigNerdRanch-SwiftProgramming | chapter-26/silver-challenge/VocalTextEdit/VocalTextEdit/Document.swift | 1 | 1840 | //
// Document.swift
// VocalTextEdit
//
// Created by Hans Yelek on 1/28/16.
// Copyright © 2016 Hans Yelek. All rights reserved.
//
import Cocoa
class Document: NSDocument {
var contents: String = ""
override class func autosavesInPlace() -> Bool {
return true
}
override func makeWindowControllers() {
// Returns the Storyboard that contains your Document window.
let storyboard = NSStoryboard(name: "Main", bundle: nil)
let windowController = storyboard.instantiateControllerWithIdentifier("Document Window Controller") as! NSWindowController
let viewController = windowController.contentViewController as! ViewController
viewController.contents = contents
self.addWindowController(windowController)
}
override func dataOfType(typeName: String) throws -> NSData {
let windowController = windowControllers[0]
let viewController = windowController.contentViewController as! ViewController
let contents = viewController.contents ?? ""
if let data = contents.dataUsingEncoding(NSUTF8StringEncoding) {
return data
} else {
let userInfo = [NSLocalizedRecoverySuggestionErrorKey: "File cannot be encoded in UTF-8."]
throw NSError(domain: "com.hny.VocalTextEdit", code: 0, userInfo: userInfo)
}
}
override func readFromData(data: NSData, ofType typeName: String) throws {
if let contents = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
self.contents = contents
} else {
let userInfo = [NSLocalizedRecoverySuggestionErrorKey: "File is not valid UTF-8."]
throw NSError(domain: "com.hny.VocalTextEdit", code: 0, userInfo: userInfo)
}
}
}
| mit |
anzfactory/TwitterClientCLI | Sources/TwitterClientCore/APIType/SearchTweetType.swift | 1 | 1031 | //
// SearchTweetType.swift
// Spectre
//
// Created by shingo asato on 2017/09/21.
//
import Foundation
import APIKit
struct SearchTweetType: TwitterAPIType {
typealias Response = SearchTweets
var oauth: TwitterOAuth
var q: String
var count: Int = 30
var sinceId: Int?
var maxId: Int?
var method: HTTPMethod {
return .get
}
var path: String {
return "/1.1/search/tweets.json"
}
var parameters: Any? {
var params: [String: Any] = ["q": self.q, "count": self.count]
if let sinceId = self.sinceId, sinceId > 0 {
params["since_id"] = sinceId
}
if let maxId = self.maxId, maxId > 0 {
params["max_id"] = maxId
}
return params
}
var queryParameters: [String : Any]? {
return self.parameters as? [String: Any]
}
func response(from object: Any, urlResponse: HTTPURLResponse) throws -> SearchTweets {
return try SearchTweets(object)
}
}
| mit |
bitserf/OAuth2 | OAuth2/Array+Extensions.swift | 1 | 1211 | //
// OAuth2
// Copyright (C) 2015 Leon Breedt
//
// 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.
//
extension Array {
/// Converts this array to a dictionary of type `[K: V]`, by calling a transform function to
/// obtain a key and a value from an array element.
/// - Parameters:
/// - transform: A function that will transform an array element of type `Element` into
/// a `(K, V)` tuple.
/// - Returns: The resulting dictionary.
func toDictionary<K, V>(transform: Element -> (K, V)) -> [K: V] {
var dict: [K: V] = [:]
for item in self {
let (key, value) = transform(item)
dict[key] = value
}
return dict
}
}
| apache-2.0 |
hughbe/ui-components | src/Bordered/SideBorderedView.swift | 1 | 1231 | //
// SideBorderedView.swift
// UIComponents
//
// Created by Hugh Bellamy on 14/06/2015.
// Copyright (c) 2015 Hugh Bellamy. All rights reserved.
//
@IBDesignable
public class SideBorderedView: UIView {
@IBInspectable public var borderWidth: CGFloat = 0
@IBInspectable public var borderColor: UIColor = UIColor.blackColor()
@IBInspectable public var showsTopBorder: Bool = false
@IBInspectable public var showsBottomBorder: Bool = false
@IBInspectable public var showsLeftBorder: Bool = false
@IBInspectable public var showsRightBorder: Bool = false
public override func awakeFromNib() {
super.awakeFromNib()
if (showsTopBorder || showsBottomBorder || showsLeftBorder || showsRightBorder) && borderWidth == 0 {
borderWidth = 1
}
if showsTopBorder {
addTopBorder(borderWidth, color: borderColor)
}
if showsBottomBorder {
addBottomBorder(borderWidth, color: borderColor)
}
if showsLeftBorder {
addLeftBorder(borderWidth, color: borderColor)
}
if showsRightBorder {
addRightBorder(borderWidth, color: borderColor)
}
}
}
| mit |
ArtSabintsev/Siren | Sources/Extensions/UserDefaultsExtension.swift | 1 | 1482 | //
// UserDefaultsExtension.swift
// Siren
//
// Created by Arthur Sabintsev on 9/25/18.
// Copyright © 2018 Sabintsev iOS Projects. All rights reserved.
//
import Foundation
// `UserDefaults` Extension for Siren.
extension UserDefaults {
/// Siren-specific `UserDefaults` Keys
private enum SirenKeys: String {
/// Key that notifies Siren to perform a version check and present
/// the Siren alert the next time the user launches the app.
case PerformVersionCheckOnSubsequentLaunch
/// Key that stores the timestamp of the last version check.
case StoredVersionCheckDate
/// Key that stores the version that a user decided to skip.
case StoredSkippedVersion
}
/// Sets and Gets a `UserDefault` around storing a version that the user wants to skip updating.
static var storedSkippedVersion: String? {
get {
return standard.string(forKey: SirenKeys.StoredSkippedVersion.rawValue)
} set {
standard.set(newValue, forKey: SirenKeys.StoredSkippedVersion.rawValue)
}
}
/// Sets and Gets a `UserDefault` around the last time the user was presented a version update alert.
static var alertPresentationDate: Date? {
get {
return standard.object(forKey: SirenKeys.StoredVersionCheckDate.rawValue) as? Date
} set {
standard.set(newValue, forKey: SirenKeys.StoredVersionCheckDate.rawValue)
}
}
}
| mit |
CMP-Studio/TheWarholOutLoud | ios/CMSBeaconManager.swift | 2 | 5951 | //
// CMSBeaconManager.swift
// AndyWarholAccessibilityProject
//
// Created by Ruben Niculcea on 5/24/16.
// Copyright © 2016 Carnegie Museums of Pittsburgh Innovation Studio.
// All rights reserved.
//
import Foundation
enum CMSBeaconManagerEvents:String {
case BeaconManagerBeaconPing
case BluetoothStatusChanged
case LocationServicesAllowedChanged
}
enum CMSBeaconManagerLocationServicesStatus:String {
case NotDetermined = "LOCATION_SERVICES_STATUS_NOTDETERMINED"
case Denied = "LOCATION_SERVICES_STATUS_DENIED"
case Authorized = "LOCATION_SERVICES_STATUS_AUTHORIZED"
}
@objc(CMSBeaconManager)
class CMSBeaconManager: RCTEventEmitter {
var beaconManager = ESTBeaconManager()
var beaconRegion:CLBeaconRegion?
var locationManager: CLLocationManager!
var bluetoothPeripheralManager: CBPeripheralManager?
var jsResolveCallback:RCTPromiseResolveBlock?
var jsRejectCallback:RCTPromiseRejectBlock?
override init() {
super.init()
beaconManager.delegate = self
beaconManager.avoidUnknownStateBeacons = true
}
override func constantsToExport() -> [String: Any] {
let BeaconManagerBeaconPing = CMSBeaconManagerEvents.BeaconManagerBeaconPing.rawValue
let BluetoothStatusChanged = CMSBeaconManagerEvents.BluetoothStatusChanged.rawValue
let LocationServicesAllowedChanged = CMSBeaconManagerEvents.LocationServicesAllowedChanged.rawValue
return [
"Events": [
BeaconManagerBeaconPing: BeaconManagerBeaconPing,
BluetoothStatusChanged: BluetoothStatusChanged,
LocationServicesAllowedChanged: LocationServicesAllowedChanged,
]
]
}
override func supportedEvents() -> [String] {
let BeaconManagerBeaconPing = CMSBeaconManagerEvents.BeaconManagerBeaconPing.rawValue
let BluetoothStatusChanged = CMSBeaconManagerEvents.BluetoothStatusChanged.rawValue
let LocationServicesAllowedChanged = CMSBeaconManagerEvents.LocationServicesAllowedChanged.rawValue
return [
BeaconManagerBeaconPing,
BluetoothStatusChanged,
LocationServicesAllowedChanged,
]
}
@objc func beginBluetoothAndLocationServicesEvents() {
let options = [CBCentralManagerOptionShowPowerAlertKey: 0] // Don't show bluetooth popover
bluetoothPeripheralManager = CBPeripheralManager(delegate: self, queue: nil, options: options)
self.locationManager = CLLocationManager()
self.locationManager.delegate = self
}
@objc func requestLocationServicesAuthorization() {
locationManager.requestWhenInUseAuthorization()
}
@objc func startTracking(_ uuid: String,
identifier: String,
resolve:@escaping RCTPromiseResolveBlock,
reject:@escaping RCTPromiseRejectBlock) {
if let nsuuid = UUID(uuidString: uuid) {
beaconRegion = CLBeaconRegion(proximityUUID: nsuuid, identifier: identifier)
if beaconManager.rangedRegions.contains(beaconRegion!) {
resolve(nil)
return
}
jsRejectCallback = reject
jsResolveCallback = resolve
beaconManager.startRangingBeacons(in: beaconRegion!)
} else {
reject("Beacon Scanning failed", "uuidString is invalid", nil)
}
}
@objc func stopTracking() {
if let _beaconRegion = beaconRegion {
beaconManager.stopRangingBeacons(in: _beaconRegion)
}
}
func clearJSCallbacks() {
jsResolveCallback = nil
jsRejectCallback = nil
}
}
extension CMSBeaconManager: ESTBeaconManagerDelegate {
func beaconManager(_ manager: Any, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) {
if let resolve = jsResolveCallback {
clearJSCallbacks()
resolve(nil)
}
var beaconsJSON = [String]()
for beacon in beacons {
beaconsJSON.append("\(beacon.major):\(beacon.minor)")
}
let eventName = CMSBeaconManagerEvents.BeaconManagerBeaconPing.rawValue
self.sendEvent(withName: eventName, body: beaconsJSON)
}
func beaconManager(_ manager: Any, rangingBeaconsDidFailFor region: CLBeaconRegion?, withError error: Error) {
if let reject = jsRejectCallback {
clearJSCallbacks()
reject("Beacon Scanning failed", error.localizedDescription, nil)
}
}
}
extension CMSBeaconManager: CBPeripheralManagerDelegate {
func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
var bluetoothActive = false
switch peripheral.state {
case .unknown, .resetting, .poweredOff:
bluetoothActive = false
case .unsupported:
// This is never hit as every modern iOS device has bluetooth
break
case .unauthorized:
// This is never hit as we only use bluetooth for location
break
case .poweredOn:
bluetoothActive = true
}
sendBluetoothStatusEvent(bluetoothActive)
}
func sendBluetoothStatusEvent(_ bluetoothOn: Bool) {
let eventName = CMSBeaconManagerEvents.BluetoothStatusChanged.rawValue
self.sendEvent(withName: eventName, body: ["bluetoothOn": bluetoothOn])
}
}
extension CMSBeaconManager: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
let locationServicesStatus:CMSBeaconManagerLocationServicesStatus
switch status {
case .notDetermined:
locationServicesStatus = .NotDetermined
case .restricted, .denied:
locationServicesStatus = .Denied
case .authorizedAlways, .authorizedWhenInUse:
locationServicesStatus = .Authorized
}
sendLocationServicesEvent(locationServicesStatus)
}
func sendLocationServicesEvent(_ status: CMSBeaconManagerLocationServicesStatus) {
let eventName = CMSBeaconManagerEvents.LocationServicesAllowedChanged.rawValue
self.sendEvent(withName: eventName, body: ["locationServicesStatus": status.rawValue])
}
}
| mit |
jerrypupu111/LearnDrawingToolSet | SwiftGL-Demo/Source/Common/PaintArtwork.swift | 1 | 3853 | //
// PaintArtwork.swift
// SwiftGL
//
// Created by jerry on 2015/5/21.
// Copyright (c) 2015年 Jerry Chan. All rights reserved.
//
enum ArtworkType:String{
case Artwork = "Artwork"
case Tutorial = "Tutorial"
case Trace = "Trace"
}
import Foundation
import GLFramework
class PaintArtwork
{
var artworkType:ArtworkType = .Artwork
var canvasWidth:Int
var canvasHeight:Int
fileprivate var _masterClip:PaintClip
fileprivate var _revisionClips:[Int:PaintClip] = [Int:PaintClip]()
var revisionClips:[Int:PaintClip]{
get{
return _revisionClips
}
}
var lastClip:PaintClip
var currentClip:PaintClip
{
willSet(newClip)
{
if newClip != currentClip
{
lastClip = currentClip
//unbind the stroke change event if the clip has changed
//newClip.onStrokeIDChanged = currentClip.onStrokeIDChanged
//currentClip.onStrokeIDChanged = nil
}
}
}
var currentRevisionID:Int!
var isFileExist:Bool = false
var currentNoteIndex:Int = 0
var currentNote:SANote!
init(width:Int,height:Int)
{
_masterClip = PaintClip(name: "master",branchAt: 0)
_masterClip.currentTime = 0
currentClip = _masterClip
lastClip = currentClip
canvasWidth = width
canvasHeight = height
}
func setReplayer(_ paintView:PaintView,type:ArtworkType = .Artwork)
{
self.artworkType = type
var buffer:GLContextBuffer = paintView.paintBuffer
if type == .Tutorial
{
buffer = paintView.tutorialBuffer
}
else if type == .Trace
{
buffer = paintView.tutorialBuffer
}
masterReplayer = PaintReplayer(paintView:paintView,context: buffer)
revisionReplayer = PaintReplayer(paintView:paintView,context: buffer)
currentReplayer = masterReplayer
}
func setUpClips()
{
masterReplayer.loadClip(_masterClip)
}
func drawAll()
{
masterReplayer.drawAll()
}
func drawClip(_ clip:PaintClip)
{
_masterClip = clip
masterReplayer.loadClip(clip)
masterReplayer.drawAll()
}
func setArtworkMode()
{
}
func loadCurrentClip()
{
masterReplayer.loadClip(currentClip)
currentReplayer = masterReplayer
}
func loadClip(_ clip:PaintClip)
{
currentClip = clip
masterReplayer.loadClip(clip)
revisionReplayer.stopPlay()
currentReplayer = masterReplayer
masterReplayer.drawAll()
}
func loadMasterClip()
{
currentClip = _masterClip
masterReplayer.loadClip(_masterClip)
revisionReplayer.stopPlay()
currentReplayer = masterReplayer
}
func loadCurrentRevisionClip()
{
loadRevisionClip(currentRevisionID)
}
func loadRevisionClip(_ stroke:Int)
{
currentRevisionID = stroke
revisionReplayer.loadClip(_revisionClips[stroke]!)
masterReplayer.pause()
currentReplayer = revisionReplayer
}
func useClip(_ clip:PaintClip)->PaintClip
{
currentClip = clip
return currentClip
}
func useMasterClip()->PaintClip
{
return useClip(_masterClip)
}
func useRevisionClip(_ id:Int)->PaintClip
{
return useClip(revisionClips[id]!)
}
func addRevisionClip(_ atStroke:Int)
{
let newClip = PaintClip(name: "revision",branchAt: atStroke)
//newClip.strokeDelegate = _masterClip.strokeDelegate
_revisionClips[atStroke] = newClip
}
var masterReplayer:PaintReplayer!
var revisionReplayer:PaintReplayer!
var currentReplayer:PaintReplayer!
}
| mit |
Alan881/AAPlayer | Sources/AAPlayProgressView.swift | 2 | 620 | //
// AAPlayProgressView.swift
// AAPlayer
//
// Created by Alan on 2017/7/1.
// Copyright © 2017年 Alan. All rights reserved.
//
import UIKit
class AAPlayProgressView: UIProgressView {
override func sizeThatFits(_ size: CGSize) -> CGSize {
super.sizeThatFits(size)
let size = CGSize.init(width: size.width, height: 2)
return size
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
| mit |
lanserxt/teamwork-ios-sdk | TeamWorkClient/TeamWorkClient/Requests/TWApiClient+Permissions.swift | 1 | 8669 | //
// TWApiClient+Invoices.swift
// TeamWorkClient
//
// Created by Anton Gubarenko on 02.02.17.
// Copyright © 2017 Anton Gubarenko. All rights reserved.
//
import Foundation
import Alamofire
extension TWApiClient{
func addNewUserToProject(projectId: String, peopleId: String, _ responseBlock: @escaping (Bool, Int, Error?) -> Void){
Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.addNewUserToProject.path, projectId, peopleId), method: HTTPMethod.post, parameters: nil, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.validate(contentType: [kContentType])
.authenticate(user: kApiToken, password: kAuthPass)
.responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
let JSON = result as! NSDictionary
if let responseContainer = ResponseContainer<UserStatus>.init(rootObjectName: TWApiClientConstants.APIPath.addNewUserToProject.rootElement, dictionary: JSON){
if (responseContainer.status == TWApiStatusCode.OK){
responseBlock (true, 200, nil)
} else {
responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK)
}
}
else
{
responseBlock (false, 0, TWApiClientErrors.ResponseValidationError)
}
}
case .failure(let error):
print(error)
responseBlock(false, (response.response?.statusCode)!, error)
}
}
}
func addNewUsers(projectId: String, parameters: [String: Any], _ responseBlock: @escaping (Bool, Int, Error?) -> Void){
Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.addNewUsers.path, projectId), method: HTTPMethod.post, parameters: parameters, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.validate(contentType: [kContentType])
.authenticate(user: kApiToken, password: kAuthPass)
.responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
let JSON = result as! NSDictionary
if let responseContainer = ResponseContainer<UserStatus>.init(rootObjectName: TWApiClientConstants.APIPath.addNewUsers.rootElement, dictionary: JSON){
if (responseContainer.status == TWApiStatusCode.OK){
responseBlock (true, 200, nil)
} else {
responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK)
}
}
else
{
responseBlock (false, 0, TWApiClientErrors.ResponseValidationError)
}
}
case .failure(let error):
print(error)
responseBlock(false, (response.response?.statusCode)!, error)
}
}
}
func deleteUserFromProject(projectId: String, _ responseBlock: @escaping (Bool, Int, Error?) -> Void){
Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.deleteUserFromProject.path, projectId), method: HTTPMethod.delete, parameters: nil, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.validate(contentType: [kContentType])
.authenticate(user: kApiToken, password: kAuthPass)
.responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
let JSON = result as! NSDictionary
if let responseContainer = ResponseContainer<UserStatus>.init(rootObjectName: TWApiClientConstants.APIPath.deleteUserFromProject.rootElement, dictionary: JSON){
if (responseContainer.status == TWApiStatusCode.OK){
responseBlock (true, 200, nil)
} else {
responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK)
}
}
else
{
responseBlock (false, 0, TWApiClientErrors.ResponseValidationError)
}
}
case .failure(let error):
print(error)
responseBlock(false, (response.response?.statusCode)!, error)
}
}
}
//CHECK that multiple response
func getUserPermissions(projectId: String, peopleId: String, _ responseBlock: @escaping (Bool, Int, [PersonDetails]?, Error?) -> Void){
Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.getUserPermissions.path, projectId, peopleId), method: HTTPMethod.get, parameters: nil, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.validate(contentType: [kContentType])
.authenticate(user: kApiToken, password: kAuthPass)
.responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
let JSON = result as! NSDictionary
if let responseContainer = MultipleResponseContainer<PersonDetails>.init(rootObjectName: TWApiClientConstants.APIPath.getUserPermissions.rootElement, dictionary: JSON){
if (responseContainer.status == TWApiStatusCode.OK){
responseBlock (true, 200, responseContainer.rootObjects, nil)
} else {
responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK)
}
}
else
{
responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError)
}
}
case .failure(let error):
print(error)
responseBlock(false, (response.response?.statusCode)!, nil, error)
}
}
}
func updateUserPermissions(personId: String, peopleId: String, permissions: [String : Any], _ responseBlock: @escaping (Bool, Int, Error?) -> Void){
let parameters: [String : Any] = ["permissions" : permissions]
Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.updateUserPermissions.path, personId, peopleId), method: HTTPMethod.put, parameters: parameters, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.validate(contentType: [kContentType])
.authenticate(user: kApiToken, password: kAuthPass)
.responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
let JSON = result as! NSDictionary
if let responseContainer = ResponseContainer<PersonDetails>.init(rootObjectName: TWApiClientConstants.APIPath.updateUserPermissions.rootElement, dictionary: JSON){
if (responseContainer.status == TWApiStatusCode.OK){
responseBlock (true, 200, nil)
} else {
responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK)
}
}
else
{
responseBlock (false, 0, TWApiClientErrors.ResponseValidationError)
}
}
case .failure(let error):
print(error)
responseBlock(false, (response.response?.statusCode)!, error)
}
}
}
}
| mit |
DataBreweryIncubator/StructuredQuery | Sources/Types/Signature.swift | 1 | 1267 | public class FunctionSignature: CustomStringConvertible {
public let arguments: [DataType]
public let returnType: DataType
public init(arguments: [DataType], returnType: DataType) {
self.arguments = arguments
self.returnType = returnType
}
// TODO: Variadic matching is not supported yet
public func matches(arguments: [DataType]) -> Bool {
if arguments.count != self.arguments.count {
return false
}
else {
return self.arguments.elementsEqual(arguments) {
(this, other) in
this == DataType.ANY || this == other
}
}
}
public var description: String {
let strings = arguments.map { $0.description }
let fullString = strings.joined(separator:", ")
return "[\(fullString)] -> \(returnType.description)"
}
}
infix operator |^|: AdditionPrecedence
public func |^|(lhs: DataType, rhs: DataType) -> FunctionSignature {
return FunctionSignature(
arguments: [lhs],
returnType: rhs
)
}
public func |^|(lhs: (DataType, DataType), rhs: DataType) -> FunctionSignature {
return FunctionSignature(
arguments: [lhs.0, lhs.1],
returnType: rhs
)
}
| mit |
JBerendes/react-native-video-processing | ios/RNVideoProcessing/RNTrimmerView/RNTrimmerView.swift | 1 | 6948 | //
// RNTrimmerView.swift
// RNVideoProcessing
//
import UIKit
import AVKit
@objc(RNTrimmerView)
class RNTrimmerView: RCTView, ICGVideoTrimmerDelegate {
var trimmerView: ICGVideoTrimmerView?
var asset: AVAsset!
var rect: CGRect = CGRect.zero
var mThemeColor = UIColor.clear
var bridge: RCTBridge!
var onChange: RCTBubblingEventBlock?
var onTrackerMove: RCTBubblingEventBlock?
var _minLength: CGFloat? = nil
var _maxLength: CGFloat? = nil
var _thumbWidth: CGFloat? = nil
var _trackerColor: UIColor = UIColor.clear
var _trackerHandleColor: UIColor = UIColor.clear
var _showTrackerHandle = false
var source: NSString? {
set {
setSource(source: newValue)
}
get {
return nil
}
}
var showTrackerHandle: NSNumber? {
set {
if newValue == nil {
return
}
let _nVal = newValue! == 1 ? true : false
if _showTrackerHandle != _nVal {
print("CHANGED: showTrackerHandle \(newValue!)");
_showTrackerHandle = _nVal
self.updateView()
}
}
get {
return nil
}
}
var trackerHandleColor: NSString? {
set {
if newValue != nil {
let color = NumberFormatter().number(from: newValue! as String)
let formattedColor = RCTConvert.uiColor(color)
if formattedColor != nil {
print("CHANGED: trackerHandleColor: \(newValue!)")
self._trackerHandleColor = formattedColor!
self.updateView();
}
}
}
get {
return nil
}
}
var height: NSNumber? {
set {
self.rect.size.height = RCTConvert.cgFloat(newValue) + 40
self.updateView()
}
get {
return nil
}
}
var width: NSNumber? {
set {
self.rect.size.width = RCTConvert.cgFloat(newValue)
self.updateView()
}
get {
return nil
}
}
var themeColor: NSString? {
set {
if newValue != nil {
let color = NumberFormatter().number(from: newValue! as String)
self.mThemeColor = RCTConvert.uiColor(color)
self.updateView()
}
}
get {
return nil
}
}
var maxLength: NSNumber? {
set {
if newValue != nil {
self._maxLength = RCTConvert.cgFloat(newValue!)
self.updateView()
}
}
get {
return nil
}
}
var minLength: NSNumber? {
set {
if newValue != nil {
self._minLength = RCTConvert.cgFloat(newValue!)
self.updateView()
}
}
get {
return nil
}
}
var thumbWidth: NSNumber? {
set {
if newValue != nil {
self._thumbWidth = RCTConvert.cgFloat(newValue!)
self.updateView()
}
}
get {
return nil
}
}
var currentTime: NSNumber? {
set {
print("CHANGED: [TrimmerView]: currentTime: \(newValue)")
if newValue != nil && self.trimmerView != nil {
let convertedValue = newValue as! CGFloat
self.trimmerView?.seek(toTime: convertedValue)
// self.trimmerView
}
}
get {
return nil
}
}
var trackerColor: NSString? {
set {
if newValue == nil {
return
}
print("CHANGED: trackerColor \(newValue!)")
let color = NumberFormatter().number(from: newValue! as String)
let formattedColor = RCTConvert.uiColor(color)
if formattedColor != nil {
self._trackerColor = formattedColor!
self.updateView()
}
}
get {
return nil
}
}
func updateView() {
self.frame = rect
if trimmerView != nil {
trimmerView!.frame = rect
trimmerView!.themeColor = self.mThemeColor
trimmerView!.trackerColor = self._trackerColor
trimmerView!.trackerHandleColor = self._trackerHandleColor
trimmerView!.showTrackerHandle = self._showTrackerHandle
trimmerView!.maxLength = _maxLength == nil ? CGFloat(self.asset.duration.seconds) : _maxLength!
self.frame = CGRect(x: rect.origin.x, y: rect.origin.y, width: rect.size.width, height: rect.size.height + 20)
if _minLength != nil {
trimmerView!.minLength = _minLength!
}
if _thumbWidth != nil {
trimmerView!.thumbWidth = _thumbWidth!
}
self.trimmerView!.resetSubviews()
// Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(self.updateTrimmer), userInfo: nil, repeats: false)
}
}
func updateTrimmer() {
self.trimmerView!.resetSubviews()
}
func setSource(source: NSString?) {
if source != nil {
let pathToSource = NSURL(string: source! as String)
self.asset = AVURLAsset(url: pathToSource! as URL, options: nil)
trimmerView = ICGVideoTrimmerView(frame: rect, asset: self.asset)
trimmerView!.showsRulerView = false
trimmerView!.hideTracker(false)
trimmerView!.delegate = self
trimmerView!.trackerColor = self._trackerColor
self.addSubview(trimmerView!)
self.updateView()
}
}
init(frame: CGRect, bridge: RCTBridge) {
super.init(frame: frame)
self.bridge = bridge
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func onTrimmerPositionChange(startTime: CGFloat, endTime: CGFloat) {
if self.onChange != nil {
let event = ["startTime": startTime, "endTime": endTime]
self.onChange!(event)
}
}
func trimmerView(_ trimmerView: ICGVideoTrimmerView, didChangeLeftPosition startTime: CGFloat, rightPosition endTime: CGFloat) {
onTrimmerPositionChange(startTime: startTime, endTime: endTime)
}
public func trimmerView(_ trimmerView: ICGVideoTrimmerView, currentPosition currentTime: CGFloat) {
print("current", currentTime)
if onTrackerMove == nil {
return
}
let event = ["currentTime": currentTime]
self.onTrackerMove!(event)
}
}
| mit |
mikekavouras/Glowb-iOS | Glowb/Utility/Router.swift | 1 | 8261 | //
// Router.swift
// Glowb
// // Created by Michael Kavouras on 12/6/16.
// Copyright © 2016 Michael Kavouras. All rights reserved.
//
import Foundation
import Alamofire
typealias JSON = [String: Any]
enum APIError: Error {
case keyNotFound
}
enum Router: URLRequestConvertible {
// auth
case createOAuthToken
case refreshOAuthToken
case revokeOAuthToken
// devices
case getDevices
case getDevice(Int)
case updateDevice(Int, String)
case createDevice(String, String)
case deleteDevice(Int)
case resetDevice(Int)
// interactions
case getInteractions
case getInteraction(Int)
case createInteraction(Interaction)
case updateInteraction(Interaction)
case deleteInteraction(Int)
case createEvent(Interaction)
// invites
case createInvite(Int, Date, Int)
case claimInvite(String, String)
// photos
case getPhotos
case createPhoto
case updatePhoto(Photo)
// shares
case createShare(Int)
case deleteShare(Share)
fileprivate static let apiRoot: String = Plist.Config.APIRoot
fileprivate static let appID: String = Plist.Config.appId
}
extension Router {
func asURLRequest() throws -> URLRequest {
switch self {
case .createOAuthToken:
return try JSONEncoding.default.encode(request, with: [:])
case .refreshOAuthToken:
return try JSONEncoding.default.encode(request, with: [:])
case .revokeOAuthToken:
return try JSONEncoding.default.encode(request, with: [:])
case .getDevices:
return try URLEncoding.default.encode(request, with: [:])
case .getDevice(let deviceId):
let params = [ "device_id" : deviceId ]
return try URLEncoding.default.encode(request, with: params)
case .updateDevice(_, let name):
let params = [ "name" : name ]
return try JSONEncoding.default.encode(request, with: params)
case .createDevice(let deviceId, let name):
let params = [ "particle_id" : deviceId, "name" : name ]
return try JSONEncoding.default.encode(request, with: params)
case .deleteDevice:
return try JSONEncoding.default.encode(request, with: [:])
case .resetDevice:
return try JSONEncoding.default.encode(request, with: [:])
case .getInteractions:
return try URLEncoding.default.encode(request, with: [:])
case .getInteraction:
return try URLEncoding.default.encode(request, with: [:])
case .createInteraction(let interaction):
let params = interaction.asJSON
return try JSONEncoding.default.encode(request, with: params)
case .updateInteraction(let interaction):
let params = interaction.asJSON
return try JSONEncoding.default.encode(request, with: params)
case .deleteInteraction:
return try URLEncoding.default.encode(request, with: [:])
case .createEvent:
return try JSONEncoding.default.encode(request, with: [:])
case .createInvite(let deviceId, let expiresAt, let limit):
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
let dateString = formatter.string(from: expiresAt)
let params: JSON = [ "device_id" : deviceId, "expires_at" : dateString, "usage_limit" : limit ]
return try JSONEncoding.default.encode(request, with: params)
case .claimInvite(let name, let token):
let params = [ "name" : name, "token" : token ]
return try JSONEncoding.default.encode(request, with: params)
case .getPhotos:
return try URLEncoding.default.encode(request, with: [:])
case .createPhoto:
return try JSONEncoding.default.encode(request, with: [:])
case .updatePhoto(let photo):
let params = photo.toJSON()
return try JSONEncoding.default.encode(request, with: params)
case .createShare(let interactionId):
let params = [ "interaction_id" : interactionId ]
return try JSONEncoding.default.encode(request, with: params)
case .deleteShare:
return try URLEncoding.default.encode(request, with: [:])
}
}
private var method: Alamofire.HTTPMethod {
switch self {
case .createOAuthToken:
return .post
case .refreshOAuthToken:
return .post
case .revokeOAuthToken:
return .post
case .getDevices:
return .get
case .getDevice:
return .get
case .updateDevice:
return .patch
case .createDevice:
return .post
case .deleteDevice:
return .delete
case .resetDevice:
return .post
case .createInteraction:
return .post
case .getInteractions:
return .get
case .getInteraction:
return .get
case .updateInteraction:
return .patch
case .deleteInteraction:
return .delete
case .createEvent:
return .post
case .createInvite:
return .post
case .claimInvite:
return .post
case .getPhotos:
return .get
case .createPhoto:
return .post
case .updatePhoto:
return .patch
case .createShare:
return .post
case .deleteShare:
return .delete
}
}
private var path: String {
switch self {
case .createOAuthToken:
return "/api/v1/oauth"
case .refreshOAuthToken:
return "/api/v1/oauth/token"
case .revokeOAuthToken:
return "/api/v1/oauth/revoke"
case .getDevices:
return "/api/v1/devices"
case .getDevice(let deviceID):
return "/api/v1/devices/\(deviceID)"
case .updateDevice(let deviceID, _):
return "/api/v1/devices/\(deviceID)"
case .createDevice:
return "/api/v1/devices"
case .deleteDevice(let deviceID):
return "/api/v1/devices/\(deviceID)"
case .resetDevice(let deviceID):
return "/api/v1/devices/reset/\(deviceID)"
case .createInteraction:
return "/api/v1/interactions"
case .getInteractions:
return "/api/v1/interactions"
case .getInteraction(let interactionId):
return "/api/v1/interactions/\(interactionId)"
case .updateInteraction(let interaction):
return "/api/v1/interactions/\(interaction.id!)"
case .deleteInteraction(let interactionId):
return "/api/v1/interactions/\(interactionId)"
case .createEvent(let interaction):
return "/api/v1/interactions/\(interaction.id!)"
case .createInvite:
return "/api/v1/invites"
case .claimInvite:
return "/api/v1/invites/accept"
case .getPhotos:
return "/api/v1/photos"
case .createPhoto:
return "/api/v1/photos"
case .updatePhoto(let photo):
return "/api/v1/photos/\(photo.id!)"
case .createShare:
return "/api/v1/shares"
case .deleteShare(let share):
return "/api/v1/shares/\(share.id)"
}
}
private var request: URLRequest {
let url = URL(string: "\(Router.apiRoot)")!
var request = URLRequest(url: url.appendingPathComponent(path))
request.httpMethod = method.rawValue
request.setValue(Router.appID, forHTTPHeaderField: "X-Application-Id")
if let token = User.current.accessToken {
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
}
return request
}
}
| mit |
zekunyan/TTGSnackbar | Package.swift | 2 | 298 | // swift-tools-version:5.0
import PackageDescription
let package = Package(
name: "TTGSnackbar",
platforms: [.iOS(.v9)],
products: [
.library(name: "TTGSnackbar", targets: ["TTGSnackbar"])
],
targets: [
.target(name: "TTGSnackbar", path: "TTGSnackbar")
]
)
| mit |
Laurensesss/Learning-iOS-Programming-with-Swift | Calculator/Calculator/AppDelegate.swift | 1 | 2137 | //
// AppDelegate.swift
// Calculator
//
// Created by 石韬 on 16/5/6.
// Copyright © 2016年 石韬. 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 |
alisidd/iOS-WeJ | WeJ/Add Tracks/MusicLibrarySelectionViewController.swift | 1 | 5896 | //
// MusicLibrarySelectionViewController.swift
// WeJ
//
// Created by Mohammad Ali Siddiqui on 8/9/17.
// Copyright © 2017 Mohammad Ali Siddiqui. All rights reserved.
//
import UIKit
import RKNotificationHub
import NVActivityIndicatorView
class MusicLibrarySelectionViewController: UIViewController, ViewControllerAccessDelegate {
private weak var delegate: AddTracksTabBarController!
@IBOutlet weak var headerHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var myLibraryLabel: UILabel!
@IBOutlet weak var doneButton: UIButton!
private var badge: RKNotificationHub!
private var totalTracksCount: Int {
let controller = tabBarController! as! AddTracksTabBarController
return controller.tracksSelected.count + controller.libraryTracksSelected.count
}
@IBOutlet weak var spotifyLibraryButton: UIButton!
@IBOutlet weak var spotifyActivityIndicator: NVActivityIndicatorView!
@IBOutlet weak var appleMusicLibraryButton: UIButton!
private var libraryMusicService: MusicService!
private var authorizationManager: AuthorizationManager!
var processingLogin = false {
didSet {
DispatchQueue.main.async {
if self.processingLogin && self.libraryMusicService == .spotify {
self.spotifyActivityIndicator.startAnimating()
} else if self.libraryMusicService == .spotify {
self.spotifyActivityIndicator.stopAnimating()
}
}
}
}
@IBOutlet weak var playlistsButton: UIButton!
@IBOutlet weak var tracksTableView: UITableView!
@IBOutlet weak var playlistsActivityIndicator: NVActivityIndicatorView!
private let fetcher: Fetcher = Party.musicService == .spotify ? SpotifyFetcher() : AppleMusicFetcher()
var tracksList = [Track]() {
didSet {
DispatchQueue.main.async {
self.tracksTableView.reloadData()
self.playlistsActivityIndicator.stopAnimating()
self.fetchArtworkForRestOfTracks()
}
}
}
func setBadge(to count: Int) {
badge.count = Int32(count)
badge.pop()
}
override func viewDidLoad() {
super.viewDidLoad()
hideNavigationBar()
initializeBadge()
initializeVariables()
setDelegates()
adjustViews()
adjustFontSizes()
getTrending()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setBadge(to: totalTracksCount)
}
private func hideNavigationBar() {
navigationController?.navigationBar.isHidden = true
}
private func initializeBadge() {
badge = RKNotificationHub(view: doneButton.titleLabel)
badge.count = Int32(totalTracksCount)
badge.moveCircleBy(x: CGFloat(Float(NSLocalizedString("DoneBadgeConstraint", comment: "")) ?? 51.0), y: 0)
badge.scaleCircleSize(by: 0.7)
badge.setCircleColor(AppConstants.orange, label: .white)
}
private func initializeVariables() {
SpotifyAuthorizationManager.storyboardSegue = "Show Spotify Library"
AppleMusicAuthorizationManager.storyboardSegue = "Show Apple Music Library"
}
private func setDelegates() {
delegate = navigationController?.tabBarController! as! AddTracksTabBarController
SpotifyAuthorizationManager.delegate = self
AppleMusicAuthorizationManager.delegate = self
tracksTableView.delegate = delegate
tracksTableView.dataSource = delegate
}
private func adjustViews() {
tracksTableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 50, right: 0)
}
private func adjustFontSizes() {
if UIDevice.deviceType == .iPhone4_4s || UIDevice.deviceType == .iPhone5_5s_SE {
myLibraryLabel.changeToSmallerFont()
doneButton.changeToSmallerFont()
spotifyLibraryButton.changeToSmallerFont()
appleMusicLibraryButton.changeToSmallerFont()
playlistsButton.changeToSmallerFont()
}
}
private func getTrending() {
playlistsActivityIndicator.startAnimating()
fetcher.getMostPlayed { [weak self] in
self?.tracksList = self?.fetcher.tracksList ?? []
}
}
private func fetchArtworkForRestOfTracks() {
let tracksCaptured = tracksList
for track in tracksList where tracksList == tracksCaptured && track.lowResArtwork == nil {
DispatchQueue.global(qos: .userInitiated).async {
track.fetchImage(fromURL: track.lowResArtworkURL) { [weak self, weak track] (image) in
track?.lowResArtwork = image
self?.tracksTableView.reloadData()
}
}
}
}
// MARK: - Navigation
@IBAction func showSpotifyLibrary() {
guard !processingLogin else { return }
authorizationManager = SpotifyAuthorizationManager()
libraryMusicService = .spotify
authorizationManager.requestAuthorization()
}
@IBAction func showAppleMusicLibrary() {
guard !processingLogin else { return }
authorizationManager = AppleMusicAuthorizationManager()
libraryMusicService = .appleMusic
authorizationManager.requestAuthorization()
}
func tryAgain() {
if libraryMusicService == .spotify {
showSpotifyLibrary()
} else {
showAppleMusicLibrary()
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let controller = segue.destination as? PlaylistSelectionViewController {
controller.musicService = libraryMusicService
}
}
}
| gpl-3.0 |
linkedin/LayoutTest-iOS | SampleApp/SampleApp/SampleFailingView.swift | 1 | 1040 | // © 2016 LinkedIn Corp. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import UIKit
open class SampleFailingView: UIView {
private static let nibName = "SampleFailingView"
@IBOutlet weak var label: UILabel!
@IBOutlet weak var button: UIButton!
class func loadFromNib() -> SampleFailingView {
return Bundle.main.loadNibNamed(SampleFailingView.nibName, owner: nil, options: nil)![0] as! SampleFailingView
}
func setup(_ json: [AnyHashable: Any]) {
label.text = json["text"] as? String
button.setTitle(json["buttonText"] as? String, for: UIControlState())
}
}
| apache-2.0 |
Mikhepls/ios-notes | accountnotes/accountnotes/copyableLabel.swift | 1 | 1393 | //
// copyableLabel.swift
// accountnotes
//
// Created by Tom Lagerbom on 04/02/16.
// Copyright © 2016 Mikael's apps. All rights reserved.
//
import UIKit
class copyableLabel: UILabel {
override init(frame: CGRect) {
super.init(frame: frame)
sharedInit()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
sharedInit()
}
override func canBecomeFirstResponder() -> Bool {
return true
}
override func copy(sender: AnyObject?) {
let board = UIPasteboard.generalPasteboard()
board.string = text
let menu = UIMenuController.sharedMenuController()
menu.setMenuVisible(false, animated: true)
}
func sharedInit() {
userInteractionEnabled = true
addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: "showMenu:"))
}
func showMenu(sender: AnyObject?) {
becomeFirstResponder()
let menu = UIMenuController.sharedMenuController()
if !menu.menuVisible {
menu.setTargetRect(bounds, inView: self)
menu.setMenuVisible(true, animated: true)
}
}
override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
if action == "copy:" {
return true
}
return false
}
} | mit |
hayashi311/iosdcjp2016app | iOSApp/Pods/AcknowList/Source/AcknowParser.swift | 1 | 4352 | //
// AcknowParser.swift
//
// Copyright (c) 2015-2016 Vincent Tourraine (http://www.vtourraine.net)
//
// 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
/// Responsible for parsing a CocoaPods acknowledgements plist file.
public class AcknowParser {
/**
The root dictionary from the loaded plist file.
*/
let rootDictionary: [String: AnyObject]
/**
Initializes the `AcknowParser` instance with a plist path.
- parameter plistPath: The path to the acknowledgements plist file.
- returns: The new `AcknowParser` instance.
*/
public init(plistPath: String) {
let root = NSDictionary(contentsOfFile: plistPath)
if let root = root where root is [String: AnyObject] {
self.rootDictionary = root as! [String: AnyObject]
}
else {
self.rootDictionary = Dictionary()
}
}
/**
Parses the header and footer values.
- return: a tuple with the header and footer values.
*/
public func parseHeaderAndFooter() -> (header: String?, footer: String?) {
let preferenceSpecifiers: AnyObject? = self.rootDictionary["PreferenceSpecifiers"]
if let preferenceSpecifiers = preferenceSpecifiers where preferenceSpecifiers is [AnyObject] {
let preferenceSpecifiersArray = preferenceSpecifiers as! [AnyObject]
if let headerItem = preferenceSpecifiersArray.first,
let footerItem = preferenceSpecifiersArray.last,
let headerText = headerItem["FooterText"] where headerItem is [String: String],
let footerText = footerItem["FooterText"] where footerItem is [String: String] {
return (headerText as! String?, footerText as! String?)
}
}
return (nil, nil)
}
/**
Parses the array of acknowledgements.
- return: an array of `Acknow` instances.
*/
public func parseAcknowledgements() -> [Acknow] {
let preferenceSpecifiers: AnyObject? = self.rootDictionary["PreferenceSpecifiers"]
if let preferenceSpecifiers = preferenceSpecifiers where preferenceSpecifiers is [AnyObject] {
let preferenceSpecifiersArray = preferenceSpecifiers as! [AnyObject]
// Remove the header and footer
let ackPreferenceSpecifiers = preferenceSpecifiersArray.filter({ (object: AnyObject) -> Bool in
if let firstObject = preferenceSpecifiersArray.first,
let lastObject = preferenceSpecifiersArray.last {
return (object.isEqual(firstObject) == false && object.isEqual(lastObject) == false)
}
return true
})
let acknowledgements = ackPreferenceSpecifiers.map({
(preferenceSpecifier: AnyObject) -> Acknow in
if let title = preferenceSpecifier["Title"] as! String?,
text = preferenceSpecifier["FooterText"] as! String? {
return Acknow(
title: title,
text: text)
}
else {
return Acknow(title: "", text: "")
}
})
return acknowledgements
}
return []
}
}
| mit |
sascha/DrawerController | KitchenSink/ExampleFiles/TableViewHelpers/CenterTableViewCell.swift | 1 | 1761 | // Copyright (c) 2017 evolved.io (http://evolved.io)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
class CenterTableViewCell: TableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.accessoryCheckmarkColor = UIColor(red: 13 / 255, green: 88 / 255, blue: 161 / 255, alpha: 1.0)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.accessoryCheckmarkColor = UIColor(red: 13 / 255, green: 88 / 255, blue: 161 / 255, alpha: 1.0)
}
override func updateContentForNewContentSize() {
self.textLabel?.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.body)
}
}
| mit |
iawtav/Simple-Weather | Weather/SearchCell.swift | 1 | 1077 | //
// SearchCell.swift
// Weather
//
// Created by TUANANH VUONG on 2016/10/10.
// Copyright © 2016 TUANANH VUONG. All rights reserved.
//
import UIKit
class SearchCell: UITableViewCell {
@IBOutlet weak var weatherTypeIcon: UIImageView!
@IBOutlet weak var weatherType: UILabel!
@IBOutlet weak var currentTemp: UILabel!
@IBOutlet weak var highTemp: UILabel!
@IBOutlet weak var lowTemp: UILabel!
@IBOutlet weak var location: UILabel!
@IBOutlet weak var summary: UILabel!
@IBOutlet weak var tomorow: UILabel!
func configCell(moreLocations: MoreLocation) {
weatherTypeIcon.image = UIImage(named: moreLocations.currentWeatherIcon)
weatherType.text = moreLocations.currentWeatherType
currentTemp.text = "\(moreLocations.currentTemp)˚"
highTemp.text = "High: \(moreLocations.highTemp)˚"
lowTemp.text = "Low: \(moreLocations.lowTemp)˚"
location.text = moreLocations.location
summary.text = moreLocations.summary
tomorow.text = "Tomorrow: \(moreLocations.tomorrow)"
}
}
| apache-2.0 |
eduarenas/GithubClient | Sources/GitHubClient/Models/Response/User.swift | 1 | 1680 | //
// RepositoriesClient.swift
// GithubClient
//
// Created by Eduardo Arenas on 8/5/17.
// Copyright © 2017 GameChanger. All rights reserved.
//
import Foundation
public struct User: Decodable {
public let login: String
public let id: Int
public let avatarUrl: String?
public let url: String?
public let htmlUrl: String?
public let type: UserType
public let siteAdmin: Bool?
public let name: String?
public let company: String?
public let blog: String?
public let location: String?
public let email: String?
public let hireable: Bool?
public let bio: String?
public let publicRepos: Int?
public let publicGists: Int?
public let followers: Int?
public let following: Int?
public let createdAt: Date?
public let updatedAt: Date?
public let totalPrivateRepos: Int?
public let ownedPrivateRepos: Int?
public let privateGists: Int?
public let diskUsage: Int?
public let collaborators: Int?
// TODO: let plan: Plan?
}
extension User {
enum CodingKeys: String, CodingKey {
case login
case id
case avatarUrl = "avatar_url"
case url
case htmlUrl = "html_url"
case type
case siteAdmin = "site_admin"
case name
case company
case blog
case location
case email
case hireable
case bio
case publicRepos = "public_repos"
case publicGists = "public_gists"
case followers
case following
case createdAt = "created_at"
case updatedAt = "updated_at"
case totalPrivateRepos = "total_private_repos"
case ownedPrivateRepos = "owned_private_repos"
case privateGists = "private_gists"
case diskUsage = "disk_usage"
case collaborators
}
}
| mit |
MrAlek/JSQDataSourcesKit | Source/DataSourceProvider.swift | 1 | 4769 | //
// Created by Jesse Squires
// http://www.jessesquires.com
//
//
// Documentation
// http://jessesquires.com/JSQDataSourcesKit
//
//
// GitHub
// https://github.com/jessesquires/JSQDataSourcesKit
//
//
// License
// Copyright © 2015 Jesse Squires
// Released under an MIT license: http://opensource.org/licenses/MIT
//
import Foundation
import UIKit
public final class DataSourceProvider<SectionInfo: SectionInfoProtocol, CellFactory: CellFactoryProtocol
where CellFactory.Item == SectionInfo.Item>: CustomStringConvertible {
public var sections: [SectionInfo]
public let cellFactory: CellFactory
private var bridgedDataSource: BridgedDataSource?
public init(sections: [SectionInfo], cellFactory: CellFactory) {
self.sections = sections
self.cellFactory = cellFactory
}
public subscript (index: Int) -> SectionInfo {
get {
return sections[index]
}
set {
sections[index] = newValue
}
}
public subscript (indexPath: NSIndexPath) -> SectionInfo.Item {
get {
return sections[indexPath.section].items[indexPath.item]
}
set {
sections[indexPath.section].items[indexPath.item] = newValue
}
}
// MARK: CustomStringConvertible
/// :nodoc:
public var description: String {
get {
return "<\(DataSourceProvider.self): sections=\(sections)>"
}
}
}
public extension DataSourceProvider where CellFactory.Cell: UITableViewCell {
public var tableViewDataSource: UITableViewDataSource {
if bridgedDataSource == nil {
bridgedDataSource = tableViewBridgedDataSource()
}
return bridgedDataSource!
}
private func tableViewBridgedDataSource() -> BridgedDataSource {
let dataSource = BridgedDataSource(
numberOfSections: { [unowned self] () -> Int in
return self.sections.count
},
numberOfItemsInSection: { [unowned self] (section) -> Int in
return self.sections[section].items.count
})
dataSource.tableCellForRowAtIndexPath = { [unowned self] (tableView, indexPath) -> UITableViewCell in
let item = self.sections[indexPath.section].items[indexPath.row]
return self.cellFactory.cellFor(item: item, parentView: tableView, indexPath: indexPath)
}
dataSource.tableTitleForHeaderInSection = { [unowned self] (section) -> String? in
return self.sections[section].headerTitle
}
dataSource.tableTitleForFooterInSection = { [unowned self] (section) -> String? in
return self.sections[section].footerTitle
}
return dataSource
}
}
public extension DataSourceProvider where CellFactory.Cell: UICollectionViewCell {
public var collectionViewDataSource: UICollectionViewDataSource {
if bridgedDataSource == nil {
bridgedDataSource = collectionViewBridgedDataSource()
}
return bridgedDataSource!
}
private func collectionViewBridgedDataSource() -> BridgedDataSource {
let dataSource = BridgedDataSource(
numberOfSections: { [unowned self] () -> Int in
return self.sections.count
},
numberOfItemsInSection: { [unowned self] (section) -> Int in
return self.sections[section].items.count
})
dataSource.collectionCellForItemAtIndexPath = { [unowned self] (collectionView, indexPath) -> UICollectionViewCell in
let item = self.sections[indexPath.section].items[indexPath.row]
return self.cellFactory.cellFor(item: item, parentView: collectionView, indexPath: indexPath)
}
// TODO: figure out supplementary views
// dataSource.collectionSupplementaryViewAtIndexPath = { [unowned self] (collectionView, kind, indexPath) -> UICollectionReusableView in
// let factory = self.supplementaryViewFactory!
// var item: Item?
// if indexPath.section < self.sections.count {
// if indexPath.item < self.sections[indexPath.section].items.count {
// item = self.sections[indexPath.section].items[indexPath.item]
// }
// }
//
// let view = factory.supplementaryViewFor(item: item, kind: kind, collectionView: collectionView, indexPath: indexPath)
// return factory.configureSupplementaryView(view, item: item, kind: kind, collectionView: collectionView, indexPath: indexPath)
// }
return dataSource
}
}
| mit |
PJayRushton/TeacherTools | TeacherTools/ProViewController.swift | 1 | 1718 | //
// ProViewController.swift
// TeacherTools
//
// Created by Parker Rushton on 12/2/16.
// Copyright © 2016 AppsByPJ. All rights reserved.
//
import UIKit
class ProViewController: UIViewController, AutoStoryboardInitializable {
@IBOutlet weak var upgradeBorderView: UIView!
fileprivate var sharedStore = TTProducts.store
var core = App.core
override func viewDidLoad() {
super.viewDidLoad()
preferredContentSize = CGSize(width: view.bounds.width * 0.6, height: view.bounds.height * 0.6)
AnalyticsHelper.logEvent(.proLaunched)
upgradeBorderView.layer.cornerRadius = 5
upgradeBorderView.backgroundColor = .appleBlue
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
core.add(subscriber: self)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
core.remove(subscriber: self)
}
@IBAction func dismissButtonPressed(_ sender: UIBarButtonItem) {
dismiss(animated: true, completion: nil)
}
@IBAction func upgradeViewPressed(_ sender: UITapGestureRecognizer) {
AnalyticsHelper.logEvent(.proPressed)
core.fire(command: GoPro())
}
@IBAction func restoreButtonPressed(_ sender: UIButton) {
AnalyticsHelper.logEvent(.restorePressed)
sharedStore.restorePurchases()
}
}
// MARK: - Subscriber
extension ProViewController: Subscriber {
func update(with state: AppState) {
guard let user = state.currentUser else { return }
if user.isPro {
dismiss(animated: true, completion: nil)
}
}
}
| mit |
kdawgwilk/Autobahn | Sources/AutobahnDescription/AutobahnDescription.swift | 1 | 4840 | #if os(Linux)
import Glibc
#else
import Darwin.C
#endif
import Foundation
@_exported import Actions
private extension Array {
var second: Element? {
guard count > 1 else {
return nil
}
return self[1]
}
}
/// Highway is the protocol which every highway should follow.
///
/// We suggest defining the highways as an enum like this:
///
/// ```Swift
/// enum MyHighways {
/// case build, test, deploy, release
///
/// var usage: String {
/// switch self {
/// case .build: return "This is how you should use build:…"
/// // … handle all cases
/// }
/// }
/// ```
public protocol Highway: RawRepresentable, Hashable where RawValue == String {
var usage: String { get }
}
public extension Highway {
var usage: String {
return "No usage specified for \(self)"
}
}
public final class Autobahn<H: Highway> {
public let version = "0.1.0"
private var highwayStart: Date
private var highwayEnd: Date?
private var beforeAllHandler: ((H) throws -> Void)?
private var highways = [H: () throws -> Void]()
private var dependings = [H: [H]]()
private var afterAllHandler: ((H) throws -> Void)?
private var onErrorHandler: ((String, Error) -> Void)?
// MARK: - Possible errors
public enum HighwayError: Error {
case noHighwaySpecified
case noValidHighwayName(String)
case highwayNotDefined(String)
}
// MARK: - Public Functions
public init(_ highwayType: H.Type) {
self.highwayStart = Date()
}
public func beforeAll(handler: @escaping (H) throws -> Void) -> Autobahn<H> {
precondition(beforeAllHandler == nil, "beforeAll declared more than once")
beforeAllHandler = handler
return self
}
public func highway(_ highway: H, dependsOn highways: [H], handler: @escaping () throws -> Void) -> Autobahn<H> {
return self.addHighway(highway, dependsOn: highways, handler: handler)
}
public func highway(_ highway: H, handler: @escaping () throws -> Void) -> Autobahn<H> {
return self.addHighway(highway, handler: handler)
}
public func highway(_ highway: H, dependsOn highways: [H]) -> Autobahn<H> {
return self.addHighway(highway, dependsOn: highways)
}
public func afterAll(handler: @escaping (H) throws -> Void) -> Autobahn<H> {
precondition(afterAllHandler == nil, "afterAll declared more than once")
afterAllHandler = handler
return self
}
public func onError(handler: @escaping (String, Error) -> Void) -> Autobahn<H> {
precondition(onErrorHandler == nil, "onError declared more than once")
onErrorHandler = handler
return self
}
public func drive() {
let args = CommandLine.arguments
let secondArg = args.second
do {
guard let raw = secondArg else {
throw HighwayError.noHighwaySpecified
}
guard let currentHighway = H(rawValue: raw) else {
throw HighwayError.noValidHighwayName(raw)
}
try self.beforeAllHandler?(currentHighway)
try self.driveHighway(currentHighway)
try self.afterAllHandler?(currentHighway)
} catch {
self.onErrorHandler?(secondArg ?? "", error)
}
highwayEnd = Date()
let duration = highwayEnd!.timeIntervalSince(highwayStart)
let rounded = Double(round(100 * duration) / 100)
print("Duration: \(rounded)s")
}
// MARK: - Private
private func addHighway(_ highway: H, dependsOn highways: [H]? = nil, handler: (() throws -> Void)? = nil) -> Autobahn<H> {
self.highways[highway] = handler
dependings[highway] = highways
return self
}
private func driveHighway(_ highway: H) throws {
if let dependings = self.dependings[highway] {
for dependingHighway in dependings {
guard let d = self.highways[dependingHighway] else {
throw HighwayError.highwayNotDefined(dependingHighway.rawValue)
}
printHeader(for: dependingHighway)
try d()
}
}
if let handler = highways[highway] {
printHeader(for: highway)
try handler()
}
}
private func printHeader(for highway: H) {
let count = highway.rawValue.count
print("-------------\(String(repeating: "-", count: count))----")
print("--- Highway: \(highway.rawValue) ---")
print("-------------\(String(repeating: "-", count: count))----")
}
}
public func sh(_ cmd: String, _ args: String...) throws {
try ShellCommand.run(cmd, args: args)
}
| mit |
AashiniSharma/Home-Living | Home&Living/SectionsforHome_Living.swift | 1 | 666 | //
// SectionsforHome_Living.swift
// Home&Living
//
// Created by Appinventiv on 18/02/17.
// Copyright © 2017 Appinventiv. All rights reserved.
//
import UIKit
class SectionsforHome_Living: UITableViewCell {
var tableIndexpath = IndexPath()
//MARK : IB Outlets
@IBOutlet weak var home_LivingCollectionView: UICollectionView!
@IBOutlet weak var brandsLabel: UILabel!
@IBOutlet weak var maskButtonOutlet: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func prepareForReuse() {
home_LivingCollectionView.reloadData()
}
}
| mit |
toddkramer/EmojiTools | EmojiTools/EmojiTools.swift | 1 | 4394 | //
// EmojiTools.swift
// EmojiTools
//
// Copyright © 2016 Todd Kramer.
//
// 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 String {
public func emojiString() -> String {
return String.emojiStringFromString(self)
}
public static func emojiStringFromString(inputString: String) -> String {
var token: dispatch_once_t = 0
var regex: NSRegularExpression? = nil
dispatch_once(&token) {
let pattern = "(:[a-z0-9-+_]+:)"
regex = try! NSRegularExpression(pattern: pattern, options: .CaseInsensitive)
}
var resultText = inputString
let matchRange = NSMakeRange(0, resultText.characters.count)
regex?.enumerateMatchesInString(resultText, options: .ReportCompletion, range: matchRange, usingBlock: { (result, _, _) -> Void in
guard let range = result?.range else { return }
if range.location != NSNotFound {
let emojiCode = (inputString as NSString).substringWithRange(range)
if let emojiCharacter = emojiShortCodes[emojiCode] {
resultText = resultText.stringByReplacingOccurrencesOfString(emojiCode, withString: emojiCharacter)
}
}
})
return resultText
}
public func containsEmoji() -> Bool {
return String.containsEmoji(self)
}
public static func containsEmoji(string: String) -> Bool {
for scalar in string.unicodeScalars {
if scalar.isEmoji() {
return true
}
}
return false
}
public func containsEmojiOnly(allowWhitespace: Bool = true) -> Bool {
return String.containsEmojiOnly(self, allowWhitespace: allowWhitespace)
}
public static func containsEmojiOnly(string: String, allowWhitespace: Bool = true) -> Bool {
var inputString = string
if allowWhitespace {
inputString = string.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).joinWithSeparator("")
}
for scalar in inputString.unicodeScalars {
if !scalar.isEmoji() {
return false
}
}
return true
}
}
extension UnicodeScalar {
public func isEmoji() -> Bool {
return UnicodeScalar.isEmoji(self)
}
public static func isEmoji(scalar: UnicodeScalar) -> Bool {
return emojis.unicodeScalars.contains(scalar)
}
}
public struct EmojiCodeSuggestion {
let code: String
let character: String
}
public struct EmojiTools {
public static func emojiCodeSuggestionsForSearchTerm(searchTerm: String) -> [EmojiCodeSuggestion] {
let keys = Array(emojiShortCodes.keys)
let filteredKeys = keys.filter { (key) -> Bool in
return key.containsString(searchTerm)
}.sort()
let unicodeCharacters = filteredKeys.map({ emojiShortCodes[$0]! })
var suggestions = [EmojiCodeSuggestion]()
if filteredKeys.count == 0 { return suggestions }
for index in 0...(filteredKeys.count - 1) {
let suggestion = EmojiCodeSuggestion(code: filteredKeys[index], character: unicodeCharacters[index])
suggestions.append(suggestion)
}
return suggestions
}
} | mit |
gregomni/swift | test/Generics/redundant_protocol_inheritance_via_concrete.swift | 3 | 318 | // RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures -requirement-machine-protocol-signatures=on 2>&1 | %FileCheck %s
protocol P {}
class C : P {}
// CHECK-LABEL: redundant_protocol_inheritance_via_concrete.(file).Q@
// CHECK-NEXT: Requirement signature: <Self where Self : C>
protocol Q : P, C {}
| apache-2.0 |
luanlzsn/EasyPass | EasyPass/Classes/Mine/Controller/MyAccountController.swift | 1 | 11137 | //
// MyAccountController.swift
// EasyPass
//
// Created by luan on 2017/7/5.
// Copyright © 2017年 luan. All rights reserved.
//
import UIKit
class MyAccountController: AntController,UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate,MyAccountTextField_Delegate {
@IBOutlet weak var tableView: UITableView!
var titleArray = ["个人头像","用户名","性别","专业","电话","邮箱"]
var contentArray = ["","","","","",""]
let placeholderArray = ["","","请选择性别","请选择专业","请输入手机号","请输入邮箱"]
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "保存", style: .plain, target: self, action: #selector(saveAccountInfo))
if AntManage.userModel?.nickName != nil {
contentArray.replaceSubrange(Range(1..<2), with: [AntManage.userModel?.nickName?.removingPercentEncoding ?? ""])
}
if AntManage.userModel?.sexStr != nil {
contentArray.replaceSubrange(Range(2..<3), with: [AntManage.userModel?.sexStr ?? ""])
}
if AntManage.userModel?.majorName != nil {
contentArray.replaceSubrange(Range(3..<4), with: [AntManage.userModel?.majorName ?? ""])
}
if AntManage.userModel?.phone != nil {
contentArray.replaceSubrange(Range(4..<5), with: [AntManage.userModel?.phone ?? ""])
}
if AntManage.userModel?.email != nil {
contentArray.replaceSubrange(Range(5..<6), with: [AntManage.userModel?.email ?? ""])
}
}
// MARK: - 保存个人信息
func saveAccountInfo() {
kWindow?.endEditing(true)
weak var weakSelf = self
var params = ["token":AntManage.userModel!.token!, "headImg":AntManage.userModel?.headImg ?? "", "userName":AntManage.userModel?.userName ?? "", "nickName":AntManage.userModel?.nickName ?? "", "phone":contentArray[4], "email":contentArray[5]] as [String : Any]
if !contentArray[2].isEmpty {
params["sex"] = (contentArray[2] == "男") ? 1 : 2
}
if !contentArray[3].isEmpty {
for model in AntManage.classifyList {
if model.name == contentArray[3] {
params["major"] = model.id!
break
}
}
}
AntManage.postRequest(path: "appAuth/updateAppUser", params: params, successResult: { (response) in
AntManage.userModel?.sexStr = weakSelf?.contentArray[2]
AntManage.userModel?.majorName = weakSelf?.contentArray[3]
AntManage.userModel?.phone = weakSelf?.contentArray[4]
AntManage.userModel?.email = weakSelf?.contentArray[5]
NotificationCenter.default.post(name: NSNotification.Name(kLoginStatusUpdate), object: nil)
UserDefaults.standard.setValue(NSKeyedArchiver.archivedData(withRootObject: AntManage.userModel!), forKey: kUserInfo)
UserDefaults.standard.synchronize()
AntManage.showDelayToast(message: "保存成功")
weakSelf?.navigationController?.popViewController(animated: true)
}, failureResult: {})
}
func uploadImage(image: UIImage) {
weak var weakSelf = self
AntManage.uploadWithPath(path: "upload/uploadImg", params: ["token":AntManage.userModel!.token!, "dir":"avators"], file: UIImageJPEGRepresentation(image, 0.1)!, successResult: { (response) in
AntManage.userModel?.headImg = response["url"] as? String
NotificationCenter.default.post(name: NSNotification.Name(kLoginStatusUpdate), object: nil)
UserDefaults.standard.setValue(NSKeyedArchiver.archivedData(withRootObject: AntManage.userModel!), forKey: kUserInfo)
UserDefaults.standard.synchronize()
weakSelf?.tableView.reloadData()
}, failureResult: {})
}
// MARK: - 选择图片
func selectPhoto() {
let sheet = UIAlertController(title: "选择图片来源", message: nil, preferredStyle: .actionSheet)
weak var weakSelf = self
sheet.addAction(UIAlertAction(title: "拍照", style: .default, handler: { (_) in
weakSelf?.takingPictures(sourceType: .camera)
}))
sheet.addAction(UIAlertAction(title: "相册", style: .default, handler: { (_) in
weakSelf?.takingPictures(sourceType: .photoLibrary)
}))
sheet.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
present(sheet, animated: true, completion: nil)
}
// MARK: - 选择性别
func selectSex() {
let actionSheet = UIAlertController(title: "选择性别", message: nil, preferredStyle: .actionSheet)
weak var weakSelf = self
actionSheet.addAction(UIAlertAction(title: "男", style: .default, handler: { (_) in
weakSelf?.contentArray.replaceSubrange(Range(2..<3), with: ["男"])
weakSelf?.tableView.reloadData()
}))
actionSheet.addAction(UIAlertAction(title: "女", style: .default, handler: { (_) in
weakSelf?.contentArray.replaceSubrange(Range(2..<3), with: ["女"])
weakSelf?.tableView.reloadData()
}))
actionSheet.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
present(actionSheet, animated: true, completion: nil)
}
// MARK: - 选择专业
func selectMajor() {
let actionSheet = UIAlertController(title: "选择专业", message: nil, preferredStyle: .actionSheet)
weak var weakSelf = self
for model in AntManage.classifyList {
actionSheet.addAction(UIAlertAction(title: model.name, style: .default, handler: { (_) in
weakSelf?.contentArray.replaceSubrange(Range(3..<4), with: [model.name!])
weakSelf?.tableView.reloadData()
}))
}
actionSheet.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
present(actionSheet, animated: true, completion: nil)
}
// MARK: - MyAccountTextField_Delegate
func textFieldEndEditing(string: String, row: Int) {
contentArray.replaceSubrange(Range(row..<(row + 1)), with: [string])
tableView.reloadData()
}
// MARK: - UITableViewDelegate,UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return titleArray.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == 0 {
return 75
} else {
return 45
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.01
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.01
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell: MyAccountHeadCell = tableView.dequeueReusableCell(withIdentifier: "MyAccountHeadCell", for: indexPath) as! MyAccountHeadCell
if AntManage.userModel?.headImg != nil {
cell.headImage.sd_setImage(with: URL(string: AntManage.userModel!.headImg!), placeholderImage: UIImage(named: "default_image"))
} else {
cell.headImage.image = UIImage(named: "head_defaults")
}
return cell
} else if indexPath.row < 4 {
var cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell")
if cell == nil {
cell = UITableViewCell(style: .value1, reuseIdentifier: "UITableViewCell")
cell?.selectionStyle = .none
cell?.textLabel?.font = UIFont.systemFont(ofSize: 14)
cell?.detailTextLabel?.font = UIFont.boldSystemFont(ofSize: 14)
}
cell?.textLabel?.text = titleArray[indexPath.row]
if contentArray[indexPath.row].isEmpty {
cell?.detailTextLabel?.text = placeholderArray[indexPath.row]
cell?.detailTextLabel?.textColor = UIColor(rgb: 0xcccccc)
} else {
cell?.detailTextLabel?.text = contentArray[indexPath.row]
cell?.detailTextLabel?.textColor = UIColor.black
}
return cell!
} else {
let cell: MyAccountTextFieldCell = tableView.dequeueReusableCell(withIdentifier: "MyAccountTextFieldCell", for: indexPath) as! MyAccountTextFieldCell
cell.delegate = self
cell.tag = indexPath.row
cell.titleLabel.text = titleArray[indexPath.row]
cell.textField.text = contentArray[indexPath.row]
cell.textField.placeholder = placeholderArray[indexPath.row]
return cell
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
selectPhoto()
} else if indexPath.row == 2 {
selectSex()
} else if indexPath.row == 3 {
selectMajor()
}
}
func takingPictures(sourceType: UIImagePickerControllerSourceType) {
if sourceType == .camera {
if !UIImagePickerController.isSourceTypeAvailable(sourceType) {
let alert = UIAlertController(title: "提示", message: "无法访问摄像头!", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "确定", style: .cancel, handler: nil))
present(alert, animated: true, completion: nil)
return;
}
}
let picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = true
picker.sourceType = sourceType
navigationController?.present(picker, animated: true, completion: nil)
}
//MARK: UIImagePickerControllerDelegate
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
weak var weakSelf = self
picker.dismiss(animated: true) {
let image = info[UIImagePickerControllerEditedImage]
weakSelf?.uploadImage(image: image as! UIImage)
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true) {
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit |
DevZheng/LeetCode | Array/FirstMissingPositive.swift | 1 | 1052 | //
// FirstMissingPositive.swift
// A
//
// Created by zyx on 2017/6/29.
// Copyright © 2017年 bluelive. All rights reserved.
//
import Foundation
/**
Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.
Your algorithm should run in O(n) time and uses constant space.
*/
class FirstMissingPositive {
func firstMissingPositive(_ nums: [Int]) -> Int {
var i = 0, nums = nums
while i < nums.count {
let num = nums[i]
guard (num > 0 && num < nums.count) && nums[num - 1] != num else {
i += 1
continue
}
let temp = nums[num - 1]
nums[i] = temp
nums[num - 1] = num
}
for (i, value) in nums.enumerated() {
if i != value - 1 {
return i + 1
}
}
return nums.count + 1
}
}
| mit |
EasySwift/EasySwift | Carthage/Checkouts/YXJPageControl/YXJPageController/AppDelegate.swift | 4 | 2184 | //
// AppDelegate.swift
// YXJPageController
//
// Created by yuanxiaojun on 2016/11/1.
// Copyright © 2016年 袁晓钧. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| apache-2.0 |
thomasvl/swift-protobuf | Sources/SwiftProtobufCore/BinaryDecodingError.swift | 3 | 1738 | // Sources/SwiftProtobuf/BinaryDecodingError.swift - Protobuf binary decoding errors
//
// Copyright (c) 2014 - 2017 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Protobuf binary format decoding errors
///
// -----------------------------------------------------------------------------
/// Describes errors that can occur when decoding a message from binary format.
public enum BinaryDecodingError: Error {
/// Extraneous data remained after decoding should have been complete.
case trailingGarbage
/// The decoder unexpectedly reached the end of the data before it was
/// expected.
case truncated
/// A string field was not encoded as valid UTF-8.
case invalidUTF8
/// The binary data was malformed in some way, such as an invalid wire format
/// or field tag.
case malformedProtobuf
/// The definition of the message or one of its nested messages has required
/// fields but the binary data did not include values for them. You must pass
/// `partial: true` during decoding if you wish to explicitly ignore missing
/// required fields.
case missingRequiredFields
/// An internal error happened while decoding. If this is ever encountered,
/// please file an issue with SwiftProtobuf with as much details as possible
/// for what happened (proto definitions, bytes being decoded (if possible)).
case internalExtensionError
/// Reached the nesting limit for messages within messages while decoding.
case messageDepthLimit
}
| apache-2.0 |
mkoehnke/WKZombie | Example/Example iOS/ProfileViewController.swift | 1 | 2180 | //
// ViewController.swift
//
// Copyright (c) 2015 Mathias Koehnke (http://www.mathiaskoehnke.de)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import WKZombie
class ProfileViewController: UITableViewController {
var items : [HTMLTableColumn]?
var snapshots : [Snapshot]?
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.hidesBackButton = true
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items?.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let item = items?[indexPath.row].children()?.first as HTMLElement?
cell.textLabel?.text = item?.text
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "snapshotSegue" {
let vc = segue.destination as? SnapshotViewController
vc?.snapshots = snapshots
}
}
}
| mit |
kickstarter/Kickstarter-Prelude | Prelude-UIKit/lenses/NSTextContainerLenses.swift | 1 | 443 | import Prelude
import UIKit
public protocol NSTextContainerProtocol: KSObjectProtocol {
var lineFragmentPadding: CGFloat { get set }
}
extension NSTextContainer: NSTextContainerProtocol {}
public extension LensHolder where Object: NSTextContainerProtocol {
public var lineFragmentPadding: Lens<Object, CGFloat> {
return Lens(
view: { $0.lineFragmentPadding },
set: { $1.lineFragmentPadding = $0; return $1 }
)
}
}
| apache-2.0 |
wayfinders/WRCalendarView | WRCalendarView/Helpers/UIColorExtention.swift | 1 | 785 | //
// UIColorExtention.swift
// Pods
//
// Created by wayfinder on 2017. 4. 18..
//
//
import Foundation
extension UIColor {
convenience init(hex: Int) {
self.init(hex: hex, a: 1.0)
}
convenience init(hex: Int, a: CGFloat) {
self.init(r: (hex >> 16) & 0xff, g: (hex >> 8) & 0xff, b: hex & 0xff, a: a)
}
convenience init(r: Int, g: Int, b: Int) {
self.init(r: r, g: g, b: b, a: 1.0)
}
convenience init(r: Int, g: Int, b: Int, a: CGFloat) {
self.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: a)
}
convenience init?(hexString: String) {
guard let hex = hexString.hex else {
return nil
}
self.init(hex: hex)
}
}
| mit |
ShaneQi/zeg_bot | Sources/FaceDetection.swift | 1 | 1094 | //
// FaceDetection.swift
// ZEGBot
//
// Created by Shane Qi on 7/5/18.
//
import Foundation
func faceDetectionRequestBody(withImage data: Data) -> Data {
return """
{
"requests": [
{
"image": {
"content": "\(String(data: data.base64EncodedData(), encoding: .utf8) ?? "")"
},
"features": [
{
"type": "FACE_DETECTION"
}
]
}
]
}
""".data(using: .utf8) ?? Data()
}
struct FaceDetectionResponse: Decodable {
let responses: [FaceAnnotations]
private enum CodingKeys: String, CodingKey {
case responses
}
}
struct FaceAnnotations: Decodable {
let hasAnything: Bool
private enum CodingKeys: String, CodingKey {
case faceAnnotations
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.hasAnything = container.contains(.faceAnnotations)
}
}
func hasFacesInResponse(_ data: Data) -> Bool {
do {
let resposne = try JSONDecoder().decode(FaceDetectionResponse.self, from: data)
return resposne.responses.first?.hasAnything ?? false
} catch {
return false
}
}
| apache-2.0 |
magicien/GLTFSceneKit | Sources/GLTFSceneKit/schema/GLTFAnimationSampler.swift | 1 | 1396 | //
// GLTFAnimationSampler.swift
//
// Animation Sampler
// Combines input and output accessors with an interpolation algorithm to define a keyframe graph (but not its target).
//
import Foundation
struct GLTFAnimationSampler: GLTFPropertyProtocol {
/** The index of an accessor containing keyframe input values, e.g., time. That accessor must have componentType `FLOAT`. The values represent time in seconds with `time[0] >= 0.0`, and strictly increasing values, i.e., `time[n + 1] > time[n]`. */
let input: GLTFGlTFid
let _interpolation: String?
/** Interpolation algorithm. */
var interpolation: String {
get { return self._interpolation ?? "LINEAR" }
}
/** The index of an accessor containing keyframe output values. When targeting TRS target, the `accessor.componentType` of the output values must be `FLOAT`. When targeting morph weights, the `accessor.componentType` of the output values must be `FLOAT` or normalized integer where each output element stores values with a count equal to the number of morph targets. */
let output: GLTFGlTFid
/** Dictionary object with extension-specific objects. */
let extensions: GLTFExtension?
/** Application-specific data. */
let extras: GLTFExtras?
private enum CodingKeys: String, CodingKey {
case input
case _interpolation = "interpolation"
case output
case extensions
case extras
}
}
| mit |
fulldecent/FDChessboardView | Tests/FDChessboardViewTests/XCTestManifests.swift | 1 | 166 | import XCTest
#if !canImport(ObjectiveC)
public func allTests() -> [XCTestCaseEntry] {
return [
testCase(FDChessboardViewTests.allTests),
]
}
#endif
| mit |
FirasAKAK/FInAppNotifications | FNotificationManager.swift | 1 | 12574 | //
// FNotificationManager.swift
// FInAppNotification
//
// Created by Firas Al Khatib Al Khalidi on 7/4/17.
// Copyright © 2017 Firas Al Khatib Al Khalidi. All rights reserved.
//
import UIKit
class FNotificationManager: NSObject {
static let shared = FNotificationManager()
fileprivate var dismissalPanGestureRecognizer: UIPanGestureRecognizer!
fileprivate var tapGestureRecognizer : UITapGestureRecognizer!
private var notificationTimer : Timer!
private var settings : FNotificationSettings!
var pauseBetweenNotifications : TimeInterval = 1
private var notificationView : FNotificationView = UINib(nibName: "FNotificationView",
bundle: nil).instantiate(withOwner: nil,
options: nil).first as! FNotificationView
private var tapCompletion : (()-> Void)?
private var notificationQueue : [(FNotification, FNotificationExtensionView?)] = []
private override init(){
super.init()
set(newSettings: .defaultStyle)
dismissalPanGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePan(gesture:)))
tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap(gesture:)))
dismissalPanGestureRecognizer.delegate = self
tapGestureRecognizer.delegate = self
notificationView.addGestureRecognizer(dismissalPanGestureRecognizer)
notificationView.addGestureRecognizer(tapGestureRecognizer)
}
@objc func handlePan(gesture: UIPanGestureRecognizer){
switch gesture.state {
case .began:
if notificationTimer != nil{
notificationTimer.invalidate()
notificationTimer = nil
}
case .changed:
var translation = gesture.translation(in: notificationView)
if notificationView.extensionView != nil && !notificationView.isExtended{
translation.y = translation.y - FNotificationView.bounceOffset
notificationView.frame.origin.y = translation.y <= 0 ? translation.y : 0
if translation.y > 0{
var notificationHeight = FNotificationView.heightWithStatusBar
if UIApplication.shared.isStatusBarHidden{
notificationHeight = FNotificationView.heightWithoutStatusBar
}
let extensionViewHeight: CGFloat = notificationView.extensionView!.height
let fullHeight: CGFloat = notificationHeight + translation.y
notificationView.frame.size.height = fullHeight <= notificationHeight + extensionViewHeight + 16 ? fullHeight : notificationHeight + extensionViewHeight + 16
}
}
else{
translation.y = translation.y - FNotificationView.bounceOffset
notificationView.frame.origin.y = translation.y <= 0 ? translation.y : 0
}
case .ended:
if gesture.velocity(in: notificationView).y < 0{
notificationTimerExpired()
}
else{
notificationView.isExtended = true
notificationView.moveToFinalPosition(animated: true, completion: nil)
}
default:
break
}
}
@objc func handleTap(gesture: UITapGestureRecognizer){
guard notificationView.frame.origin.y == -20 else{
return
}
tapCompletion?()
notificationTimerExpired()
}
func set(newSettings settings: FNotificationSettings){
notificationView.backgroundView = settings.backgroundView
notificationView.titleLabel.textColor = settings.titleTextColor
notificationView.subtitleLabel.textColor = settings.subtitleTextColor
notificationView.imageView.layer.cornerRadius = settings.imageViewCornerRadius
notificationView.titleLabel.font = settings.titleFont
notificationView.subtitleLabel.font = settings.subtitleFont
notificationView.backgroundColor = settings.backgroundColor
}
func show(audioPlayerNotificationWithTitleText titleText: String = "", subtitleText: String = "", image: UIImage? = nil, andDuration duration: TimeInterval = 5, extensionAudioUrl: String, notificationWasTapped: (()-> Void)?, didPlayRecording: (()-> Void)?){
let audioPlayerExtension = UINib(nibName: "FNotificationVoicePlayerExtensionView", bundle: nil).instantiate(withOwner: nil, options: nil).first as! FNotificationVoicePlayerExtensionView
audioPlayerExtension.dataUrl = extensionAudioUrl
audioPlayerExtension.didPlayRecording = didPlayRecording
guard notificationView.superview == nil else{
notificationQueue.append((FNotification(withTitleText: titleText, subtitleText: subtitleText, image: image, duration: duration, notificationWasTapped: notificationWasTapped), audioPlayerExtension))
return
}
notificationView.extensionView = audioPlayerExtension
defaultShow(withTitleText: titleText,
subtitleText: subtitleText,
image: image,
andDuration: duration,
notificationWasTapped: notificationWasTapped)
}
func show(imageNotificationWithTitleText titleText: String = "", subtitleText: String = "", image: UIImage? = nil, andDuration duration: TimeInterval = 5, extensionImage: UIImage, notificationWasTapped: (()-> Void)?){
let imageViewExtentionView = FNotificationImageExtensionView()
imageViewExtentionView.imageView.image = extensionImage
guard notificationView.superview == nil else{
notificationQueue.append((FNotification(withTitleText: titleText, subtitleText: subtitleText, image: image, duration: duration, notificationWasTapped: notificationWasTapped), imageViewExtentionView))
return
}
notificationView.extensionView = imageViewExtentionView
defaultShow(withTitleText: titleText,
subtitleText: subtitleText,
image: image,
andDuration: duration,
notificationWasTapped: notificationWasTapped)
}
func show(textFieldNotificationWithTitleText titleText: String = "", subtitleText: String = "", image: UIImage? = nil, andDuration duration: TimeInterval = 5, notificationWasTapped: (()-> Void)?, accessoryTextFieldButtonPressed: ((_ text: String)-> Void)?){
let textFieldExtensionView = UINib(nibName: "FNotificationTextFieldExtensionView", bundle: nil).instantiate(withOwner: nil, options: nil).first as! FNotificationTextFieldExtensionView
textFieldExtensionView.sendButtonPressed = accessoryTextFieldButtonPressed
guard notificationView.superview == nil else{
notificationQueue.append((FNotification(withTitleText: titleText, subtitleText: subtitleText, image: image, duration: duration, notificationWasTapped: notificationWasTapped), textFieldExtensionView))
return
}
notificationView.extensionView = textFieldExtensionView
defaultShow(withTitleText: titleText,
subtitleText: subtitleText,
image: image,
andDuration: duration,
notificationWasTapped: notificationWasTapped)
}
func show(withTitleText titleText: String = "", subtitleText: String = "", image: UIImage? = nil, andDuration duration: TimeInterval = 5, notificationWasTapped: (()-> Void)?){
guard notificationView.superview == nil else{
notificationQueue.append((FNotification(withTitleText: titleText, subtitleText: subtitleText, image: image, duration: duration, notificationWasTapped: notificationWasTapped), nil))
return
}
notificationView.extensionView = nil
defaultShow(withTitleText: titleText,
subtitleText: subtitleText,
image: image,
andDuration: duration,
notificationWasTapped: notificationWasTapped)
}
func show(notification: FNotification, withExtensionView extensionView: FNotificationExtensionView, notificationWasTapped: (()-> Void)?, extensionViewInteractionHandlers:(()-> Void)...){
guard notificationView.superview == nil else{
notificationQueue.append((notification, nil))
return
}
notificationView.extensionView = extensionView
defaultShow(withTitleText: notification.titleText,
subtitleText: notification.subtitleText,
image: notification.image,
andDuration: notification.duration,
notificationWasTapped: notificationWasTapped)
}
func defaultShow(withTitleText titleText: String = "", subtitleText: String = "", image: UIImage? = nil, andDuration duration: TimeInterval = 5, notificationWasTapped: (()-> Void)?){
notificationView.moveToInitialPosition(animated: false, completion: nil)
notificationView.titleLabel.text = titleText
notificationView.subtitleLabel.text = subtitleText
notificationView.imageView.image = image
tapCompletion = notificationWasTapped
if notificationTimer != nil{
self.notificationTimer.invalidate()
self.notificationTimer = nil
}
if UIApplication.shared.isStatusBarHidden{
notificationView.topConstraint.constant = FNotificationView.topConstraintWithoutStatusBar
notificationView.frame.size.height = FNotificationView.heightWithoutStatusBar
notificationView.layoutIfNeeded()
}
else{
notificationView.topConstraint.constant = FNotificationView.topConstraintWithStatusBar
notificationView.frame.size.height = FNotificationView.heightWithStatusBar
notificationView.layoutIfNeeded()
}
guard case let window?? = UIApplication.shared.delegate?.window else{
return
}
window.addSubview(notificationView)
notificationView.moveToFinalPosition(animated: true) {
if self.notificationTimer != nil{
self.notificationTimer.invalidate()
self.notificationTimer = nil
}
self.notificationTimer = Timer.scheduledTimer(timeInterval: duration,
target: self,
selector: #selector(self.notificationTimerExpired),
userInfo: nil,
repeats: false)
}
}
private func dequeueAndDisplayNotification(){
guard notificationQueue.count != 0 else{
return
}
let notificationTuple = notificationQueue.removeFirst()
notificationView.extensionView = notificationTuple.1
defaultShow(withTitleText: notificationTuple.0.titleText, subtitleText: notificationTuple.0.subtitleText, image: notificationTuple.0.image, andDuration: notificationTuple.0.duration, notificationWasTapped: notificationTuple.0.notificationWasTapped)
}
@objc private func notificationTimerExpired(){
notificationView.moveToInitialPosition(animated: true){
self.notificationView.removeFromSuperview()
self.notificationView.extensionView = nil
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + FNotificationManager.shared.pauseBetweenNotifications, execute: {
self.dequeueAndDisplayNotification()
})
}
}
func removeCurrentNotification(){
notificationTimerExpired()
}
func removeAllNotifications(){
notificationQueue = []
notificationTimerExpired()
}
}
extension FNotificationManager: UIGestureRecognizerDelegate{
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return false
}
}
| mit |
vigneshuvi/SwiftLoggly | Package.swift | 1 | 211 | //
// Package.swift
// SwiftLoggly
//
// Created by Vignesh on 30/01/17.
// Copyright © 2017 vigneshuvi. All rights reserved.
//
import PackageDescription
let package = Package(
name: "SwiftLoggly"
)
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.