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 |
---|---|---|---|---|---|
xin-wo/kankan | kankan/kankan/Class/Home/Controller/HomeAnimViewController.swift | 1 | 459 | //
// HomeAnimViewController.swift
// kankan
//
// Created by Xin on 16/10/31.
// Copyright © 2016年 王鑫. All rights reserved.
//
import UIKit
class HomeAnimViewController: HomeBaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
url = homeAnimationUrl
loadData()
configUI()
moreUrl = homeAllAnimUrl
categoryString = "动漫片库"
loadMoreData()
}
}
| mit |
radex/swift-compiler-crashes | crashes-fuzzing/09972-swift-typechecker-conformstoprotocol.swift | 11 | 239 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class a<T{func b{}struct b<T where g:a{func b{}}func b(let g:AnyObject | mit |
dnseitz/YAPI | YAPI/YAPI/V2/V2_CommonParameters.swift | 1 | 431 | //
// CommonParameters.swift
// YAPI
//
// Created by Daniel Seitz on 9/12/16.
// Copyright © 2016 Daniel Seitz. All rights reserved.
//
import Foundation
enum YelpCountryCodeParameter : String {
case unitedStates = "US"
case unitedKingdom = "GB"
case canada = "CA"
}
extension YelpCountryCodeParameter : YelpParameter {
var key: String {
return "cc"
}
var value: String {
return self.rawValue
}
}
| mit |
Hodglim/hacking-with-swift | Project-14/WhackAPenguin/GameViewController.swift | 1 | 1272 | //
// GameViewController.swift
// WhackAPenguin
//
// Created by Darren Hodges on 27/10/2015.
// Copyright (c) 2015 Darren Hodges. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController
{
override func viewDidLoad()
{
super.viewDidLoad()
if let scene = GameScene(fileNamed:"GameScene")
{
// Configure the view.
let skView = self.view as! SKView
//skView.showsFPS = true
//skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
override func shouldAutorotate() -> Bool
{
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask
{
if UIDevice.currentDevice().userInterfaceIdiom == .Phone
{
return .AllButUpsideDown
}
else
{
return .All
}
}
override func prefersStatusBarHidden() -> Bool
{
return true
}
}
| mit |
GeekSpeak/GeekSpeak-Show-Timer | GeekSpeak Show Timer/BreakCount-3/Timer+StatePreservation.swift | 2 | 5177 | import UIKit
extension Timer: NSCoding {
// MARK: -
// MARK: State Preservation and Restoration
convenience init?(coder aDecoder: NSCoder) {
self.init()
decodeWithCoder(coder: aDecoder)
}
func decodeWithCoder(coder aDecoder: NSCoder) {
let decodedObject = aDecoder.decodeObject(forKey: Constants.UUIDId) as! UUID
uuid = decodedObject
demoTimings = aDecoder.decodeBool(forKey: Constants.DemoId)
let countingState = aDecoder.decodeCInt(forKey: Constants.StateId)
switch countingState {
case 1:
_state = .Ready
case 2:
_state = .Counting
case 3:
_state = .Paused
default:
_state = .Ready
}
let countingStartTimeDecoded =
aDecoder.decodeDouble(forKey: Constants.CountingStartTimeId)
if countingStartTimeDecoded == DBL_MAX {
countingStartTime = .none
} else {
countingStartTime = countingStartTimeDecoded
}
timing = ShowTiming()
let int = aDecoder.decodeCInt(forKey: Constants.PhaseId)
let phase: ShowPhase
switch int {
case 1: phase = .PreShow
case 2: phase = .Section1
case 3: phase = .Break1
case 4: phase = .Section2
case 5: phase = .Break2
case 6: phase = .Section3
case 7: phase = .PostShow
default: phase = .PreShow
}
timing.phase = phase
timing.durations.preShow =
aDecoder.decodeDouble(forKey: Constants.Durations.PreShowId)
timing.durations.section1 =
aDecoder.decodeDouble(forKey: Constants.Durations.Section1Id)
timing.durations.section2 =
aDecoder.decodeDouble(forKey: Constants.Durations.Section2Id)
timing.durations.section3 =
aDecoder.decodeDouble(forKey: Constants.Durations.Section3Id)
timing.durations.break1 =
aDecoder.decodeDouble(forKey: Constants.Durations.Break1Id)
timing.durations.break2 =
aDecoder.decodeDouble(forKey: Constants.Durations.Break2Id)
timing.timeElapsed.preShow =
aDecoder.decodeDouble(forKey: Constants.ElapsedTime.PreShowId)
timing.timeElapsed.section1 =
aDecoder.decodeDouble(forKey: Constants.ElapsedTime.Section1Id)
timing.timeElapsed.section2 =
aDecoder.decodeDouble(forKey: Constants.ElapsedTime.Section2Id)
timing.timeElapsed.section3 =
aDecoder.decodeDouble(forKey: Constants.ElapsedTime.Section3Id)
timing.timeElapsed.break1 =
aDecoder.decodeDouble(forKey: Constants.ElapsedTime.Break1Id)
timing.timeElapsed.break2 =
aDecoder.decodeDouble(forKey: Constants.ElapsedTime.Break2Id)
timing.timeElapsed.postShow =
aDecoder.decodeDouble(forKey: Constants.ElapsedTime.PostShowId)
incrementTimer()
}
func encode(with aCoder: NSCoder) {
aCoder.encode(uuid, forKey: Constants.UUIDId)
aCoder.encode(demoTimings, forKey: Constants.DemoId)
switch _state {
case .Ready:
aCoder.encodeCInt(1, forKey: Constants.StateId)
case .Counting:
aCoder.encodeCInt(2, forKey: Constants.StateId)
case .Paused:
aCoder.encodeCInt(3, forKey: Constants.StateId)
case .PausedAfterComplete:
aCoder.encodeCInt(4, forKey: Constants.StateId)
case .CountingAfterComplete:
aCoder.encodeCInt(5, forKey: Constants.StateId)
}
if let countingStartTime = countingStartTime {
aCoder.encode( countingStartTime,
forKey: Constants.CountingStartTimeId)
} else {
aCoder.encode( DBL_MAX,
forKey: Constants.CountingStartTimeId)
}
aCoder.encode(demoTimings, forKey: Constants.UseDemoDurations)
let int: Int32
switch timing.phase {
case .PreShow: int = 1
case .Section1: int = 2
case .Break1: int = 3
case .Section2: int = 4
case .Break2: int = 5
case .Section3: int = 6
case .PostShow: int = 7
}
aCoder.encodeCInt(int, forKey: Constants.PhaseId)
let d = timing.durations
aCoder.encode(d.preShow, forKey: Constants.Durations.PreShowId)
aCoder.encode(d.section1, forKey: Constants.Durations.Section1Id)
aCoder.encode(d.break1, forKey: Constants.Durations.Break1Id)
aCoder.encode(d.section2, forKey: Constants.Durations.Section2Id)
aCoder.encode(d.break2, forKey: Constants.Durations.Break2Id)
aCoder.encode(d.section3, forKey: Constants.Durations.Section3Id)
let t = timing.timeElapsed
aCoder.encode(t.preShow, forKey: Constants.ElapsedTime.PreShowId)
aCoder.encode(t.section1, forKey: Constants.ElapsedTime.Section1Id)
aCoder.encode(t.break1, forKey: Constants.ElapsedTime.Break1Id)
aCoder.encode(t.section2, forKey: Constants.ElapsedTime.Section2Id)
aCoder.encode(t.break2, forKey: Constants.ElapsedTime.Break2Id)
aCoder.encode(t.section3, forKey: Constants.ElapsedTime.Section3Id)
aCoder.encode(t.postShow, forKey: Constants.ElapsedTime.PostShowId)
}
}
| mit |
CalvinChina/Demo | Swift3Demo/Swift3Demo/AnimationWithCollisionQuartzCore/CollisionQuartzCoreViewController.swift | 1 | 3741 | //
// CollisionQuartzCoreViewController.swift
// Swift3Demo
//
// Created by pisen on 16/9/19.
// Copyright © 2016年 丁文凯. All rights reserved.
//
import UIKit
class CollisionQuartzCoreViewController: UIViewController,UICollisionBehaviorDelegate {
@IBOutlet weak var gravity: UIButton!
@IBOutlet weak var push: UIButton!
@IBOutlet weak var attachment: UIButton!
var collision:UICollisionBehavior!
var animator = UIDynamicAnimator()
var attachmentBehavior: UIAttachmentBehavior? = nil
@IBAction func gravityClick(_ sender :UIButton){
animator.removeAllBehaviors()
let gravity_t = UIGravityBehavior(items:[self.gravity,self.push,self.attachment])
animator.addBehavior(gravity_t)
collision = UICollisionBehavior(items:[self.gravity ,self.push,self.attachment])
collision.translatesReferenceBoundsIntoBoundary = true
animator.addBehavior(collision)
}
@IBAction func push(_ sender:AnyObject){
animator.removeAllBehaviors()
let push_t = UIPushBehavior(items:[self.gravity,self.push,self.attachment], mode:.instantaneous)
push_t.magnitude = 2
animator.addBehavior(push_t)
collision = UICollisionBehavior(items:[self.gravity ,self.push,self.attachment])
collision.translatesReferenceBoundsIntoBoundary = true
animator.addBehavior(collision)
}
@IBAction func attachment(_ sender:AnyObject){
animator.removeAllBehaviors()
let anchorPoint = CGPoint(x:self.attachment.center.x ,y:self.attachment.center.y)
attachmentBehavior = UIAttachmentBehavior(item:self.attachment ,attachedToAnchor:anchorPoint)
attachmentBehavior!.frequency = 0.5
attachmentBehavior!.damping = 2
attachmentBehavior!.length = 20
animator.addBehavior(attachmentBehavior!)
collision = UICollisionBehavior(items:[self.gravity ,self.push,self.attachment])
collision.translatesReferenceBoundsIntoBoundary = true
animator.addBehavior(collision)
}
@IBAction func handleAttachment(_ sender: UIPanGestureRecognizer) {
if((attachmentBehavior) != nil){
attachmentBehavior!.anchorPoint = sender.location(in: self.view)
}
}
override func viewDidLoad() {
super.viewDidLoad()
animator = UIDynamicAnimator(referenceView: self.view)
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let max: CGRect = UIScreen.main.bounds
let snap1 = UISnapBehavior(item: self.gravity, snapTo: CGPoint(x: max.size.width/2, y: max.size.height/2 - 50))
let snap2 = UISnapBehavior(item: self.push, snapTo: CGPoint(x: max.size.width/2, y: max.size.height/2 ))
let snap3 = UISnapBehavior(item: self.attachment, snapTo: CGPoint(x: max.size.width/2, y: max.size.height/2 + 50))
snap1.damping = 1
snap2.damping = 2
snap3.damping = 4
animator.addBehavior(snap1)
animator.addBehavior(snap2)
animator.addBehavior(snap3)
}
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 |
Mobilette/MobiletteDashboardiOS | MobiletteDashboardIOS/Classes/Modules/Login/MobiletteDashboardIOSLoginTrelloNetworkController.swift | 1 | 1727 | //
// MobiletteDashboardIOSLoginTrelloNetworkController.swift
// MobiletteDashboardIOS
//
// Mobilette template version 1.0
//
// Created by Benaly Issouf M'sa on 06/03/16.
// Copyright © 2016 Mobilette. All rights reserved.
//
import Foundation
import PromiseKit
// import ObjectMapper
class MobiletteDashboardIOSLoginTrelloNetworkController: MobiletteDashboardIOSLoginTrelloNetworkProtocol
{
// MARK: - Property
// MARK: - Life cycle
// MARK: - Network
func userTrelloAuthentification() -> Promise<String>
{
return Promise<String> { fullfil, reject in
// To do: perform trello authentification
}
}
// MARK: - Error
enum MobiletteDashboardIOSLoginTrelloNetworkControllerError
{
case Mapping(String)
var code: Int {
switch self {
case .Mapping:
return 500
}
}
var domain: String {
return "NetworkControllerDomain"
}
var description: String {
switch self {
case .Mapping:
return "Mapping Error."
}
}
var reason: String {
switch self {
case .Mapping(let JSONString):
return "Response string can not be mapped to the object.\nString: \(JSONString)."
}
}
var error: NSError {
let userInfo = [
NSLocalizedDescriptionKey: self.description,
NSLocalizedFailureReasonErrorKey: self.reason
]
return NSError(domain: self.domain, code: self.code, userInfo: userInfo)
}
}
} | mit |
modocache/FutureKit | FutureKit/Synchronization.swift | 3 | 22522 | //
// NSData-Ext.swift
// FutureKit
//
// Created by Michael Gray on 4/21/15.
// 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
// this adds some missing feature that we don't have with normal dispatch_queue_t
// like .. what DispatchQueue am I currently running in?
// Add assertions to make sure logic is always running on a specific Queue
// Don't know what sort of synchronization is perfect?
// try them all!
// testing different strategys may result in different performances (depending on your implementations)
public protocol SynchronizationProtocol {
init()
// modify your object. The block() code may run asynchronously, but doesn't return any result
func modify(block:() -> Void)
// modify your shared object and return some value in the process
// the "done" block could execute inside ANY thread/queue so care should be taken.
// will try NOT to block the current thread (for Barrier/Queue strategies)
// Lock strategies may still end up blocking the calling thread.
func modifyAsync<_ANewType>(block:() -> _ANewType, done : (_ANewType) -> Void)
// modify your container and retrieve a result/element to the same calling thread
// current thread will block until the modifyBlock is done running.
func modifySync<_ANewType>(block:() -> _ANewType) -> _ANewType
// read your object. The block() code may run asynchronously, but doesn't return any result
// if you need to read the block and return a result, use readAsync/readSync
func read(block:() -> Void)
// perform a readonly query of your shared object and return some value/element T
// current thread may block until the read block is done running.
// do NOT modify your object inside this block
func readSync<_ANewType>(block:() -> _ANewType) -> _ANewType
// perform a readonly query of your object and return some value/element of type _ANewType.
// the results are delivered async inside the done() block.
// the done block is NOT protected by the synchronization - do not modify your shared data inside the "done:" block
// the done block could execute inside ANY thread/queue so care should be taken
// do NOT modify your object inside this block
func readAsync<_ANewType>(block:() -> _ANewType, done : (_ANewType) -> Void)
}
public enum SynchronizationType {
case BarrierConcurrent
case BarrierSerial
case SerialQueue
case NSObjectLock
case NSLock
case NSRecursiveLock
case OSSpinLock
func lockObject() -> SynchronizationProtocol {
switch self {
case BarrierConcurrent:
return QueueBarrierSynchronization(type: DISPATCH_QUEUE_CONCURRENT)
case BarrierSerial:
return QueueBarrierSynchronization(type: DISPATCH_QUEUE_SERIAL)
case SerialQueue:
return QueueSerialSynchronization()
case NSObjectLock:
return NSObjectLockSynchronization()
case NSLock:
return NSLockSynchronization()
case NSRecursiveLock:
return NSRecursiveLockSynchronization()
case OSSpinLock:
return OSSpinLockSynchronization()
}
}
}
let DispatchQueuePoolIsActive = false
class DispatchQueuePool {
let attr : dispatch_queue_attr_t
let qos : qos_class_t
let relative_priority : Int32
let syncObject : SynchronizationProtocol
var queues : [dispatch_queue_t] = []
init(a : dispatch_queue_attr_t, qos q: qos_class_t = QOS_CLASS_DEFAULT, relative_priority p :Int32 = 0) {
self.attr = a
self.qos = q
self.relative_priority = p
let c_attr = dispatch_queue_attr_make_with_qos_class(self.attr,self.qos, self.relative_priority)
let synchObjectBarrierQueue = dispatch_queue_create("DispatchQueuePool-Root", c_attr)
self.syncObject = QueueBarrierSynchronization(queue: synchObjectBarrierQueue)
}
final func createNewQueue() -> dispatch_queue_t {
let c_attr = dispatch_queue_attr_make_with_qos_class(self.attr,self.qos, self.relative_priority)
return dispatch_queue_create(nil, c_attr)
}
func getQueue() -> dispatch_queue_t {
if (DispatchQueuePoolIsActive) {
let queue = self.syncObject.modifySync { () -> dispatch_queue_t? in
if let q = self.queues.last {
self.queues.removeLast()
return q
}
else {
return nil
}
}
if let q = queue {
return q
}
}
return self.createNewQueue()
}
func recycleQueue(q: dispatch_queue_t) {
if (DispatchQueuePoolIsActive) {
self.syncObject.modify { () -> Void in
self.queues.append(q)
}
}
}
func flushQueue(keepCapacity : Bool = false) {
self.syncObject.modify { () -> Void in
self.queues.removeAll(keepCapacity: keepCapacity)
}
}
}
/* public var serialQueueDispatchPool = DispatchQueuePool(a: DISPATCH_QUEUE_SERIAL, qos: QOS_CLASS_DEFAULT, relative_priority: 0)
public var concurrentQueueDispatchPool = DispatchQueuePool(a: DISPATCH_QUEUE_CONCURRENT, qos: QOS_CLASS_DEFAULT, relative_priority: 0)
public var defaultBarrierDispatchPool = concurrentQueueDispatchPool */
public class QueueBarrierSynchronization : SynchronizationProtocol {
var q : dispatch_queue_t
init(queue : dispatch_queue_t) {
self.q = queue
}
required public init() {
let c_attr = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_CONCURRENT,QOS_CLASS_DEFAULT, 0)
self.q = dispatch_queue_create("QueueBarrierSynchronization", c_attr)
}
init(type : dispatch_queue_attr_t, _ q: qos_class_t = QOS_CLASS_DEFAULT, _ p :Int32 = 0) {
let c_attr = dispatch_queue_attr_make_with_qos_class(type,q, p)
self.q = dispatch_queue_create("QueueBarrierSynchronization", c_attr)
}
public func read(block:() -> Void) {
dispatch_async(self.q,block)
}
public func readSync<T>(block:() -> T) -> T {
var ret : T?
dispatch_sync(self.q) {
ret = block()
}
return ret!
}
public func readAsync<T>(block:() -> T, done : (T) -> Void) {
dispatch_async(self.q) {
done(block())
}
}
public func modify(block:() -> Void) {
dispatch_barrier_async(self.q,block)
}
public func modifyAsync<T>(block:() -> T, done : (T) -> Void) {
dispatch_barrier_async(self.q) {
done(block())
}
}
public func modifySync<T>(block:() -> T) -> T {
var ret : T?
dispatch_barrier_sync(self.q) {
ret = block()
}
return ret!
}
}
public class QueueSerialSynchronization : SynchronizationProtocol {
var q : dispatch_queue_t
init(queue : dispatch_queue_t) {
self.q = queue
}
required public init() {
let c_attr = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL,QOS_CLASS_DEFAULT, 0)
self.q = dispatch_queue_create("QueueSynchronization", c_attr)
}
public func read(block:() -> Void) {
dispatch_async(self.q,block)
}
public func readSync<T>(block:() -> T) -> T {
var ret : T?
dispatch_sync(self.q) {
ret = block()
}
return ret!
}
public func readAsync<T>(block:() -> T, done : (T) -> Void) {
dispatch_async(self.q) {
done(block())
}
}
public func modify(block:() -> Void) {
dispatch_async(self.q,block)
}
public func modifyAsync<T>(block:() -> T, done : (T) -> Void) {
dispatch_async(self.q) {
done(block())
}
}
public func modifySync<T>(block:() -> T) -> T {
var ret : T?
dispatch_sync(self.q) {
ret = block()
}
return ret!
}
}
class NSObjectLockSynchronization : SynchronizationProtocol {
var lock : AnyObject
required init() {
self.lock = NSObject()
}
init(lock l: AnyObject) {
self.lock = l
}
func synchronized<T>(block:() -> T) -> T {
return SYNCHRONIZED(self.lock) { () -> T in
return block()
}
}
func read(block:() -> Void) {
self.synchronized(block)
}
func readSync<T>(block:() -> T) -> T {
return self.synchronized(block)
}
func readAsync<T>(block:() -> T, done : (T) -> Void) {
let ret = self.synchronized(block)
done(ret)
}
func modify(block:() -> Void) {
self.synchronized(block)
}
func modifySync<T>(block:() -> T) -> T {
return self.synchronized(block)
}
func modifyAsync<T>(block:() -> T, done : (T) -> Void) {
let ret = self.synchronized(block)
done(ret)
}
}
func synchronizedWithLock<T>(l: NSLocking, @noescape closure: ()->T) -> T {
l.lock()
let retVal: T = closure()
l.unlock()
return retVal
}
public class NSLockSynchronization : SynchronizationProtocol {
var lock = NSLock()
required public init() {
}
final func synchronized<T>(block:() -> T) -> T {
return synchronizedWithLock(self.lock) { () -> T in
return block()
}
}
public func read(block:() -> Void) {
synchronizedWithLock(lock,block)
}
public func readSync<T>(block:() -> T) -> T {
return synchronizedWithLock(lock,block)
}
public func readAsync<T>(block:() -> T, done : (T) -> Void) {
let ret = synchronizedWithLock(lock,block)
done(ret)
}
public func modify(block:() -> Void) {
synchronizedWithLock(lock,block)
}
public func modifySync<T>(block:() -> T) -> T {
return synchronizedWithLock(lock,block)
}
public func modifyAsync<T>(block:() -> T, done : (T) -> Void) {
let ret = synchronizedWithLock(lock,block)
done(ret)
}
}
func synchronizedWithSpinLock<T>(l: UnSafeMutableContainer<OSSpinLock>, @noescape closure: ()->T) -> T {
OSSpinLockLock(l.unsafe_pointer)
let retVal: T = closure()
OSSpinLockUnlock(l.unsafe_pointer)
return retVal
}
public class OSSpinLockSynchronization : SynchronizationProtocol {
var lock = UnSafeMutableContainer<OSSpinLock>(OS_SPINLOCK_INIT)
required public init() {
}
final func synchronized<T>(block:() -> T) -> T {
return synchronizedWithSpinLock(self.lock) { () -> T in
return block()
}
}
public func read(block:() -> Void) {
synchronizedWithSpinLock(lock,block)
}
public func readSync<T>(block:() -> T) -> T {
return synchronizedWithSpinLock(lock,block)
}
public func readAsync<T>(block:() -> T, done : (T) -> Void) {
let ret = synchronizedWithSpinLock(lock,block)
done(ret)
}
public func modify(block:() -> Void) {
synchronizedWithSpinLock(lock,block)
}
public func modifySync<T>(block:() -> T) -> T {
return synchronizedWithSpinLock(lock,block)
}
public func modifyAsync<T>(block:() -> T, done : (T) -> Void) {
let ret = synchronizedWithSpinLock(lock,block)
done(ret)
}
}
public class NSRecursiveLockSynchronization : SynchronizationProtocol {
var lock = NSRecursiveLock()
required public init() {
}
final func synchronized<T>(block:() -> T) -> T {
return synchronizedWithLock(self.lock) { () -> T in
return block()
}
}
public func read(block:() -> Void) {
synchronizedWithLock(lock,block)
}
public func readSync<T>(block:() -> T) -> T {
return synchronizedWithLock(lock,block)
}
public func readAsync<T>(block:() -> T, done : (T) -> Void) {
let ret = synchronizedWithLock(lock,block)
done(ret)
}
public func modify(block:() -> Void) {
synchronizedWithLock(lock,block)
}
public func modifySync<T>(block:() -> T) -> T {
return synchronizedWithLock(lock,block)
}
public func modifyAsync<T>(block:() -> T, done : (T) -> Void) {
let ret = synchronizedWithLock(lock,block)
done(ret)
}
}
// wraps your synch strategy into a Future
// increases 'composability'
// warning: Future has it's own lockObject (usually NSLock)
public class SynchronizationObject<P : SynchronizationProtocol> {
let sync : P
let defaultExecutor : Executor // used to execute 'done' blocks for async lookups
public init() {
self.sync = P()
self.defaultExecutor = Executor.Immediate
}
public init(_ p : P) {
self.sync = p
self.defaultExecutor = Executor.Immediate
}
public init(_ p : P, _ executor : Executor) {
self.sync = p
self.defaultExecutor = executor
}
public func read(block:() -> Void) {
self.sync.read(block)
}
public func readSync<T>(block:() -> T) -> T {
return self.sync.readSync(block)
}
public func readAsync<T>(block:() -> T, done : (T) -> Void) {
return self.sync.readAsync(block,done: done)
}
public func modify(block:() -> Void) {
self.sync.modify(block)
}
public func modifySync<T>(block:() -> T) -> T {
return self.sync.modifySync(block)
}
public func modifyAsync<T>(block:() -> T, done : (T) -> Void) {
return self.sync.modifyAsync(block,done: done)
}
public func modifyFuture<T>(block:() -> T) -> Future<T> {
return self.modifyFuture(self.defaultExecutor,block: block)
}
public func readFuture<T>(block:() -> T) -> Future<T> {
return self.readFuture(self.defaultExecutor,block: block)
}
public func readFuture<T>(executor : Executor, block:() -> T) -> Future<T> {
let p = Promise<T>()
self.sync.readAsync({ () -> T in
return block()
}, done: { (result) -> Void in
p.completeWithSuccess(result)
})
return p.future
}
public func modifyFuture<T>(executor : Executor, block:() -> T) -> Future<T> {
let p = Promise<T>()
self.sync.modifyAsync({ () -> T in
return block()
}, done: { (t) -> Void in
p.completeWithSuccess(t)
})
return p.future
}
}
class CollectionAccessControl<C : MutableCollectionType, S: SynchronizationProtocol> {
typealias Index = C.Index
typealias Element = C.Generator.Element
var syncObject : SynchronizationObject<S>
var collection : C
init(c : C, _ s: SynchronizationObject<S>) {
self.collection = c
self.syncObject = s
}
func getValue(key : Index) -> Future<Element> {
return self.syncObject.readFuture { () -> Element in
return self.collection[key]
}
}
/* subscript (key: Index) -> Element {
get {
return self.syncObject.readSync { () -> Element in
return self.collection[key]
}
}
set(newValue) {
self.syncObject.modifySync {
self.collection[key] = newValue
}
}
} */
}
class DictionaryWithSynchronization<Key : Hashable, Value, S: SynchronizationProtocol> {
typealias Index = Key
typealias Element = Value
typealias DictionaryType = Dictionary<Key,Value>
var syncObject : SynchronizationObject<S>
var dictionary : DictionaryType
init() {
self.dictionary = DictionaryType()
self.syncObject = SynchronizationObject<S>()
}
init(_ d : DictionaryType, _ s: SynchronizationObject<S>) {
self.dictionary = d
self.syncObject = s
}
init(_ s: SynchronizationObject<S>) {
self.dictionary = DictionaryType()
self.syncObject = s
}
func getValue(key : Key) -> Future<Value?> {
return self.syncObject.readFuture { () -> Value? in
return self.dictionary[key]
}
}
var count: Int {
get {
return self.syncObject.readSync { () -> Int in
return self.dictionary.count
}
}
}
var isEmpty: Bool {
get {
return self.syncObject.readSync { () -> Bool in
return self.dictionary.isEmpty
}
}
}
/* subscript (key: Key) -> Value? {
get {
return self.syncObject.readSync { () -> Element? in
return self.dictionary[key]
}
}
set(newValue) {
self.syncObject.modifySync {
self.dictionary[key] = newValue
}
}
} */
}
class ArrayAccessControl<T, S: SynchronizationProtocol> : CollectionAccessControl< Array<T> , S> {
var array : Array<T> {
get {
return self.collection
}
}
init() {
super.init(c: Array<T>(), SynchronizationObject<S>())
}
init(array : Array<T>, _ a: SynchronizationObject<S>) {
super.init(c: array, a)
}
init(a: SynchronizationObject<S>) {
super.init(c: Array<T>(), a)
}
var count: Int {
get {
return self.syncObject.readSync { () -> Int in
return self.collection.count
}
}
}
var isEmpty: Bool {
get {
return self.syncObject.readSync { () -> Bool in
return self.collection.isEmpty
}
}
}
var first: T? {
get {
return self.syncObject.readSync { () -> T? in
return self.collection.first
}
}
}
var last: T? {
get {
return self.syncObject.readSync { () -> T? in
return self.collection.last
}
}
}
/* subscript (future index: Int) -> Future<T> {
return self.syncObject.readFuture { () -> T in
return self.collection[index]
}
} */
func getValue(atIndex i: Int) -> Future<T> {
return self.syncObject.readFuture { () -> T in
return self.collection[i]
}
}
func append(newElement: T) {
self.syncObject.modify {
self.collection.append(newElement)
}
}
func removeLast() -> T {
return self.syncObject.modifySync {
self.collection.removeLast()
}
}
func insert(newElement: T, atIndex i: Int) {
self.syncObject.modify {
self.collection.insert(newElement,atIndex: i)
}
}
func removeAtIndex(index: Int) -> T {
return self.syncObject.modifySync {
self.collection.removeAtIndex(index)
}
}
}
class DictionaryWithLockAccess<Key : Hashable, Value> : DictionaryWithSynchronization<Key,Value,NSObjectLockSynchronization> {
typealias LockObjectType = SynchronizationObject<NSObjectLockSynchronization>
override init() {
super.init(LockObjectType(NSObjectLockSynchronization()))
}
init(d : Dictionary<Key,Value>) {
super.init(d,LockObjectType(NSObjectLockSynchronization()))
}
}
class DictionaryWithBarrierAccess<Key : Hashable, Value> : DictionaryWithSynchronization<Key,Value,QueueBarrierSynchronization> {
typealias LockObjectType = SynchronizationObject<QueueBarrierSynchronization>
init(queue : dispatch_queue_t) {
super.init(LockObjectType(QueueBarrierSynchronization(queue: queue)))
}
init(d : Dictionary<Key,Value>,queue : dispatch_queue_t) {
super.init(d,LockObjectType(QueueBarrierSynchronization(queue: queue)))
}
}
/* func dispatch_queue_create_compatibleIOS8(label : String,
attr : dispatch_queue_attr_t,
qos_class : dispatch_qos_class_t,relative_priority : Int32) -> dispatch_queue_t
{
let c_attr = dispatch_queue_attr_make_with_qos_class(attr,qos_class, relative_priority)
let queue = dispatch_queue_create(label, c_attr)
return queue;
} */
/* class DispatchQueue: NSObject {
enum QueueType {
case Serial
case Concurrent
}
enum QueueClass {
case Main
case UserInteractive // QOS_CLASS_USER_INTERACTIVE
case UserInitiated // QOS_CLASS_USER_INITIATED
case Default // QOS_CLASS_DEFAULT
case Utility // QOS_CLASS_UTILITY
case Background // QOS_CLASS_BACKGROUND
}
var q : dispatch_queue_t
var type : QueueType
init(name : String, type : QueueType, relative_priority : Int32) {
var attr = (type == .Concurrent) ? DISPATCH_QUEUE_CONCURRENT : DISPATCH_QUEUE_SERIAL
let c_attr = dispatch_queue_attr_make_with_qos_class(attr,qos_class, relative_priority);
dispatch_queue_t queue = dispatch_queue_create(label, c_attr);
return queue;
}
} */
| mit |
QuickBlox/QMChatViewController-ios | ChatExample/ChatExample/AppDelegate.swift | 1 | 561 | //
// AppDelegate.swift
// ChatExample
//
// Created by Andrey Ivanov on 23/03/2018.
// Copyright © 2018 Andrey Ivanov. 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.
self.window?.backgroundColor = UIColor.white
return true
}
}
| bsd-3-clause |
jtbandes/swift-compiler-crashes | crashes-duplicates/27304-swift-patternbindingdecl-setpattern.swift | 4 | 312 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct B<T where f=B{
enum S{
struct B<T
var f=B{
func a{var b{
struct B{
class A{
class b{
func b{
{struct Q{let a{var a{
case
s{class A{var:
| mit |
wordpress-mobile/WordPress-iOS | WordPress/Classes/Models/FileDownloadsStatsRecordValue+CoreDataProperties.swift | 2 | 378 | import Foundation
import CoreData
extension FileDownloadsStatsRecordValue {
@nonobjc public class func fetchRequest() -> NSFetchRequest<FileDownloadsStatsRecordValue> {
return NSFetchRequest<FileDownloadsStatsRecordValue>(entityName: "FileDownloadsStatsRecordValue")
}
@NSManaged public var downloadCount: Int64
@NSManaged public var file: String?
}
| gpl-2.0 |
kickstarter/ios-oss | Library/ViewModels/ShippingRuleCellViewModelTests.swift | 1 | 1369 | import Foundation
@testable import KsApi
@testable import Library
import Prelude
import ReactiveExtensions_TestHelpers
final class ShippingRuleCellViewModelTests: TestCase {
private let vm: ShippingRuleCellViewModelType = ShippingRuleCellViewModel()
private let isSelected = TestObserver<Bool, Never>()
private let textLabelText = TestObserver<String, Never>()
override func setUp() {
super.setUp()
self.vm.outputs.isSelected.observe(self.isSelected.observer)
self.vm.outputs.textLabelText.observe(self.textLabelText.observer)
}
func testIsSelected_False() {
let selectedShippingRule: ShippingRule = .template
|> ShippingRule.lens.location .~ Location.canada
let data = ShippingRuleData(
selectedShippingRule: selectedShippingRule,
shippingRule: .template
)
self.vm.inputs.configureWith(data)
self.isSelected.assertValues([false])
}
func testIsSelected_True() {
let data = ShippingRuleData(
selectedShippingRule: .template,
shippingRule: .template
)
self.vm.inputs.configureWith(data)
self.isSelected.assertValues([true])
}
func testTextLabelText() {
let data = ShippingRuleData(
selectedShippingRule: .template,
shippingRule: .template
)
self.vm.inputs.configureWith(data)
self.textLabelText.assertValues(["Brooklyn, NY"])
}
}
| apache-2.0 |
yajeka/PS | PS/BackendManager.swift | 1 | 2854 | //
// BackendManager.swift
// PS
//
// Created by Andrey Koyro on 20/03/2016.
// Copyright © 2016 hackathon. All rights reserved.
//
import Foundation
import Parse
public typealias BackedBlock = (success: PFObject?, error: String?) -> Void
public class BackendManager {
private class func handleResult(result: AnyObject? , error: NSError?, block: BackedBlock?, className: String) {
if result is String {
block!(success: nil, error: result as? String)
} else if error != nil {
block!(success: nil, error: error?.localizedDescription)
} else if let input = result as? NSDictionary {
let query = PFQuery(className: className);
let objectId = input["objectId"] as! String
let task = query.getObjectInBackgroundWithId(objectId)
task.waitUntilFinished()
let object:PFObject = task.result as! PFObject
block!(success: object, error: nil)
}
}
public class func signUp(uid: String, email: String, password: String, block: BackedBlock?) {
findByEmailAndPassword(email, password: password, block: { (success: PFObject?, error: String?) -> Void in
if ((error) != nil) {
let account = PFObject(className: "Account")
account["uids"] = [uid]
account["email"] = email
account["password"] = password
let task = account.saveInBackground()
task.waitUntilFinished()
block!(success: account, error: nil)
} else {
block!(success: nil, error: "account_exists")
}
})
}
public class func findByEmailAndPassword(email: String, password: String, block: BackedBlock?) {
PFCloud.callFunctionInBackground("findByEmailAndPassword", withParameters: ["email": email, "password": password], block: {(result: AnyObject? , error: NSError?) -> Void in
handleResult(result,error: error, block: block, className: "Account")
});
}
public class func findByUid(uid: String, block: BackedBlock?) {
PFCloud.callFunctionInBackground("findByUid", withParameters: ["uid": uid], block: {(result: AnyObject? , error: NSError?) -> Void in
handleResult(result,error: error, block: block, className: "Account")
});
}
public class func findByEmailAndPassword(email: String, password: String) -> BFTask {
return PFCloud.callFunctionInBackground("findByEmailAndPassword", withParameters: ["email": email, "password": password]);
}
private class func findByUid(uid: String) -> BFTask {
return PFCloud.callFunctionInBackground("findByUid", withParameters: ["uid": uid]);
}
}
| lgpl-3.0 |
EZ-NET/ESOcean | ESOcean/DateTime/Time.swift | 1 | 3114 | //
// Time.swift
// ESOcean
//
// Created by Tomohiro Kumagai on H27/06/19.
//
//
import Darwin.C
extension timespec : Equatable {
public init(_ value:timeval) {
self.tv_sec = value.tv_sec
self.tv_nsec = Int(value.tv_usec) * Time.nanosecondPerMicrosecond
}
}
extension timeval : Equatable {
public init(_ spec:timespec) {
self.tv_sec = spec.tv_sec
self.tv_usec = Int32(spec.tv_nsec / Time.nanosecondPerMicrosecond)
}
}
public func == (lhs:timespec, rhs:timespec) -> Bool {
return lhs.tv_sec == rhs.tv_sec && lhs.tv_nsec == rhs.tv_nsec
}
public func == (lhs:timeval, rhs:timeval) -> Bool {
return lhs.tv_sec == rhs.tv_sec && lhs.tv_usec == rhs.tv_usec
}
public struct Time {
var _timespec:timespec
/// Get an instance means Today.
public init?() {
var value = timeval()
guard gettimeofday(&value, nil) == 0 else {
return nil
}
self._timespec = timespec(value)
}
public init(_ spec:timespec) {
self._timespec = spec
}
public init(_ value:timeval) {
self.init(timespec(value))
}
/// Get time by nanoseconds.
public var nanoseconds:IntMax {
return self._timespec.tv_sec.toIntMax() * Time.nanosecondPerSecond.toIntMax() + self._timespec.tv_nsec.toIntMax()
}
public var microseconds:IntMax {
return self._timespec.tv_sec.toIntMax() * Time.microsecondPerSecond.toIntMax() + IntMax(self._timespec.tv_nsec / Time.nanosecondPerMicrosecond)
}
public var milliseconds:IntMax {
return self._timespec.tv_sec.toIntMax() * Time.millisecondPerSecond.toIntMax() + IntMax(self._timespec.tv_nsec / Time.nanosecondPerMillisecond)
}
public var seconds:Int64 {
return Int64(self._timespec.tv_sec) + Int64(self._timespec.tv_nsec / Time.nanosecondPerSecond)
}
/// Get time as Unix time.
public var time:Int {
return self._timespec.tv_sec
}
public var gmtTime:Int {
var time = self.time
return mktime(gmtime(&time))
}
public var localTime:Int {
var time = self.time
return mktime(localtime(&time))
}
public var localTimeString:String {
var _time = time
let _characters = ctime(&_time)
return String.fromCString(_characters)!.replace("\n", "")
}
}
extension Time : CustomStringConvertible {
public var description:String {
return self.localTimeString
}
}
extension Time : Comparable {
}
public func == (lhs:Time, rhs:Time) -> Bool {
return lhs._timespec == rhs._timespec
}
public func < (lhs:Time, rhs:Time) -> Bool {
return lhs.nanoseconds < rhs.nanoseconds
}
// MARK: Constants
extension Time {
/// Get milliseconds per a second.
public static let millisecondPerSecond = 1000;
/// Get microseconds per a second.
public static let microsecondPerSecond = 1000000;
/// Get nanoseconds per a second.
public static let nanosecondPerSecond = 1000000000;
/// Get microseconds per a millisecond.
public static let microsecondPerMillisecond = 1000
/// Get nanoseconds per a millisecond.
public static let nanosecondPerMillisecond = 1000000
/// Get nanoseconds per a microsecond.
public static let nanosecondPerMicrosecond = 1000
} | mit |
kickstarter/ios-oss | Kickstarter-iOS/SharedViews/LoadingButton.swift | 1 | 3574 | import Library
import Prelude
import UIKit
final class LoadingButton: UIButton {
// MARK: - Properties
private let viewModel: LoadingButtonViewModelType = LoadingButtonViewModel()
private lazy var activityIndicator: UIActivityIndicatorView = {
UIActivityIndicatorView(style: .medium)
|> \.hidesWhenStopped .~ true
|> \.translatesAutoresizingMaskIntoConstraints .~ false
}()
public var activityIndicatorStyle: UIActivityIndicatorView.Style = .medium {
didSet {
self.activityIndicator.style = self.activityIndicatorStyle
}
}
public var isLoading: Bool = false {
didSet {
self.viewModel.inputs.isLoading(self.isLoading)
}
}
private var originalTitles: [UInt: String] = [:]
// MARK: - Lifecycle
override init(frame: CGRect) {
super.init(frame: frame)
self.configureViews()
self.bindViewModel()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
self.configureViews()
self.bindViewModel()
}
override func setTitle(_ title: String?, for state: UIControl.State) {
// Do not allow changing the title while the activity indicator is animating
guard !self.activityIndicator.isAnimating else {
self.originalTitles[state.rawValue] = title
return
}
super.setTitle(title, for: state)
}
// MARK: - Configuration
private func configureViews() {
self.addSubview(self.activityIndicator)
self.activityIndicator.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
self.activityIndicator.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
}
// MARK: - View model
override func bindViewModel() {
super.bindViewModel()
self.viewModel.outputs.isUserInteractionEnabled
.observeForUI()
.observeValues { [weak self] isUserInteractionEnabled in
_ = self
?|> \.isUserInteractionEnabled .~ isUserInteractionEnabled
}
self.viewModel.outputs.startLoading
.observeForUI()
.observeValues { [weak self] in
self?.startLoading()
}
self.viewModel.outputs.stopLoading
.observeForUI()
.observeValues { [weak self] in
self?.stopLoading()
}
}
// MARK: - Loading
private func startLoading() {
self.removeTitle()
self.activityIndicator.startAnimating()
}
private func stopLoading() {
self.activityIndicator.stopAnimating()
self.restoreTitle()
}
// MARK: - Titles
private func removeTitle() {
let states: [UIControl.State] = [.disabled, .highlighted, .normal, .selected]
states.compactMap { state -> (String, UIControl.State)? in
guard let title = self.title(for: state) else { return nil }
return (title, state)
}
.forEach { title, state in
self.originalTitles[state.rawValue] = title
self.setTitle(nil, for: state)
}
_ = self
|> \.accessibilityLabel %~ { _ in Strings.Loading() }
UIAccessibility.post(notification: .layoutChanged, argument: self)
}
private func restoreTitle() {
let states: [UIControl.State] = [.disabled, .highlighted, .normal, .selected]
states.compactMap { state -> (String, UIControl.State)? in
guard let title = self.originalTitles[state.rawValue] else { return nil }
return (title, state)
}
.forEach { title, state in
self.originalTitles[state.rawValue] = nil
self.setTitle(title, for: state)
}
_ = self
|> \.accessibilityLabel .~ nil
UIAccessibility.post(notification: .layoutChanged, argument: self)
}
}
| apache-2.0 |
Onion-Shen/ONSCalendar | src/CalendarItem.swift | 1 | 819 | import UIKit
class CalendarItem : UIView
{
var year : Int = 0
var month : Int = 0
var day : Int = 0
var contentLabel : UILabel = UILabel()
override init(frame: CGRect)
{
super.init(frame: frame)
self.backgroundColor = UIColor.white
self.layer.borderColor = UIColor.black.cgColor
self.layer.borderWidth = 0.25
self.contentLabel.textAlignment = .center
self.addSubview(self.contentLabel)
}
override func layoutSubviews()
{
super.layoutSubviews()
self.contentLabel.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
}
required init?(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 |
apple/swift-nio | Sources/NIOCore/AddressedEnvelope.swift | 1 | 3088 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 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
//
//===----------------------------------------------------------------------===//
/// A data structure for processing addressed datagrams, such as those used by UDP.
///
/// The AddressedEnvelope is used extensively on `DatagramChannel`s in order to keep track
/// of source or destination address metadata: that is, where some data came from or where
/// it is going.
public struct AddressedEnvelope<DataType> {
public var remoteAddress: SocketAddress
public var data: DataType
/// Any metadata associated with this `AddressedEnvelope`
public var metadata: Metadata? = nil
public init(remoteAddress: SocketAddress, data: DataType) {
self.remoteAddress = remoteAddress
self.data = data
}
public init(remoteAddress: SocketAddress, data: DataType, metadata: Metadata?) {
self.remoteAddress = remoteAddress
self.data = data
self.metadata = metadata
}
/// Any metadata associated with an `AddressedEnvelope`
public struct Metadata: Hashable, Sendable {
/// Details of any congestion state.
public var ecnState: NIOExplicitCongestionNotificationState
public var packetInfo: NIOPacketInfo?
public init(ecnState: NIOExplicitCongestionNotificationState) {
self.ecnState = ecnState
self.packetInfo = nil
}
public init(ecnState: NIOExplicitCongestionNotificationState, packetInfo: NIOPacketInfo?) {
self.ecnState = ecnState
self.packetInfo = packetInfo
}
}
}
extension AddressedEnvelope: CustomStringConvertible {
public var description: String {
return "AddressedEnvelope { remoteAddress: \(self.remoteAddress), data: \(self.data) }"
}
}
extension AddressedEnvelope: Equatable where DataType: Equatable {}
extension AddressedEnvelope: Hashable where DataType: Hashable {}
extension AddressedEnvelope: Sendable where DataType: Sendable {}
/// Possible Explicit Congestion Notification States
public enum NIOExplicitCongestionNotificationState: Hashable, Sendable {
/// Non-ECN Capable Transport.
case transportNotCapable
/// ECN Capable Transport (flag 0).
case transportCapableFlag0
/// ECN Capable Transport (flag 1).
case transportCapableFlag1
/// Congestion Experienced.
case congestionExperienced
}
public struct NIOPacketInfo: Hashable, Sendable {
public var destinationAddress: SocketAddress
public var interfaceIndex: Int
public init(destinationAddress: SocketAddress, interfaceIndex: Int) {
self.destinationAddress = destinationAddress
self.interfaceIndex = interfaceIndex
}
}
| apache-2.0 |
chenyunguiMilook/VisualDebugger | Package.swift | 1 | 1055 | // swift-tools-version:5.1
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "VisualDebugger",
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "VisualDebugger",
targets: ["VisualDebugger"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "VisualDebugger",
dependencies: []),
.testTarget(
name: "VisualDebuggerTests",
dependencies: ["VisualDebugger"]),
]
)
| mit |
whiteshadow-gr/HatForIOS | HAT/Objects/Data Offers/HATDataOffer.swift | 1 | 11206 | /**
* Copyright (C) 2018 HAT Data Exchange Ltd
*
* SPDX-License-Identifier: MPL2
*
* This file is part of the Hub of All Things project (HAT).
*
* 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 SwiftyJSON
// MARK: Struct
public struct HATDataOffer: HATObject {
// MARK: - CodingKeys
/**
The JSON fields used by the hat
The Fields are the following:
* `dataOfferID` in JSON is `id`
* `createdDate` in JSON is `created`
* `offerTitle` in JSON is `title`
* `shortDescription` in JSON is `shortDescription`
* `longDescription` in JSON is `longDescription`
* `imageURL` in JSON is `illustrationUrl`
* `offerStarts` in JSON is `starts`
* `offerExpires` in JSON is `expires`
* `collectsDataFor` in JSON is `collectFor`
* `minimumUsers` in JSON is `requiredMinUser`
* `maximumUsers` in JSON is `requiredMaxUser`
* `usersClaimedOffer` in JSON is `totalUserClaims`
* `requiredDataDefinitions` in JSON is `requiredDataDefinition`
* `dataConditions` in JSON is `dataConditions`
* `dataRequirements` in JSON is `dataRequirements`
* `reward` in JSON is `reward`
* `owner` in JSON is `owner`
* `claim` in JSON is `claim`
* `pii` in JSON is `pii`
* `merchantCode` in JSON is `merchantCode`
*/
private enum CodingKeys: String, CodingKey {
case dataOfferID = "id"
case dateCreated = "created"
case offerTitle = "title"
case shortDescription = "shortDescription"
case longDescription = "longDescription"
case imageURL = "illustrationUrl"
case startDate = "starts"
case expireDate = "expires"
case collectsDataFor = "collectFor"
case minimumUsers = "requiredMinUser"
case maximumUsers = "requiredMaxUser"
case usersClaimedOffer = "totalUserClaims"
case requiredDataDefinition = "requiredDataDefinition"
case dataConditions = "dataConditions"
case dataRequirements = "dataRequirements"
case reward = "reward"
case owner = "owner"
case claim = "claim"
case isPΙIRequested = "pii"
case merchantCode = "merchantCode"
}
// MARK: - Variables
/// The `Data Offer` unique ID
public var dataOfferID: String = ""
/// The `Data Offer` title
public var offerTitle: String = ""
/// The short description of the `Data Offer`, usually 1 phrase
public var shortDescription: String = ""
/// The long description of the `Data Offer`, usually 1 small paragraph stating more info about the offer and the reward
public var longDescription: String = ""
/// The image URL of the `Data Offer` in order to fetch it
public var imageURL: String = ""
/// The merchant code of the `Data Offer`, this is how you can ask for offers from a specific merchants. Any merchant ending in `private` is not visible publicly. Some merchants can be public as well
public var merchantCode: String = ""
/// the date created as unix time stamp
public var dateCreated: String = ""
/// the start date of the `Data Offer` as unix time stamp
public var startDate: String = ""
/// the expire date of the `Data Offer` as unix time stamp. After this date no one can claim the offer
public var expireDate: String = ""
/// the duration that the `Data Offer` collects data for as unix time stamp
public var collectsDataFor: Int = -1
/// the minimum users required for the `Data Offer` to activate
public var minimumUsers: Int = -1
/// the max users of the `Data Offer`. If this number is reached no one else can claim the offer
public var maximumUsers: Int = -1
/// the number of users claimed the `Data Offer` so far
public var usersClaimedOffer: Int = -1
/// the data definition object of the `Data Offer`. Here you can find info about the name of the data definitions alongside what endpoints and fields has access to. Optional
public var requiredDataDefinition: HATDataDefinition?
/// the data conditions object of the `Data Offer`. Here you can find info about the name of the data definitions alongside what endpoints and fields has access to. Optional
public var dataConditions: HATDataDefinition?
/// the data requirements object of the `Data Offer`. Here you can find info about the name of the data definitions alongside what endpoints and fields has access to. Optional
public var dataRequirements: HATDataDefinition?
/// the rewards information of the `Data Offer`. Here you can find information about the type of the reward, tha value, vouchers etc
public var reward: HATDataOfferRewards = HATDataOfferRewards()
/// The owner information of the `Data Offer`. Here you can find stuff like the name of the owner, email address etc
public var owner: HATDataOfferOwner = HATDataOfferOwner()
/// The claim information object of the `Data Offer`. Here you can find stuff like if the offer is claimed, when was it claimed etc
public var claim: HATDataOfferClaim = HATDataOfferClaim()
/// The downloaded image of the `Data Offer`, used to cache the image once downloaded. Optional
public var image: UIImage?
/// A flag indicating if the `Data Offer` requires pii, personal identifying information
public var isPΙIRequested: Bool = false
// MARK: - Initialisers
/**
The default initialiser. Initialises everything to default values.
*/
public init() {
dataOfferID = ""
offerTitle = ""
shortDescription = ""
longDescription = ""
imageURL = ""
merchantCode = ""
dateCreated = ""
startDate = ""
expireDate = ""
collectsDataFor = -1
minimumUsers = -1
maximumUsers = -1
usersClaimedOffer = -1
requiredDataDefinition = nil
dataConditions = nil
dataRequirements = nil
reward = HATDataOfferRewards()
owner = HATDataOfferOwner()
claim = HATDataOfferClaim()
image = nil
isPΙIRequested = false
}
/**
It initialises everything from the received JSON file from the HAT
- dictionary: The JSON file received
*/
public init(dictionary: Dictionary<String, JSON>) {
if let tempID: String = dictionary[HATDataOffer.CodingKeys.dataOfferID.rawValue]?.string {
dataOfferID = tempID
}
if let tempCreated: String = dictionary[HATDataOffer.CodingKeys.dateCreated.rawValue]?.string {
dateCreated = tempCreated
}
if let tempTitle: String = dictionary[HATDataOffer.CodingKeys.offerTitle.rawValue]?.string {
offerTitle = tempTitle
}
if let tempShortDescription: String = dictionary[HATDataOffer.CodingKeys.shortDescription.rawValue]?.string {
shortDescription = tempShortDescription
}
if let tempLongDescription: String = dictionary[HATDataOffer.CodingKeys.longDescription.rawValue]?.string {
longDescription = tempLongDescription
}
if let tempIllustrationUrl: String = dictionary[HATDataOffer.CodingKeys.imageURL.rawValue]?.string {
imageURL = tempIllustrationUrl
}
if let tempMerchantCode: String = dictionary[HATDataOffer.CodingKeys.merchantCode.rawValue]?.string {
merchantCode = tempMerchantCode
}
if let tempOfferStarts: String = dictionary[HATDataOffer.CodingKeys.startDate.rawValue]?.string {
startDate = tempOfferStarts
}
if let tempOfferExpires: String = dictionary[HATDataOffer.CodingKeys.expireDate.rawValue]?.string {
expireDate = tempOfferExpires
}
if let tempCollectOfferFor: Int = dictionary[HATDataOffer.CodingKeys.collectsDataFor.rawValue]?.int {
collectsDataFor = tempCollectOfferFor
}
if let tempRequiresMinUsers: Int = dictionary[HATDataOffer.CodingKeys.minimumUsers.rawValue]?.int {
minimumUsers = tempRequiresMinUsers
}
if let tempRequiresMaxUsers: Int = dictionary[HATDataOffer.CodingKeys.maximumUsers.rawValue]?.int {
maximumUsers = tempRequiresMaxUsers
}
if let tempUserClaims: Int = dictionary[HATDataOffer.CodingKeys.usersClaimedOffer.rawValue]?.int {
usersClaimedOffer = tempUserClaims
}
if let tempPII: Bool = dictionary[HATDataOffer.CodingKeys.isPΙIRequested.rawValue]?.bool {
isPΙIRequested = tempPII
}
if let tempRequiredDataDefinition: JSON = dictionary[HATDataOffer.CodingKeys.requiredDataDefinition.rawValue] {
let decoder: JSONDecoder = JSONDecoder()
do {
let data: Data = try tempRequiredDataDefinition.rawData()
requiredDataDefinition = try decoder.decode(HATDataDefinition.self, from: data)
} catch {
print(error)
}
}
if let tempDataConditions: JSON = dictionary[HATDataOffer.CodingKeys.dataConditions.rawValue] {
let decoder: JSONDecoder = JSONDecoder()
do {
let data: Data = try tempDataConditions.rawData()
dataConditions = try decoder.decode(HATDataDefinition.self, from: data)
} catch {
print(error)
}
}
if let tempDataRequirements: JSON = dictionary[HATDataOffer.CodingKeys.dataRequirements.rawValue] {
let decoder: JSONDecoder = JSONDecoder()
do {
let data: Data = try tempDataRequirements.rawData()
dataRequirements = try decoder.decode(HATDataDefinition.self, from: data)
} catch {
print(error)
}
}
if let tempReward: [String: JSON] = dictionary[HATDataOffer.CodingKeys.reward.rawValue]?.dictionary {
reward = HATDataOfferRewards(dictionary: tempReward)
}
if let tempOwner: [String: JSON] = dictionary[HATDataOffer.CodingKeys.owner.rawValue]?.dictionary {
owner = HATDataOfferOwner(dictionary: tempOwner)
}
if let tempClaim: [String: JSON] = dictionary[HATDataOffer.CodingKeys.claim.rawValue]?.dictionary {
claim = HATDataOfferClaim(dictionary: tempClaim)
}
}
}
| mpl-2.0 |
EclipseSoundscapes/EclipseSoundscapes | EclipseSoundscapes/Extensions/UIView+Extensions.swift | 1 | 5679 | //
// UIView+Extensions.swift
// EclipseSoundscapes
//
// Created by Arlindo on 7/15/18.
// Copyright © 2018 Arlindo Goncalves. All rights reserved.
//
import UIKit
extension UIView {
class var identifier: String {
return String(describing: self)
}
/// Add subviews
/// - Note: Each view's translatesAutoresizingMaskIntoConstraints attribute is marked as false
///
/// - Parameter views: Views to add
func addSubviews(_ views : UIView...) {
views.forEach { (view) in
view.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(view)
}
}
/// Center a view in given view
///
/// - Parameter view: View to center in
/// - Returns: Array of NSLayoutContraints
@discardableResult
func center(in view : UIView) -> [NSLayoutConstraint] {
translatesAutoresizingMaskIntoConstraints = false
var anchors = [NSLayoutConstraint]()
anchors.append(centerXAnchor.constraint(equalTo: view.centerXAnchor))
anchors.append(centerYAnchor.constraint(equalTo: view.centerYAnchor))
anchors.forEach({$0.isActive = true})
return anchors
}
/// Set the size of the view
/// - Note: Values are constant values
///
/// - Parameters:
/// - width: Width Constant
/// - height: Height Constant
/// - Returns: Array of NSLayoutContraints
@discardableResult
func setSize(_ width: CGFloat, height: CGFloat ) -> [NSLayoutConstraint] {
return self.anchor(nil, left: nil, bottom: nil, right: nil, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: width, heightConstant: height)
}
/// Set the size of the view
/// - Note: Values are constrained to layout dimensions
///
/// - Parameters:
/// - widthAnchor: Width dimension
/// - heightAnchor: Height dimension
/// - Returns: Array of NSLayoutContraints
@discardableResult
func setSize(widthAnchor: NSLayoutDimension, heightAnchor: NSLayoutDimension, widthMultiplier: CGFloat = 1, heightMultiplier: CGFloat = 1) -> [NSLayoutConstraint] {
var anchors = [NSLayoutConstraint]()
anchors.append(widthAnchor.constraint(equalTo: widthAnchor, multiplier: widthMultiplier))
anchors.append(heightAnchor.constraint(equalTo: heightAnchor, multiplier: heightMultiplier))
anchors.forEach({$0.isActive = true})
return anchors
}
func anchorToTop(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil) {
anchorWithConstantsToTop(top, left: left, bottom: bottom, right: right, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0)
}
func anchorWithConstantsToTop(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, topConstant: CGFloat = 0, leftConstant: CGFloat = 0, bottomConstant: CGFloat = 0, rightConstant: CGFloat = 0) {
_ = anchor(top, left: left, bottom: bottom, right: right, topConstant: topConstant, leftConstant: leftConstant, bottomConstant: bottomConstant, rightConstant: rightConstant)
}
@discardableResult
func anchor(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, topConstant: CGFloat = 0, leftConstant: CGFloat = 0, bottomConstant: CGFloat = 0, rightConstant: CGFloat = 0, widthConstant: CGFloat = 0, heightConstant: CGFloat = 0) -> [NSLayoutConstraint] {
translatesAutoresizingMaskIntoConstraints = false
var anchors = [NSLayoutConstraint]()
if let top = top {
anchors.append(topAnchor.constraint(equalTo: top, constant: topConstant))
}
if let left = left {
anchors.append(leftAnchor.constraint(equalTo: left, constant: leftConstant))
}
if let bottom = bottom {
anchors.append(bottomAnchor.constraint(equalTo: bottom, constant: -bottomConstant))
}
if let right = right {
anchors.append(rightAnchor.constraint(equalTo: right, constant: -rightConstant))
}
if widthConstant > 0 {
anchors.append(widthAnchor.constraint(equalToConstant: widthConstant))
}
if heightConstant > 0 {
anchors.append(heightAnchor.constraint(equalToConstant: heightConstant))
}
anchors.forEach({$0.isActive = true})
return anchors
}
/// Get Rombus Pattern View
///
/// - Returns: Rombus Pattern View
class func rombusPattern() -> UIView {
let iv = UIImageView()
iv.image = #imageLiteral(resourceName: "Rhombus Pattern")
return iv
}
/**
Slide in view from the top.
*/
func slideInFromTop(_ duration: TimeInterval = 0.3, completionDelegate: AnyObject? = nil) {
let slideInFromTopTransition = CATransition()
if let delegate: AnyObject = completionDelegate {
slideInFromTopTransition.delegate = delegate as? CAAnimationDelegate
}
slideInFromTopTransition.type = CATransitionType.push
slideInFromTopTransition.subtype = CATransitionSubtype.fromBottom
slideInFromTopTransition.duration = duration
slideInFromTopTransition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
slideInFromTopTransition.fillMode = CAMediaTimingFillMode.removed
self.layer.add(slideInFromTopTransition, forKey: "slideInFromTopTransition")
}
}
| gpl-3.0 |
mnisn/zhangchu | zhangchu/zhangchu/classes/recipe/service/SubjectListService.swift | 1 | 196 | //
// SubjectListService.swift
// zhangchu
//
// Created by 苏宁 on 2016/11/3.
// Copyright © 2016年 suning. All rights reserved.
//
import UIKit
class SubjectListService: NSObject {
}
| mit |
eBardX/XestiMonitors | Sources/Core/DependencyInjection/FileSystemInjection.swift | 1 | 673 | //
// FileSystemInjection.swift
// XestiMonitors
//
// Created by J. G. Pusey on 2018-02-21.
//
// © 2018 J. G. Pusey (see LICENSE.md)
//
internal protocol FileSystemProtocol: AnyObject {
@discardableResult
func close(_ fd: Int32) -> Int32
func fcntl(_ fd: Int32,
_ cmd: Int32,
_ ptr: UnsafeMutableRawPointer) -> Int32
func open(_ path: UnsafePointer<CChar>,
_ oflag: Int32) -> Int32
}
extension FileSystem: FileSystemProtocol {}
internal enum FileSystemInjector {
internal static var inject: () -> FileSystemProtocol = { shared }
private static let shared: FileSystemProtocol = FileSystem()
}
| mit |
joshua7v/ResearchOL-iOS | ResearchOL/Class/Home/Controller/ROLHomeDetailController.swift | 1 | 10332 | //
// ROLHomeDetailController.swift
// ResearchOL
//
// Created by Joshua on 15/4/18.
// Copyright (c) 2015年 SigmaStudio. All rights reserved.
//
import UIKit
protocol ROLHomeDetailControllerDelegate: NSObjectProtocol {
func homeDetailControllerDidGetQuestions(homeDetailController: ROLHomeDetailController, questionare: ROLQuestionare)
}
class ROLHomeDetailController: UITableViewController {
var questionare: ROLQuestionare = ROLQuestionare()
var delegate: ROLHomeDetailControllerDelegate?
var watch = false
var sysBtnColor: UIColor {
get {
return UIButton().tintColor!
}
}
@IBOutlet weak var watchBtn: UIButton!
@IBOutlet weak var indicator: UIActivityIndicatorView!
@IBOutlet weak var startBtn: UIButton!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var descLabel: UILabel!
@IBOutlet weak var participantLabel: UILabel!
@IBOutlet weak var pointLabel: UILabel!
@IBOutlet weak var requiredTimeLabel: UILabel!
@IBAction func watchBtnDIdClicked(sender: UIButton) {
if !ROLUserInfoManager.sharedManager.isUserLogin {
SEProgressHUDTool.showError("需要登录", toView: self.navigationController?.view, yOffset: 200)
return
}
if !self.watch {
sender.enabled = false
sender.setTitle("关注中...", forState: .Normal)
ROLUserInfoManager.sharedManager.watchQuestionareForCurrentUser(self.questionare.uuid, success: { () -> Void in
sender.setTitleColor(UIColor.coolGrayColor(), forState: .Normal)
sender.setTitle("已关注 √", forState: .Normal)
sender.enabled = true
self.watch = true
}, failure: { () -> Void in
sender.setTitle("关注问卷", forState: .Normal)
sender.setTitleColor(self.sysBtnColor, forState: .Normal)
sender.enabled = true
self.watch = false
dispatch_async(dispatch_get_main_queue(), { () -> Void in
SEProgressHUDTool.showError("请检查网络", toView: self.view)
})
})
} else {
sender.enabled = false
sender.setTitle("取消关注中...", forState: .Normal)
ROLUserInfoManager.sharedManager.unWatchQuestionareForCurrentUser(self.questionare.uuid, success: { () -> Void in
sender.setTitleColor(self.sysBtnColor, forState: .Normal)
sender.setTitle("关注问卷", forState: .Normal)
sender.enabled = true
self.watch = false
}, failure: { () -> Void in
sender.setTitle("已关注 √", forState: .Normal)
sender.setTitleColor(UIColor.coolGrayColor(), forState: .Normal)
sender.enabled = true
self.watch = true
dispatch_async(dispatch_get_main_queue(), { () -> Void in
SEProgressHUDTool.showError("请检查网络", toView: self.view)
})
})
}
}
@IBAction func startBtnClicked() {
if !ROLUserInfoManager.sharedManager.isUserLogin {
var alert = AMSmoothAlertView(dropAlertWithTitle: "提示", andText: "未登陆无法获得奖励哦", andCancelButton: true, forAlertType: AlertType.Info, andColor: UIColor.blackColor(), withCompletionHandler: { (alertView, button) -> Void in
if button == alertView.defaultButton {
self.presentViewController(UIStoryboard(name: "Login", bundle: nil).instantiateInitialViewController() as! UINavigationController, animated: true, completion: { () -> Void in
})
} else {
var dest = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("ROLQuestionareController") as! ROLQuestionareController
dest.questions = self.questionare.questions
dest.questionareID = self.questionare.uuid
dest.isAnonymous = true
// reset answers in memory
ROLQuestionManager.sharedManager.resetAnswers()
self.presentViewController(dest, animated: true) { () -> Void in
}
}
})
alert.defaultButton.setTitle("去登录", forState: .Normal)
alert.cancelButton.setTitle("匿名答题", forState: .Normal)
alert.defaultButton.titleLabel?.font = UIFont.systemFontOfSize(13)
alert.cancelButton.titleLabel?.font = UIFont.systemFontOfSize(13)
alert.cornerRadius = 5
alert.show()
return
}
var dest = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("ROLQuestionareController") as! ROLQuestionareController
dest.questions = self.questionare.questions
dest.questionareID = self.questionare.uuid
// reset answers in memory
ROLQuestionManager.sharedManager.resetAnswers()
self.presentViewController(dest, animated: true) { () -> Void in
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.setup()
self.setupData()
self.setupNotifications()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if !ROLUserInfoManager.sharedManager.isUserLogin { return }
// if self.startBtn.titleLabel?.text == "正在提交答案..." { return }
if ROLQuestionManager.sharedManager.isQuestionareAnswered(self.questionare.uuid) {
self.startBtn.setTitle("您已答过", forState: .Normal)
self.startBtn.enabled = false
} else {
self.startBtn.setTitle("马上参与", forState: .Normal)
self.startBtn.enabled = true
}
}
// MARK: - private
private func setupNotifications() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleUserFinishedAnswerQuestionareNotification", name: ROLNotifications.userFinishedAnswerQuestionareNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleUserDidFinishedAnswerQuestionareNotification", name: ROLNotifications.userDidFinishedAnswerQuestionareNotification, object: nil)
}
@objc private func handleUserFinishedAnswerQuestionareNotification() {
// self.startBtn.setTitle("正在提交答案...", forState: .Normal)
SEProgressHUDTool.showMessage("正在提交答案...", toView: self.view)
self.startBtn.enabled = false
}
@objc private func handleUserDidFinishedAnswerQuestionareNotification() {
self.startBtn.setTitle("您已答过", forState: .Normal)
SEProgressHUDTool.hideHUDForView(self.view)
self.startBtn.enabled = false
}
func setup() {
self.navigationItem.title = "问卷详情"
titleLabel.text = questionare.title
descLabel.text = questionare.desc
participantLabel.text = String(format: "%d 人", questionare.participant)
pointLabel.text = String(format: "%d 积分", questionare.point)
requiredTimeLabel.text = String(format: "%d 分钟", 3)
self.watchBtn.enabled = false
}
func setupData() {
if questionare.questions.count == 0 {
self.startBtn.enabled = false
self.startBtn.setTitle("数据加载中", forState: .Normal)
self.indicator.hidden = false
self.indicator.startAnimating()
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
ROLQuestionManager.sharedManager.getQuestions(questionare.questionCount, questionare: questionare) { () -> Void in
println("get questions success -- ")
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.startBtn.setTitle("马上参与", forState: .Normal)
self.watchBtn.setTitle("关注问卷", forState: .Normal)
self.startBtn.enabled = true
self.watchBtn.enabled = true
self.indicator.stopAnimating()
self.indicator.hidden = true
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
})
if (self.delegate?.respondsToSelector("homeDetailControllerDidGetQuestions:") != nil) {
self.delegate?.homeDetailControllerDidGetQuestions(self, questionare: self.questionare)
}
}
} else {
self.startBtn.setTitle("马上参与", forState: .Normal)
self.watchBtn.setTitle("关注问卷", forState: .Normal)
self.startBtn.enabled = true
self.watchBtn.enabled = true
self.indicator.stopAnimating()
self.indicator.hidden = true
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
var watchList = ROLUserInfoManager.sharedManager.getWatchListForCurrentUser()
for i in watchList {
if self.questionare.uuid == i {
self.watchBtn.setTitle("已关注 √", forState: .Normal)
self.watchBtn.setTitleColor(UIColor.coolGrayColor(), forState: .Normal)
self.watch = true
return
}
}
self.watchBtn.setTitle("关注问卷", forState: .Normal)
self.watchBtn.setTitleColor(self.sysBtnColor, forState: .Normal)
self.watch = false
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var dest = segue.destinationViewController as! ROLQuestionareController
dest.questions = self.questionare.questions
dest.questionareID = self.questionare.uuid
// reset answers in memory
ROLQuestionManager.sharedManager.resetAnswers()
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
| mit |
PopcornTimeTV/PopcornTimeTV | PopcornTime/UI/Shared/Collection View Controllers/DescriptionCollectionViewController.swift | 1 | 4654 |
import Foundation
class DescriptionCollectionViewController: ResponsiveCollectionViewController, UICollectionViewDelegateFlowLayout {
var headerTitle: String?
var sizingCell: DescriptionCollectionViewCell?
var dataSource: [(key: Any, value: String)] = [("", "")]
var isDark = true {
didSet {
guard isDark != oldValue else { return }
collectionView?.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.register(UINib(nibName: String(describing: DescriptionCollectionViewCell.self), bundle: nil), forCellWithReuseIdentifier: "cell")
}
override func collectionView(_ collectionView: UICollectionView, layout: UICollectionViewFlowLayout, didChangeToSize size: CGSize) {
var estimatedContentHeight: CGFloat = 0.0
for section in 0..<collectionView.numberOfSections {
let headerSize = self.collectionView(collectionView, layout: layout, referenceSizeForHeaderInSection: section)
estimatedContentHeight += headerSize.height
let numberOfCells = collectionView.numberOfItems(inSection: section)
for item in 0..<numberOfCells {
let itemSize = self.collectionView(collectionView, layout: layout, sizeForItemAt: IndexPath(item: item, section: section))
estimatedContentHeight += itemSize.height + layout.minimumLineSpacing
}
}
super.collectionView(collectionView, layout: layout, didChangeToSize: CGSize(width: collectionView.bounds.width, height: estimatedContentHeight))
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! DescriptionCollectionViewCell
let data = dataSource[indexPath.row]
if let text = data.key as? String {
cell.keyLabel.text = text
} else if let attributedText = data.key as? NSAttributedString {
cell.keyLabel.attributedText = attributedText
}
cell.valueLabel.text = data.value
cell.isDark = isDark
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let data = dataSource[indexPath.row]
sizingCell = sizingCell ?? .fromNib()
if let text = data.key as? String {
sizingCell?.keyLabel.text = text
} else if let attributedText = data.key as? NSAttributedString {
sizingCell?.keyLabel.attributedText = attributedText
}
sizingCell?.valueLabel.text = data.value
sizingCell?.setNeedsLayout()
sizingCell?.layoutIfNeeded()
let maxWidth = collectionView.bounds.width
let targetSize = CGSize(width: maxWidth, height: 0)
return sizingCell?.contentView.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: UILayoutPriority.required, verticalFittingPriority: UILayoutPriority.fittingSizeLevel) ?? .zero
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataSource.count
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return headerTitle == nil ? .zero : CGSize(width: collectionView.bounds.width, height: 50)
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if kind == UICollectionView.elementKindSectionHeader, let title = headerTitle {
let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "header", for: indexPath)
let titleLabel = view.viewWithTag(1) as? UILabel
titleLabel?.text = title
titleLabel?.textColor = isDark ? .white : .black
return view
}
return super.collectionView(collectionView, viewForSupplementaryElementOfKind: kind, at: indexPath)
}
}
| gpl-3.0 |
Webtrekk/webtrekk-ios-sdk | Source/Internal/Features/ExceptionTrackerImpl.swift | 1 | 18138 | import Foundation
//these function should be global due to requriements to NSSetUncaughtExceptionHandler
private func exceptionHandler(exception: NSException) {
defer {
// init old handler
if let oldHandler = ExceptionTrackerImpl.previousExceptionHandler {
oldHandler(exception)
}
}
//Save exception to file
WebtrekkTracking.defaultLogger.logDebug("""
Webtrekk catched exception: \(exception),
callStack: \(exception.callStackSymbols),
reason: \(exception.reason ?? "nil"),
name: \(exception.name),
user info: \(String(describing: exception.userInfo)),
return address: \(exception.callStackReturnAddresses)
""")
ExceptionSaveAndSendHelper.default.saveToFile(name: exception.name.rawValue,
stack: exception.callStackSymbols,
reason: exception.reason,
userInfo: exception.userInfo as NSDictionary?,
stackReturnAddress: exception.callStackReturnAddresses)
}
#if !os(watchOS)
//these function should be global due to requriements to signal handler API
private func signalHandler(signalNum: Int32) {
let signalsMap: [Int32: String] = [4: "SIGILL",
5: "SIGTRAP",
6: "SIGABRT",
8: "SIGFPE",
10: "SIGBUS",
11: "SIGSEGV",
13: "SIGPIPE"]
//Save exception to file
defer {
if let oldSignal = ExceptionTrackerImpl.previousSignalHandlers[signalNum] {
//just call original one it should exit
oldSignal(signalNum)
}
exit(signalNum)
}
//Save exception to file
WebtrekkTracking.defaultLogger.logDebug("""
Webtrekk catched signal: \(signalsMap[signalNum] ?? "undefined") with dump: \(Thread.callStackSymbols)
""")
// remove first two items as this is handler function items.
let stack = Array(Thread.callStackSymbols.suffix(from: 2))
ExceptionSaveAndSendHelper.default.saveToFile(name: "Signal: \(signalsMap[signalNum] ?? "undefined")",
stack: stack,
reason: nil,
userInfo: nil,
stackReturnAddress: nil)
}
#endif
class ExceptionTrackerImpl: ExceptionTracker {
// use var to make it lazy initialized.
static var previousExceptionHandler: ExceptionHandler = nil
private static var initialized = false
fileprivate static var previousSignalHandlers = [Int32: SignalHanlder]()
#if !os(watchOS)
private let signals: [Int32] = [SIGABRT, SIGILL, SIGSEGV, SIGFPE, SIGBUS, SIGPIPE, SIGTRAP]
#endif
private var errorLogLevel: ErrorLogLevel = .disable
typealias SignalHanlder = (@convention(c) (Int32) -> Swift.Void)
typealias ExceptionHandler = (@convention(c) (NSException) -> Swift.Void)?
fileprivate enum ErrorLogLevel: Int {
case disable, fatal, catched, info
}
//here should be defined exceptionTrackingMode
func initializeExceptionTracking(config: TrackerConfiguration) {
// init only once
guard !ExceptionTrackerImpl.initialized else {
return
}
if let errorLogLevel = config.errorLogLevel, (0...3).contains(errorLogLevel) {
self.errorLogLevel = ErrorLogLevel(rawValue: errorLogLevel)!
}
guard satisfyToLevel(level: .fatal) else {
// don't do anything for disable level
ExceptionTrackerImpl.initialized = true
return
}
installUncaughtExceptionHandler()
ExceptionTrackerImpl.initialized = true
}
func sendSavedException() {
guard satisfyToLevel(level: .fatal) else {
// don't do anything for disable level
return
}
ExceptionSaveAndSendHelper.default.loadAndSend(logLevel: self.errorLogLevel)
}
deinit {
guard ExceptionTrackerImpl.initialized else {
return
}
NSSetUncaughtExceptionHandler(ExceptionTrackerImpl.previousExceptionHandler)
ExceptionTrackerImpl.previousExceptionHandler = nil
#if !os(watchOS)
for signalNum in self.signals {
// restore signals back
signal(signalNum, ExceptionTrackerImpl.previousSignalHandlers[signalNum])
}
#endif
ExceptionTrackerImpl.initialized = false
}
private func installUncaughtExceptionHandler() {
// save previous exception handler
ExceptionTrackerImpl.previousExceptionHandler = NSGetUncaughtExceptionHandler()
// set Webtrekk one
NSSetUncaughtExceptionHandler(exceptionHandler)
#if !os(watchOS)
// setup processing for signals. Save old processing as well
for signalNum in self.signals {
// set Webtrekk signal handler and get previoius one
let oldSignal = signal(signalNum, signalHandler)
// save previoius signal handler
if oldSignal != nil {
ExceptionTrackerImpl.previousSignalHandlers[signalNum] = oldSignal
}
}
#endif
WebtrekkTracking.defaultLogger.logDebug("exception tracking has been initialized")
}
func trackInfo(_ name: String, message: String) {
guard checkIfInitialized() else {
return
}
guard satisfyToLevel(level: .info) else {
WebtrekkTracking.defaultLogger.logDebug("""
Tracking level isn't correspond to info/warning level. No tracking will be done.
""")
return
}
ExceptionSaveAndSendHelper.default.track(logLevel: self.errorLogLevel, name: name, message: message)
}
func trackException(_ exception: NSException) {
guard checkIfInitialized() else {
return
}
guard satisfyToLevel(level: .catched) else {
WebtrekkTracking.defaultLogger.logDebug("""
Tracking level isn't correspond to caught/exception level. No tracking will be done.
""")
return
}
ExceptionSaveAndSendHelper.default.track(logLevel: self.errorLogLevel,
name: exception.name.rawValue,
stack: exception.callStackSymbols,
message: exception.reason,
userInfo: exception.userInfo as NSDictionary?,
stackReturnAddress: exception.callStackReturnAddresses)
}
func trackError(_ error: Error) {
guard checkIfInitialized() else {
return
}
guard satisfyToLevel(level: .catched) else {
WebtrekkTracking.defaultLogger.logDebug("""
Tracking level isn't correspond to caught/exception level. No tracking will be done.
""")
return
}
ExceptionSaveAndSendHelper.default.track(logLevel: self.errorLogLevel,
name: "Error",
message: error.localizedDescription)
}
func trackNSError(_ error: NSError) {
guard checkIfInitialized() else {
return
}
guard satisfyToLevel(level: .catched) else {
WebtrekkTracking.defaultLogger.logDebug("""
Tracking level isn't correspond to caught/exception level. No tracking will be done.
""")
return
}
ExceptionSaveAndSendHelper.default.track(logLevel: self.errorLogLevel, name: "NSError",
message: "code:\(error.code), domain:\(error.domain)",
userInfo: error.userInfo as NSDictionary?)
}
private func checkIfInitialized() -> Bool {
if !ExceptionTrackerImpl.initialized {
logError("Webtrekk exception tracking isn't initialited")
}
return ExceptionTrackerImpl.initialized
}
private func satisfyToLevel(level: ErrorLogLevel) -> Bool {
return self.errorLogLevel.rawValue >= level.rawValue
}
}
private class ExceptionSaveAndSendHelper {
private var applicationSupportDir: URL?
private let exceptionFileName = "webtrekk_exception"
private let maxParameterLength = 255
private let saveDirectory: FileManager.SearchPathDirectory
// set it var to make it lazy
fileprivate static var `default` = ExceptionSaveAndSendHelper()
init() {
#if os(tvOS)
saveDirectory = .cachesDirectory
#else
saveDirectory = .applicationSupportDirectory
#endif
self.applicationSupportDir = FileManager.default.urls(for: saveDirectory,
in: .userDomainMask).first?.appendingPathComponent("Webtrekk")
}
private func normalizeStack(stack: [String]?) -> NSString {
let returnStack = stack?.joined(separator: "|")
.replacingOccurrences(of: "\\s{2,}", with: " ", options: .regularExpression, range: nil)
return normalizeField(field: returnStack, fieldName: "stack")
}
private func normalizeUserInfo(userInfo: NSDictionary?) -> NSString {
let userInfo = userInfo?.compactMap { key, value in
return "\(key):\(value);"
}.joined()
return normalizeField(field: userInfo, fieldName: "user info")
}
private func normalizeUserReturnAddress(returnAddress: [NSNumber]?) -> NSString {
let returnValue = returnAddress?.compactMap({$0.stringValue}).joined(separator: " ")
return normalizeField(field: returnValue, fieldName: "stack return address")
}
// make string not more then 255 length TODO: use Swift4 for this converstions
private func normalizeField(field: String?, fieldName: String) -> NSString {
guard let fieldUtf8 = field?.utf8CString, !fieldUtf8.isEmpty else {
return ""
}
guard fieldUtf8.count <= 255 else {
WebtrekkTracking.defaultLogger.logWarning("""
Field \(fieldName) is more then 255 length during excception tracking.
Normalize it by cutting to 255 length.
""")
let cutUTF8Field = Array(fieldUtf8.prefix(maxParameterLength))
return cutUTF8Field.withUnsafeBytes { buffer in
return NSString(bytes: buffer.baseAddress!,
length: maxParameterLength,
encoding: String.Encoding.utf8.rawValue)!
}
}
return NSString(string: field ?? "")
}
fileprivate func saveToFile(name: String,
stack: [String],
reason: String?,
userInfo: NSDictionary?,
stackReturnAddress: [NSNumber]?) {
saveToFile(name: normalizeField(field: name, fieldName: "name"),
stack: normalizeStack(stack: stack),
reason: normalizeField(field: reason, fieldName: "reason"),
userInfo: normalizeUserInfo(userInfo: userInfo),
stackReturnAddress: normalizeUserReturnAddress(returnAddress: stackReturnAddress))
}
private func saveToFile(name: NSString,
stack: NSString,
reason: NSString,
userInfo: NSString,
stackReturnAddress: NSString) {
// get url
guard let url = newFileURL else {
return
}
let array: NSArray = [name, stack, reason, userInfo, stackReturnAddress]
//construct string
guard array.write(to: url, atomically: true) else {
WebtrekkTracking.defaultLogger.logError("""
Can't save exception with url: \(url). Exception tracking won't be done.
""")
return
}
}
private var newFileURL: URL? {
var url: URL
var i: Int = 0
repeat {
let urlValue = applicationSupportDir?.appendingPathComponent(exceptionFileName+"\(i)"+".xml")
if urlValue == nil {
WebtrekkTracking.defaultLogger.logError("""
Can't define path for saving exception.
Exception tracking for fatal exception won't work.
""")
return nil
} else {
url = urlValue!
}
i = i + 1
} while FileManager.default.fileExists(atPath: url.path)
return url
}
private var existedFileURL: URL? {
guard let supportDir = applicationSupportDir?.path else {
WebtrekkTracking.defaultLogger.logError("""
Can't define path for reading exception.
Exception tracking for fatal exception won't work.
""")
return nil
}
let enumerator = FileManager.default.enumerator(atPath: supportDir)
var minimumNumber: Int? = nil
var fileName: String? = nil
//find file with minimumID
enumerator?.forEach { value in
if let strValue = value as? String, strValue.contains(exceptionFileName) {
if let range = strValue.range(of: "\\d", options: .regularExpression),
let number = Int(strValue[range]) {
if minimumNumber == nil || minimumNumber! > number {
minimumNumber = number
fileName = strValue
}
}
}
}
guard let _ = fileName else {
return nil
}
return applicationSupportDir?.appendingPathComponent(fileName!)
}
// send exception that is saved on NAND
fileprivate func loadAndSend(logLevel: ExceptionTrackerImpl.ErrorLogLevel) {
while let url = self.existedFileURL {
defer {
// delete file
do {
try FileManager.default.removeItem(atPath: url.path)
} catch let error {
WebtrekkTracking.defaultLogger.logError("""
Serious problem with saved exception file deletion: \(error).
Information about exception can be sent several times.
""")
}
}
guard let array = NSArray(contentsOf: url) as? [NSString] else {
continue
}
// send action
track(logLevel: logLevel,
name: array[0],
stack: array[1],
message: array[2],
userInfo: array[3],
stackReturnAddress: array[4])
}
}
fileprivate func track(logLevel: ExceptionTrackerImpl.ErrorLogLevel,
name: String, stack: [String]? = nil,
message: String? = nil,
userInfo: NSDictionary? = nil,
stackReturnAddress: [NSNumber]? = nil) {
track(logLevel: logLevel,
name: normalizeField(field: name, fieldName: "name"),
stack: normalizeStack(stack: stack),
message: normalizeField(field: message, fieldName: "message/reason"),
userInfo: normalizeUserInfo(userInfo: userInfo),
stackReturnAddress: normalizeUserReturnAddress(returnAddress: stackReturnAddress))
}
// common function for tracking exception field message can be as message and reason
private func track(logLevel: ExceptionTrackerImpl.ErrorLogLevel,
name: NSString? = nil,
stack: NSString? = nil,
message: NSString? = nil,
userInfo: NSString? = nil,
stackReturnAddress: NSString? = nil) {
guard let webtrekk = WebtrekkTracking.instance() as? DefaultTracker else {
WebtrekkTracking.defaultLogger.logDebug("Can't convert to DefaultTracker for sending event")
return
}
guard logLevel.rawValue > ExceptionTrackerImpl.ErrorLogLevel.disable.rawValue else {
WebtrekkTracking.defaultLogger.logDebug("Error level is disabled. Won't do any call")
return
}
//define details
var details: [Int: TrackingValue] = [:]
details[910] = .constant(String(logLevel.rawValue))
if let name = name as String?, !name.isEmpty {
details[911] = .constant(name)
}
if let message = message as String?, !message.isEmpty {
details[912] = .constant(message)
}
if let stack = stack as String?, !stack.isEmpty {
details[913] = .constant(stack)
}
if let userInfo = userInfo as String?, !userInfo.isEmpty {
details[916] = .constant(userInfo)
}
if let stackReturnAddress = stackReturnAddress as String?, !stackReturnAddress.isEmpty {
details[917] = .constant(stackReturnAddress)
}
let action = ActionEvent(actionProperties: ActionProperties(name: "webtrekk_ignore", details: details),
pageProperties: PageProperties(name: nil))
webtrekk.enqueueRequestForEvent(action, type: .exceptionTracking)
}
}
| mit |
coylums/arcturus | arcturus/arcturus/Helpers/StringHelper.swift | 1 | 139 | //
// StringHelper.swift
// Arcturus
//
// Created by William Woolard on 8/3/14.
// Copyright (c) 2014 coylums. All rights reserved.
// | mit |
aleksandrshoshiashvili/AwesomeSpotlightView | AwesomeSpotlightViewDemoObjC/Pods/AwesomeSpotlightView/AwesomeSpotlightView/Classes/AwesomeTabButton.swift | 2 | 582 | //
// AwesomeTabButton.swift
// AwesomeSpotlightViewDemo
//
// Created by Alexander Shoshiashvili on 11/02/2018.
// Copyright © 2018 Alex Shoshiashvili. All rights reserved.
//
import UIKit
public struct AwesomeTabButton {
public var title: String
public var font: UIFont
public var isEnable: Bool
public var backgroundColor: UIColor?
public init(title: String, font: UIFont, isEnable: Bool = true, backgroundColor: UIColor? = nil) {
self.title = title
self.font = font
self.isEnable = isEnable
self.backgroundColor = backgroundColor
}
}
| mit |
TonnyTao/HowSwift | how_to_update_view_in_mvvm.playground/Sources/RxSwift/RxSwift/Observables/Concat.swift | 8 | 5067 | //
// Concat.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Concatenates the second observable sequence to `self` upon successful termination of `self`.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- parameter second: Second observable sequence.
- returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence.
*/
public func concat<Source: ObservableConvertibleType>(_ second: Source) -> Observable<Element> where Source.Element == Element {
Observable.concat([self.asObservable(), second.asObservable()])
}
}
extension ObservableType {
/**
Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully.
This operator has tail recursive optimizations that will prevent stack overflow.
Optimizations will be performed in cases equivalent to following:
[1, [2, [3, .....].concat()].concat].concat()
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat<Sequence: Swift.Sequence>(_ sequence: Sequence) -> Observable<Element>
where Sequence.Element == Observable<Element> {
return Concat(sources: sequence, count: nil)
}
/**
Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully.
This operator has tail recursive optimizations that will prevent stack overflow.
Optimizations will be performed in cases equivalent to following:
[1, [2, [3, .....].concat()].concat].concat()
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat<Collection: Swift.Collection>(_ collection: Collection) -> Observable<Element>
where Collection.Element == Observable<Element> {
return Concat(sources: collection, count: Int64(collection.count))
}
/**
Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully.
This operator has tail recursive optimizations that will prevent stack overflow.
Optimizations will be performed in cases equivalent to following:
[1, [2, [3, .....].concat()].concat].concat()
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat(_ sources: Observable<Element> ...) -> Observable<Element> {
Concat(sources: sources, count: Int64(sources.count))
}
}
final private class ConcatSink<Sequence: Swift.Sequence, Observer: ObserverType>
: TailRecursiveSink<Sequence, Observer>
, ObserverType where Sequence.Element: ObservableConvertibleType, Sequence.Element.Element == Observer.Element {
typealias Element = Observer.Element
override init(observer: Observer, cancel: Cancelable) {
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<Element>){
switch event {
case .next:
self.forwardOn(event)
case .error:
self.forwardOn(event)
self.dispose()
case .completed:
self.schedule(.moveNext)
}
}
override func subscribeToNext(_ source: Observable<Element>) -> Disposable {
source.subscribe(self)
}
override func extract(_ observable: Observable<Element>) -> SequenceGenerator? {
if let source = observable as? Concat<Sequence> {
return (source.sources.makeIterator(), source.count)
}
else {
return nil
}
}
}
final private class Concat<Sequence: Swift.Sequence>: Producer<Sequence.Element.Element> where Sequence.Element: ObservableConvertibleType {
typealias Element = Sequence.Element.Element
fileprivate let sources: Sequence
fileprivate let count: IntMax?
init(sources: Sequence, count: IntMax?) {
self.sources = sources
self.count = count
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
let sink = ConcatSink<Sequence, Observer>(observer: observer, cancel: cancel)
let subscription = sink.run((self.sources.makeIterator(), self.count))
return (sink: sink, subscription: subscription)
}
}
| mit |
satorun/designPattern | Builder/BuilderUITests/BuilderUITests.swift | 1 | 1242 | //
// BuilderUITests.swift
// BuilderUITests
//
// Created by satorun on 2016/02/03.
// Copyright © 2016年 satorun. All rights reserved.
//
import XCTest
class BuilderUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| mit |
jiaopen/ImagePickerSheetController | ImagePickerSheetController/ImagePickerSheetController/PreviewSupplementaryView.swift | 1 | 2711 | //
// PreviewSupplementaryView.swift
// ImagePickerSheet
//
// Created by Laurin Brandner on 06/09/14.
// Copyright (c) 2014 Laurin Brandner. All rights reserved.
//
import UIKit
class PreviewSupplementaryView : UICollectionReusableView {
private let button: UIButton = {
let button = UIButton()
button.tintColor = .whiteColor()
button.userInteractionEnabled = false
button.setImage(PreviewSupplementaryView.checkmarkImage, forState: .Normal)
button.setImage(PreviewSupplementaryView.selectedCheckmarkImage, forState: .Selected)
return button
}()
var buttonInset = UIEdgeInsetsZero
var selected: Bool = false {
didSet {
button.selected = selected
reloadButtonBackgroundColor()
}
}
class var checkmarkImage: UIImage? {
let bundle = NSBundle(forClass: ImagePickerSheetController.self)
let image = UIImage(named: "PreviewSupplementaryView-Checkmark")
// let image = UIImage(contentsOfFile: bundle.pathForResource("PreviewSupplementaryView-Checkmark", ofType: "png")!)
return image?.imageWithRenderingMode(.AlwaysTemplate)
}
class var selectedCheckmarkImage: UIImage? {
let bundle = NSBundle(forClass: ImagePickerSheetController.self)
let image = UIImage(named: "PreviewSupplementaryView-Checkmark-Selected")
// let image = UIImage(contentsOfFile: bundle.pathForResource("PreviewSupplementaryView-Checkmark-Selected", ofType: "png")!)
return image?.imageWithRenderingMode(.AlwaysTemplate)
}
// MARK: - Initialization
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
private func initialize() {
addSubview(button)
}
// MARK: - Other Methods
override func prepareForReuse() {
super.prepareForReuse()
selected = false
}
override func tintColorDidChange() {
super.tintColorDidChange()
reloadButtonBackgroundColor()
}
private func reloadButtonBackgroundColor() {
button.backgroundColor = (selected) ? tintColor : nil
}
// MARK: - Layout
override func layoutSubviews() {
super.layoutSubviews()
button.sizeToFit()
button.frame.origin = CGPointMake(buttonInset.left, CGRectGetHeight(bounds)-CGRectGetHeight(button.frame)-buttonInset.bottom)
button.layer.cornerRadius = CGRectGetHeight(button.frame) / 2.0
}
}
| mit |
zSOLz/viper-base | ViperBase-Sample/ViperBase-Sample/Helpers/KeyboardHeightObserver.swift | 1 | 1937 | //
// KeyboardSizeObserver.swift
// ViperBase-Sample
//
// Created by SOL on 09.05.17.
// Copyright © 2017 SOL. All rights reserved.
//
import UIKit
class KeyboardHeightObserver {
var heightChangedClosure: ((CGFloat)->Void)?
init() {
NotificationCenter.default.addObserver(self,
selector: #selector(KeyboardHeightObserver.keyboardWillChangeSize(_:)),
name: .UIKeyboardWillChangeFrame,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(KeyboardHeightObserver.keyboardWillHide(_:)),
name: .UIKeyboardWillHide,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(KeyboardHeightObserver.keyboardWillShow(_:)),
name: .UIKeyboardWillShow,
object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
fileprivate extension KeyboardHeightObserver {
@objc func keyboardWillShow(_ notification: NSNotification) {
guard let frame = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect else {
return
}
heightChangedClosure?(frame.size.height)
}
@objc func keyboardWillHide(_ notification: NSNotification) {
heightChangedClosure?(0)
}
@objc func keyboardWillChangeSize(_ notification: NSNotification) {
guard let frame = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect else {
return
}
heightChangedClosure?(frame.size.height)
}
}
| mit |
apple/swift-syntax | Tests/PerformanceTest/SyntaxClassifierPerformanceTests.swift | 1 | 1097 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org 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 https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import XCTest
import IDEUtils
import SwiftSyntax
import SwiftSyntaxParser
public class SyntaxClassifierPerformanceTests: XCTestCase {
var inputFile: URL {
return URL(fileURLWithPath: #file)
.deletingLastPathComponent()
.appendingPathComponent("Inputs")
.appendingPathComponent("MinimalCollections.swift.input")
}
func testParsingPerformance() {
XCTAssertNoThrow(try {
let parsed = try SyntaxParser.parse(inputFile)
measure {
for _ in 0..<10 {
for _ in parsed.classifications {}
}
}
}())
}
}
| apache-2.0 |
fauve-/sunday-afternoon-swift | Sources/main.swift | 1 | 1863 | //so we're going to implement http://rosettacode.org/wiki/Globally_replace_text_in_several_files
//invoked like so `./fnr "my sweet text" file1 file2 file3 file4
//if those files are directories, we'll ignore them
//pretty much it
//it's a little weird not having an entrypoint function
//wonder how large programs do the whole
//int main(){
//init_state()
//main_loop()
//}
//idiom that is so common
//my it's my server-side background talking
//import glibc for exit etc
import Glibc
//let's go ahead and look at our arguments
//TODO: guards!
if Process.arguments.count < 3 {
print("Invoke like this \(Process.arguments[0]) <old string> <new string> <some files...>")
exit(-1)
}
//okay, now we need to do some real work I guess
//we have to revert back to c stuff to open some files
let toReplace = Process.arguments[1]
let newString = Process.arguments[2]
//remove the cruft
var filesToScan = Array<String>.init(Process.arguments)
filesToScan.removeFirst(3)
for filename in filesToScan {
//some dog and pony show to open up this pit
let UnsafeFileName = [UInt8](filename.utf8)
var unsafeFilePointer = UnsafeMutablePointer<Int8>(UnsafeFileName)
let fp = fopen(unsafeFilePointer,"r+")
let BUFSIZE = 1024
var buf = [CChar](count:BUFSIZE, repeatedValue:CChar(0))
fread(&buf,Int(1),Int(BUFSIZE),fp)
fclose(fp)
//let us now do some things
let contents = String.fromCString(buf)!
let newContents = contents.replace(toReplace,newString:newString)
let UnsafeNewContents = [UInt8](newContents.utf8)
//reopen file to get a new FILE* that will allow us to tuncate if the file lengths are different
let newfp = fopen(unsafeFilePointer,"w")
fwrite(UnsafeNewContents,Int(1),UnsafeNewContents.count,newfp);
fflush(newfp)
fclose(newfp)
}
| mit |
nuclearace/Starscream | Sources/Starscream/WebSocket.swift | 1 | 54685 | //////////////////////////////////////////////////////////////////////////////////////////////////
//
// Websocket.swift
//
// Created by Dalton Cherry on 7/16/14.
// Copyright (c) 2014-2017 Dalton Cherry.
//
// 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
import CoreFoundation
import SSCommonCrypto
public let WebsocketDidConnectNotification = "WebsocketDidConnectNotification"
public let WebsocketDidDisconnectNotification = "WebsocketDidDisconnectNotification"
public let WebsocketDisconnectionErrorKeyName = "WebsocketDisconnectionErrorKeyName"
//Standard WebSocket close codes
public enum CloseCode : UInt16 {
case normal = 1000
case goingAway = 1001
case protocolError = 1002
case protocolUnhandledType = 1003
// 1004 reserved.
case noStatusReceived = 1005
//1006 reserved.
case encoding = 1007
case policyViolated = 1008
case messageTooBig = 1009
}
public enum ErrorType: Error {
case outputStreamWriteError //output stream error during write
case compressionError
case invalidSSLError //Invalid SSL certificate
case writeTimeoutError //The socket timed out waiting to be ready to write
case protocolError //There was an error parsing the WebSocket frames
case upgradeError //There was an error during the HTTP upgrade
case closeError //There was an error during the close (socket probably has been dereferenced)
}
public struct WSError: Error {
public let type: ErrorType
public let message: String
public let code: Int
}
//WebSocketClient is setup to be dependency injection for testing
public protocol WebSocketClient: class {
var delegate: WebSocketDelegate? {get set}
var disableSSLCertValidation: Bool {get set}
var overrideTrustHostname: Bool {get set}
var desiredTrustHostname: String? {get set}
var sslClientCertificate: SSLClientCertificate? {get set}
#if os(Linux)
#else
var security: SSLTrustValidator? {get set}
var enabledSSLCipherSuites: [SSLCipherSuite]? {get set}
#endif
var isConnected: Bool {get}
func connect()
func disconnect(forceTimeout: TimeInterval?, closeCode: UInt16)
func write(string: String, completion: (() -> ())?)
func write(data: Data, completion: (() -> ())?)
func write(ping: Data, completion: (() -> ())?)
func write(pong: Data, completion: (() -> ())?)
}
//implements some of the base behaviors
extension WebSocketClient {
public func write(string: String) {
write(string: string, completion: nil)
}
public func write(data: Data) {
write(data: data, completion: nil)
}
public func write(ping: Data) {
write(ping: ping, completion: nil)
}
public func write(pong: Data) {
write(pong: pong, completion: nil)
}
public func disconnect() {
disconnect(forceTimeout: nil, closeCode: CloseCode.normal.rawValue)
}
}
//SSL settings for the stream
public struct SSLSettings {
public let useSSL: Bool
public let disableCertValidation: Bool
public var overrideTrustHostname: Bool
public var desiredTrustHostname: String?
public let sslClientCertificate: SSLClientCertificate?
#if os(Linux)
#else
public let cipherSuites: [SSLCipherSuite]?
#endif
}
public protocol WSStreamDelegate: class {
func newBytesInStream()
func streamDidError(error: Error?)
}
//This protocol is to allow custom implemention of the underlining stream. This way custom socket libraries (e.g. linux) can be used
public protocol WSStream {
var delegate: WSStreamDelegate? {get set}
func connect(url: URL, port: Int, timeout: TimeInterval, ssl: SSLSettings, completion: @escaping ((Error?) -> Void))
func write(data: Data) -> Int
func read() -> Data?
func cleanup()
#if os(Linux) || os(watchOS)
#else
func sslTrust() -> (trust: SecTrust?, domain: String?)
#endif
}
open class FoundationStream : NSObject, WSStream, StreamDelegate {
private static let sharedWorkQueue = DispatchQueue(label: "com.vluxe.starscream.websocket", attributes: [])
private var inputStream: InputStream?
private var outputStream: OutputStream?
public weak var delegate: WSStreamDelegate?
let BUFFER_MAX = 4096
public var enableSOCKSProxy = false
public func connect(url: URL, port: Int, timeout: TimeInterval, ssl: SSLSettings, completion: @escaping ((Error?) -> Void)) {
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
let h = url.host! as NSString
CFStreamCreatePairWithSocketToHost(nil, h, UInt32(port), &readStream, &writeStream)
inputStream = readStream!.takeRetainedValue()
outputStream = writeStream!.takeRetainedValue()
#if os(watchOS) //watchOS us unfortunately is missing the kCFStream properties to make this work
#else
if enableSOCKSProxy {
let proxyDict = CFNetworkCopySystemProxySettings()
let socksConfig = CFDictionaryCreateMutableCopy(nil, 0, proxyDict!.takeRetainedValue())
let propertyKey = CFStreamPropertyKey(rawValue: kCFStreamPropertySOCKSProxy)
CFWriteStreamSetProperty(outputStream, propertyKey, socksConfig)
CFReadStreamSetProperty(inputStream, propertyKey, socksConfig)
}
#endif
guard let inStream = inputStream, let outStream = outputStream else { return }
inStream.delegate = self
outStream.delegate = self
if ssl.useSSL {
inStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey)
outStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey)
#if os(watchOS) //watchOS us unfortunately is missing the kCFStream properties to make this work
#else
var settings = [NSObject: NSObject]()
if ssl.disableCertValidation {
settings[kCFStreamSSLValidatesCertificateChain] = NSNumber(value: false)
}
if ssl.overrideTrustHostname {
if let hostname = ssl.desiredTrustHostname {
settings[kCFStreamSSLPeerName] = hostname as NSString
} else {
settings[kCFStreamSSLPeerName] = kCFNull
}
}
if let sslClientCertificate = ssl.sslClientCertificate {
settings[kCFStreamSSLCertificates] = sslClientCertificate.streamSSLCertificates
}
inStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey)
outStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey)
#endif
#if os(Linux)
#else
if let cipherSuites = ssl.cipherSuites {
#if os(watchOS) //watchOS us unfortunately is missing the kCFStream properties to make this work
#else
if let sslContextIn = CFReadStreamCopyProperty(inputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext?,
let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? {
let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count)
let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count)
if resIn != errSecSuccess {
completion(WSError(type: .invalidSSLError, message: "Error setting ingoing cypher suites", code: Int(resIn)))
}
if resOut != errSecSuccess {
completion(WSError(type: .invalidSSLError, message: "Error setting outgoing cypher suites", code: Int(resOut)))
}
}
#endif
}
#endif
}
CFReadStreamSetDispatchQueue(inStream, FoundationStream.sharedWorkQueue)
CFWriteStreamSetDispatchQueue(outStream, FoundationStream.sharedWorkQueue)
inStream.open()
outStream.open()
var out = timeout// wait X seconds before giving up
FoundationStream.sharedWorkQueue.async { [weak self] in
while !outStream.hasSpaceAvailable {
usleep(100) // wait until the socket is ready
out -= 100
if out < 0 {
completion(WSError(type: .writeTimeoutError, message: "Timed out waiting for the socket to be ready for a write", code: 0))
return
} else if let error = outStream.streamError {
completion(error)
return // disconnectStream will be called.
} else if self == nil {
completion(WSError(type: .closeError, message: "socket object has been dereferenced", code: 0))
return
}
}
completion(nil) //success!
}
}
public func write(data: Data) -> Int {
guard let outStream = outputStream else {return -1}
let buffer = UnsafeRawPointer((data as NSData).bytes).assumingMemoryBound(to: UInt8.self)
return outStream.write(buffer, maxLength: data.count)
}
public func read() -> Data? {
guard let stream = inputStream else {return nil}
let buf = NSMutableData(capacity: BUFFER_MAX)
let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self)
let length = stream.read(buffer, maxLength: BUFFER_MAX)
if length < 1 {
return nil
}
return Data(bytes: buffer, count: length)
}
public func cleanup() {
if let stream = inputStream {
stream.delegate = nil
CFReadStreamSetDispatchQueue(stream, nil)
stream.close()
}
if let stream = outputStream {
stream.delegate = nil
CFWriteStreamSetDispatchQueue(stream, nil)
stream.close()
}
outputStream = nil
inputStream = nil
}
#if os(Linux) || os(watchOS)
#else
public func sslTrust() -> (trust: SecTrust?, domain: String?) {
guard let outputStream = outputStream else { return (nil, nil) }
let trust = outputStream.property(forKey: kCFStreamPropertySSLPeerTrust as Stream.PropertyKey) as! SecTrust?
var domain = outputStream.property(forKey: kCFStreamSSLPeerName as Stream.PropertyKey) as! String?
if domain == nil,
let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? {
var peerNameLen: Int = 0
SSLGetPeerDomainNameLength(sslContextOut, &peerNameLen)
var peerName = Data(count: peerNameLen)
let _ = peerName.withUnsafeMutableBytes { (peerNamePtr: UnsafeMutablePointer<Int8>) in
SSLGetPeerDomainName(sslContextOut, peerNamePtr, &peerNameLen)
}
if let peerDomain = String(bytes: peerName, encoding: .utf8), peerDomain.count > 0 {
domain = peerDomain
}
}
return (trust, domain)
}
#endif
/**
Delegate for the stream methods. Processes incoming bytes
*/
open func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
if eventCode == .hasBytesAvailable {
if aStream == inputStream {
delegate?.newBytesInStream()
}
} else if eventCode == .errorOccurred {
delegate?.streamDidError(error: aStream.streamError)
} else if eventCode == .endEncountered {
delegate?.streamDidError(error: nil)
}
}
}
//WebSocket implementation
//standard delegate you should use
public protocol WebSocketDelegate: class {
func websocketDidConnect(socket: WebSocketClient)
func websocketDidDisconnect(socket: WebSocketClient, error: Error?)
func websocketDidReceiveMessage(socket: WebSocketClient, text: String)
func websocketDidReceiveData(socket: WebSocketClient, data: Data)
}
//got pongs
public protocol WebSocketPongDelegate: class {
func websocketDidReceivePong(socket: WebSocketClient, data: Data?)
}
// A Delegate with more advanced info on messages and connection etc.
public protocol WebSocketAdvancedDelegate: class {
func websocketDidConnect(socket: WebSocket)
func websocketDidDisconnect(socket: WebSocket, error: Error?)
func websocketDidReceiveMessage(socket: WebSocket, text: String, response: WebSocket.WSResponse)
func websocketDidReceiveData(socket: WebSocket, data: Data, response: WebSocket.WSResponse)
func websocketHttpUpgrade(socket: WebSocket, request: String)
func websocketHttpUpgrade(socket: WebSocket, response: String)
}
open class WebSocket : NSObject, StreamDelegate, WebSocketClient, WSStreamDelegate {
public enum OpCode : UInt8 {
case continueFrame = 0x0
case textFrame = 0x1
case binaryFrame = 0x2
// 3-7 are reserved.
case connectionClose = 0x8
case ping = 0x9
case pong = 0xA
// B-F reserved.
}
public static let ErrorDomain = "WebSocket"
// Where the callback is executed. It defaults to the main UI thread queue.
public var callbackQueue = DispatchQueue.main
// MARK: - Constants
let headerWSUpgradeName = "Upgrade"
let headerWSUpgradeValue = "websocket"
let headerWSHostName = "Host"
let headerWSConnectionName = "Connection"
let headerWSConnectionValue = "Upgrade"
let headerWSProtocolName = "Sec-WebSocket-Protocol"
let headerWSVersionName = "Sec-WebSocket-Version"
let headerWSVersionValue = "13"
let headerWSExtensionName = "Sec-WebSocket-Extensions"
let headerWSKeyName = "Sec-WebSocket-Key"
let headerOriginName = "Origin"
let headerWSAcceptName = "Sec-WebSocket-Accept"
let BUFFER_MAX = 4096
let FinMask: UInt8 = 0x80
let OpCodeMask: UInt8 = 0x0F
let RSVMask: UInt8 = 0x70
let RSV1Mask: UInt8 = 0x40
let MaskMask: UInt8 = 0x80
let PayloadLenMask: UInt8 = 0x7F
let MaxFrameSize: Int = 32
let httpSwitchProtocolCode = 101
let supportedSSLSchemes = ["wss", "https"]
public class WSResponse {
var isFin = false
public var code: OpCode = .continueFrame
var bytesLeft = 0
public var frameCount = 0
public var buffer: NSMutableData?
public let firstFrame = {
return Date()
}()
}
// MARK: - Delegates
/// Responds to callback about new messages coming in over the WebSocket
/// and also connection/disconnect messages.
public weak var delegate: WebSocketDelegate?
/// The optional advanced delegate can be used instead of of the delegate
public weak var advancedDelegate: WebSocketAdvancedDelegate?
/// Receives a callback for each pong message recived.
public weak var pongDelegate: WebSocketPongDelegate?
public var onConnect: (() -> Void)?
public var onDisconnect: ((Error?) -> Void)?
public var onText: ((String) -> Void)?
public var onData: ((Data) -> Void)?
public var onPong: ((Data?) -> Void)?
public var disableSSLCertValidation = false
public var overrideTrustHostname = false
public var desiredTrustHostname: String? = nil
public var sslClientCertificate: SSLClientCertificate? = nil
public var enableCompression = true
#if os(Linux)
#else
public var security: SSLTrustValidator?
public var enabledSSLCipherSuites: [SSLCipherSuite]?
#endif
public var isConnected: Bool {
mutex.lock()
let isConnected = connected
mutex.unlock()
return isConnected
}
public var request: URLRequest //this is only public to allow headers, timeout, etc to be modified on reconnect
public var currentURL: URL { return request.url! }
public var respondToPingWithPong: Bool = true
// MARK: - Private
private struct CompressionState {
var supportsCompression = false
var messageNeedsDecompression = false
var serverMaxWindowBits = 15
var clientMaxWindowBits = 15
var clientNoContextTakeover = false
var serverNoContextTakeover = false
var decompressor:Decompressor? = nil
var compressor:Compressor? = nil
}
private var stream: WSStream
private var connected = false
private var isConnecting = false
private let mutex = NSLock()
private var compressionState = CompressionState()
private var writeQueue = OperationQueue()
private var readStack = [WSResponse]()
private var inputQueue = [Data]()
private var fragBuffer: Data?
private var certValidated = false
private var didDisconnect = false
private var readyToWrite = false
private var headerSecKey = ""
private var canDispatch: Bool {
mutex.lock()
let canWork = readyToWrite
mutex.unlock()
return canWork
}
/// Used for setting protocols.
public init(request: URLRequest, protocols: [String]? = nil, stream: WSStream = FoundationStream()) {
self.request = request
self.stream = stream
if request.value(forHTTPHeaderField: headerOriginName) == nil {
guard let url = request.url else {return}
var origin = url.absoluteString
if let hostUrl = URL (string: "/", relativeTo: url) {
origin = hostUrl.absoluteString
origin.remove(at: origin.index(before: origin.endIndex))
}
self.request.setValue(origin, forHTTPHeaderField: headerOriginName)
}
if let protocols = protocols {
self.request.setValue(protocols.joined(separator: ","), forHTTPHeaderField: headerWSProtocolName)
}
writeQueue.maxConcurrentOperationCount = 1
}
public convenience init(url: URL, protocols: [String]? = nil) {
var request = URLRequest(url: url)
request.timeoutInterval = 5
self.init(request: request, protocols: protocols)
}
// Used for specifically setting the QOS for the write queue.
public convenience init(url: URL, writeQueueQOS: QualityOfService, protocols: [String]? = nil) {
self.init(url: url, protocols: protocols)
writeQueue.qualityOfService = writeQueueQOS
}
/**
Connect to the WebSocket server on a background thread.
*/
open func connect() {
guard !isConnecting else { return }
didDisconnect = false
isConnecting = true
createHTTPRequest()
}
/**
Disconnect from the server. I send a Close control frame to the server, then expect the server to respond with a Close control frame and close the socket from its end. I notify my delegate once the socket has been closed.
If you supply a non-nil `forceTimeout`, I wait at most that long (in seconds) for the server to close the socket. After the timeout expires, I close the socket and notify my delegate.
If you supply a zero (or negative) `forceTimeout`, I immediately close the socket (without sending a Close control frame) and notify my delegate.
- Parameter forceTimeout: Maximum time to wait for the server to close the socket.
- Parameter closeCode: The code to send on disconnect. The default is the normal close code for cleanly disconnecting a webSocket.
*/
open func disconnect(forceTimeout: TimeInterval? = nil, closeCode: UInt16 = CloseCode.normal.rawValue) {
guard isConnected else { return }
switch forceTimeout {
case .some(let seconds) where seconds > 0:
let milliseconds = Int(seconds * 1_000)
callbackQueue.asyncAfter(deadline: .now() + .milliseconds(milliseconds)) { [weak self] in
self?.disconnectStream(nil)
}
fallthrough
case .none:
writeError(closeCode)
default:
disconnectStream(nil)
break
}
}
/**
Write a string to the websocket. This sends it as a text frame.
If you supply a non-nil completion block, I will perform it when the write completes.
- parameter string: The string to write.
- parameter completion: The (optional) completion handler.
*/
open func write(string: String, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(string.data(using: String.Encoding.utf8)!, code: .textFrame, writeCompletion: completion)
}
/**
Write binary data to the websocket. This sends it as a binary frame.
If you supply a non-nil completion block, I will perform it when the write completes.
- parameter data: The data to write.
- parameter completion: The (optional) completion handler.
*/
open func write(data: Data, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(data, code: .binaryFrame, writeCompletion: completion)
}
/**
Write a ping to the websocket. This sends it as a control frame.
Yodel a sound to the planet. This sends it as an astroid. http://youtu.be/Eu5ZJELRiJ8?t=42s
*/
open func write(ping: Data, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(ping, code: .ping, writeCompletion: completion)
}
/**
Write a pong to the websocket. This sends it as a control frame.
Respond to a Yodel.
*/
open func write(pong: Data, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(pong, code: .pong, writeCompletion: completion)
}
/**
Private method that starts the connection.
*/
private func createHTTPRequest() {
guard let url = request.url else {return}
var port = url.port
if port == nil {
if supportedSSLSchemes.contains(url.scheme!) {
port = 443
} else {
port = 80
}
}
request.setValue(headerWSUpgradeValue, forHTTPHeaderField: headerWSUpgradeName)
request.setValue(headerWSConnectionValue, forHTTPHeaderField: headerWSConnectionName)
headerSecKey = generateWebSocketKey()
request.setValue(headerWSVersionValue, forHTTPHeaderField: headerWSVersionName)
request.setValue(headerSecKey, forHTTPHeaderField: headerWSKeyName)
if enableCompression {
let val = "permessage-deflate; client_max_window_bits; server_max_window_bits=15"
request.setValue(val, forHTTPHeaderField: headerWSExtensionName)
}
let hostValue = request.allHTTPHeaderFields?[headerWSHostName] ?? "\(url.host!):\(port!)"
request.setValue(hostValue, forHTTPHeaderField: headerWSHostName)
var path = url.absoluteString
let offset = (url.scheme?.count ?? 2) + 3
path = String(path[path.index(path.startIndex, offsetBy: offset)..<path.endIndex])
if let range = path.range(of: "/") {
path = String(path[range.lowerBound..<path.endIndex])
} else {
path = "/"
if let query = url.query {
path += "?" + query
}
}
var httpBody = "\(request.httpMethod ?? "GET") \(path) HTTP/1.1\r\n"
if let headers = request.allHTTPHeaderFields {
for (key, val) in headers {
httpBody += "\(key): \(val)\r\n"
}
}
httpBody += "\r\n"
initStreamsWithData(httpBody.data(using: .utf8)!, Int(port!))
advancedDelegate?.websocketHttpUpgrade(socket: self, request: httpBody)
}
/**
Generate a WebSocket key as needed in RFC.
*/
private func generateWebSocketKey() -> String {
var key = ""
let seed = 16
for _ in 0..<seed {
let uni = UnicodeScalar(UInt32(97 + arc4random_uniform(25)))
key += "\(Character(uni!))"
}
let data = key.data(using: String.Encoding.utf8)
let baseKey = data?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
return baseKey!
}
/**
Start the stream connection and write the data to the output stream.
*/
private func initStreamsWithData(_ data: Data, _ port: Int) {
guard let url = request.url else {
disconnectStream(nil, runDelegate: true)
return
}
// Disconnect and clean up any existing streams before setting up a new pair
disconnectStream(nil, runDelegate: false)
let useSSL = supportedSSLSchemes.contains(url.scheme!)
#if os(Linux)
let settings = SSLSettings(useSSL: useSSL,
disableCertValidation: disableSSLCertValidation,
overrideTrustHostname: overrideTrustHostname,
desiredTrustHostname: desiredTrustHostname),
sslClientCertificate: sslClientCertificate
#else
let settings = SSLSettings(useSSL: useSSL,
disableCertValidation: disableSSLCertValidation,
overrideTrustHostname: overrideTrustHostname,
desiredTrustHostname: desiredTrustHostname,
sslClientCertificate: sslClientCertificate,
cipherSuites: self.enabledSSLCipherSuites)
#endif
certValidated = !useSSL
let timeout = request.timeoutInterval * 1_000_000
stream.delegate = self
stream.connect(url: url, port: port, timeout: timeout, ssl: settings, completion: { [weak self] (error) in
guard let s = self else {return}
if error != nil {
s.disconnectStream(error)
return
}
let operation = BlockOperation()
operation.addExecutionBlock { [weak self, weak operation] in
guard let sOperation = operation, let s = self else { return }
guard !sOperation.isCancelled else { return }
// Do the pinning now if needed
#if os(Linux) || os(watchOS)
s.certValidated = false
#else
if let sec = s.security, !s.certValidated {
let trustObj = s.stream.sslTrust()
if let possibleTrust = trustObj.trust {
s.certValidated = sec.isValid(possibleTrust, domain: trustObj.domain)
} else {
s.certValidated = false
}
if !s.certValidated {
s.disconnectStream(WSError(type: .invalidSSLError, message: "Invalid SSL certificate", code: 0))
return
}
}
#endif
let _ = s.stream.write(data: data)
}
s.writeQueue.addOperation(operation)
})
self.mutex.lock()
self.readyToWrite = true
self.mutex.unlock()
}
/**
Delegate for the stream methods. Processes incoming bytes
*/
public func newBytesInStream() {
processInputStream()
}
public func streamDidError(error: Error?) {
disconnectStream(error)
}
/**
Disconnect the stream object and notifies the delegate.
*/
private func disconnectStream(_ error: Error?, runDelegate: Bool = true) {
if error == nil {
writeQueue.waitUntilAllOperationsAreFinished()
} else {
writeQueue.cancelAllOperations()
}
mutex.lock()
cleanupStream()
connected = false
mutex.unlock()
if runDelegate {
doDisconnect(error)
}
}
/**
cleanup the streams.
*/
private func cleanupStream() {
stream.cleanup()
fragBuffer = nil
}
/**
Handles the incoming bytes and sending them to the proper processing method.
*/
private func processInputStream() {
let data = stream.read()
guard let d = data else { return }
var process = false
if inputQueue.count == 0 {
process = true
}
inputQueue.append(d)
if process {
dequeueInput()
}
}
/**
Dequeue the incoming input so it is processed in order.
*/
private func dequeueInput() {
while !inputQueue.isEmpty {
autoreleasepool {
let data = inputQueue[0]
var work = data
if let buffer = fragBuffer {
var combine = NSData(data: buffer) as Data
combine.append(data)
work = combine
fragBuffer = nil
}
let buffer = UnsafeRawPointer((work as NSData).bytes).assumingMemoryBound(to: UInt8.self)
let length = work.count
if !connected {
processTCPHandshake(buffer, bufferLen: length)
} else {
processRawMessagesInBuffer(buffer, bufferLen: length)
}
inputQueue = inputQueue.filter{ $0 != data }
}
}
}
/**
Handle checking the inital connection status
*/
private func processTCPHandshake(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) {
let code = processHTTP(buffer, bufferLen: bufferLen)
switch code {
case 0:
break
case -1:
fragBuffer = Data(bytes: buffer, count: bufferLen)
break // do nothing, we are going to collect more data
default:
doDisconnect(WSError(type: .upgradeError, message: "Invalid HTTP upgrade", code: code))
}
}
/**
Finds the HTTP Packet in the TCP stream, by looking for the CRLF.
*/
private func processHTTP(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int {
let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")]
var k = 0
var totalSize = 0
for i in 0..<bufferLen {
if buffer[i] == CRLFBytes[k] {
k += 1
if k == 4 {
totalSize = i + 1
break
}
} else {
k = 0
}
}
if totalSize > 0 {
let code = validateResponse(buffer, bufferLen: totalSize)
if code != 0 {
return code
}
isConnecting = false
mutex.lock()
connected = true
mutex.unlock()
didDisconnect = false
if canDispatch {
callbackQueue.async { [weak self] in
guard let s = self else { return }
s.onConnect?()
s.delegate?.websocketDidConnect(socket: s)
s.advancedDelegate?.websocketDidConnect(socket: s)
NotificationCenter.default.post(name: NSNotification.Name(WebsocketDidConnectNotification), object: self)
}
}
//totalSize += 1 //skip the last \n
let restSize = bufferLen - totalSize
if restSize > 0 {
processRawMessagesInBuffer(buffer + totalSize, bufferLen: restSize)
}
return 0 //success
}
return -1 // Was unable to find the full TCP header.
}
/**
Validates the HTTP is a 101 as per the RFC spec.
*/
private func validateResponse(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int {
guard let str = String(data: Data(bytes: buffer, count: bufferLen), encoding: .utf8) else { return -1 }
let splitArr = str.components(separatedBy: "\r\n")
var code = -1
var i = 0
var headers = [String: String]()
for str in splitArr {
if i == 0 {
let responseSplit = str.components(separatedBy: .whitespaces)
guard responseSplit.count > 1 else { return -1 }
if let c = Int(responseSplit[1]) {
code = c
}
} else {
let responseSplit = str.components(separatedBy: ":")
guard responseSplit.count > 1 else { break }
let key = responseSplit[0].trimmingCharacters(in: .whitespaces)
let val = responseSplit[1].trimmingCharacters(in: .whitespaces)
headers[key.lowercased()] = val
}
i += 1
}
advancedDelegate?.websocketHttpUpgrade(socket: self, response: str)
if code != httpSwitchProtocolCode {
return code
}
if let extensionHeader = headers[headerWSExtensionName.lowercased()] {
processExtensionHeader(extensionHeader)
}
if let acceptKey = headers[headerWSAcceptName.lowercased()] {
if acceptKey.count > 0 {
if headerSecKey.count > 0 {
let sha = "\(headerSecKey)258EAFA5-E914-47DA-95CA-C5AB0DC85B11".sha1Base64()
if sha != acceptKey as String {
return -1
}
}
return 0
}
}
return -1
}
/**
Parses the extension header, setting up the compression parameters.
*/
func processExtensionHeader(_ extensionHeader: String) {
let parts = extensionHeader.components(separatedBy: ";")
for p in parts {
let part = p.trimmingCharacters(in: .whitespaces)
if part == "permessage-deflate" {
compressionState.supportsCompression = true
} else if part.hasPrefix("server_max_window_bits=") {
let valString = part.components(separatedBy: "=")[1]
if let val = Int(valString.trimmingCharacters(in: .whitespaces)) {
compressionState.serverMaxWindowBits = val
}
} else if part.hasPrefix("client_max_window_bits=") {
let valString = part.components(separatedBy: "=")[1]
if let val = Int(valString.trimmingCharacters(in: .whitespaces)) {
compressionState.clientMaxWindowBits = val
}
} else if part == "client_no_context_takeover" {
compressionState.clientNoContextTakeover = true
} else if part == "server_no_context_takeover" {
compressionState.serverNoContextTakeover = true
}
}
if compressionState.supportsCompression {
compressionState.decompressor = Decompressor(windowBits: compressionState.serverMaxWindowBits)
compressionState.compressor = Compressor(windowBits: compressionState.clientMaxWindowBits)
}
}
/**
Read a 16 bit big endian value from a buffer
*/
private static func readUint16(_ buffer: UnsafePointer<UInt8>, offset: Int) -> UInt16 {
return (UInt16(buffer[offset + 0]) << 8) | UInt16(buffer[offset + 1])
}
/**
Read a 64 bit big endian value from a buffer
*/
private static func readUint64(_ buffer: UnsafePointer<UInt8>, offset: Int) -> UInt64 {
var value = UInt64(0)
for i in 0...7 {
value = (value << 8) | UInt64(buffer[offset + i])
}
return value
}
/**
Write a 16-bit big endian value to a buffer.
*/
private static func writeUint16(_ buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt16) {
buffer[offset + 0] = UInt8(value >> 8)
buffer[offset + 1] = UInt8(value & 0xff)
}
/**
Write a 64-bit big endian value to a buffer.
*/
private static func writeUint64(_ buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt64) {
for i in 0...7 {
buffer[offset + i] = UInt8((value >> (8*UInt64(7 - i))) & 0xff)
}
}
/**
Process one message at the start of `buffer`. Return another buffer (sharing storage) that contains the leftover contents of `buffer` that I didn't process.
*/
private func processOneRawMessage(inBuffer buffer: UnsafeBufferPointer<UInt8>) -> UnsafeBufferPointer<UInt8> {
let response = readStack.last
guard let baseAddress = buffer.baseAddress else {return emptyBuffer}
let bufferLen = buffer.count
if response != nil && bufferLen < 2 {
fragBuffer = Data(buffer: buffer)
return emptyBuffer
}
if let response = response, response.bytesLeft > 0 {
var len = response.bytesLeft
var extra = bufferLen - response.bytesLeft
if response.bytesLeft > bufferLen {
len = bufferLen
extra = 0
}
response.bytesLeft -= len
response.buffer?.append(Data(bytes: baseAddress, count: len))
_ = processResponse(response)
return buffer.fromOffset(bufferLen - extra)
} else {
let isFin = (FinMask & baseAddress[0])
let receivedOpcodeRawValue = (OpCodeMask & baseAddress[0])
let receivedOpcode = OpCode(rawValue: receivedOpcodeRawValue)
let isMasked = (MaskMask & baseAddress[1])
let payloadLen = (PayloadLenMask & baseAddress[1])
var offset = 2
if compressionState.supportsCompression && receivedOpcode != .continueFrame {
compressionState.messageNeedsDecompression = (RSV1Mask & baseAddress[0]) > 0
}
if (isMasked > 0 || (RSVMask & baseAddress[0]) > 0) && receivedOpcode != .pong && !compressionState.messageNeedsDecompression {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(WSError(type: .protocolError, message: "masked and rsv data is not currently supported", code: Int(errCode)))
writeError(errCode)
return emptyBuffer
}
let isControlFrame = (receivedOpcode == .connectionClose || receivedOpcode == .ping)
if !isControlFrame && (receivedOpcode != .binaryFrame && receivedOpcode != .continueFrame &&
receivedOpcode != .textFrame && receivedOpcode != .pong) {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(WSError(type: .protocolError, message: "unknown opcode: \(receivedOpcodeRawValue)", code: Int(errCode)))
writeError(errCode)
return emptyBuffer
}
if isControlFrame && isFin == 0 {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(WSError(type: .protocolError, message: "control frames can't be fragmented", code: Int(errCode)))
writeError(errCode)
return emptyBuffer
}
var closeCode = CloseCode.normal.rawValue
if receivedOpcode == .connectionClose {
if payloadLen == 1 {
closeCode = CloseCode.protocolError.rawValue
} else if payloadLen > 1 {
closeCode = WebSocket.readUint16(baseAddress, offset: offset)
if closeCode < 1000 || (closeCode > 1003 && closeCode < 1007) || (closeCode > 1013 && closeCode < 3000) {
closeCode = CloseCode.protocolError.rawValue
}
}
if payloadLen < 2 {
doDisconnect(WSError(type: .protocolError, message: "connection closed by server", code: Int(closeCode)))
writeError(closeCode)
return emptyBuffer
}
} else if isControlFrame && payloadLen > 125 {
writeError(CloseCode.protocolError.rawValue)
return emptyBuffer
}
var dataLength = UInt64(payloadLen)
if dataLength == 127 {
dataLength = WebSocket.readUint64(baseAddress, offset: offset)
offset += MemoryLayout<UInt64>.size
} else if dataLength == 126 {
dataLength = UInt64(WebSocket.readUint16(baseAddress, offset: offset))
offset += MemoryLayout<UInt16>.size
}
if bufferLen < offset || UInt64(bufferLen - offset) < dataLength {
fragBuffer = Data(bytes: baseAddress, count: bufferLen)
return emptyBuffer
}
var len = dataLength
if dataLength > UInt64(bufferLen) {
len = UInt64(bufferLen-offset)
}
if receivedOpcode == .connectionClose && len > 0 {
let size = MemoryLayout<UInt16>.size
offset += size
len -= UInt64(size)
}
let data: Data
if compressionState.messageNeedsDecompression, let decompressor = compressionState.decompressor {
do {
data = try decompressor.decompress(bytes: baseAddress+offset, count: Int(len), finish: isFin > 0)
if isFin > 0 && compressionState.serverNoContextTakeover {
try decompressor.reset()
}
} catch {
let closeReason = "Decompression failed: \(error)"
let closeCode = CloseCode.encoding.rawValue
doDisconnect(WSError(type: .protocolError, message: closeReason, code: Int(closeCode)))
writeError(closeCode)
return emptyBuffer
}
} else {
data = Data(bytes: baseAddress+offset, count: Int(len))
}
if receivedOpcode == .connectionClose {
var closeReason = "connection closed by server"
if let customCloseReason = String(data: data, encoding: .utf8) {
closeReason = customCloseReason
} else {
closeCode = CloseCode.protocolError.rawValue
}
doDisconnect(WSError(type: .protocolError, message: closeReason, code: Int(closeCode)))
writeError(closeCode)
return emptyBuffer
}
if receivedOpcode == .pong {
if canDispatch {
callbackQueue.async { [weak self] in
guard let s = self else { return }
let pongData: Data? = data.count > 0 ? data : nil
s.onPong?(pongData)
s.pongDelegate?.websocketDidReceivePong(socket: s, data: pongData)
}
}
return buffer.fromOffset(offset + Int(len))
}
var response = readStack.last
if isControlFrame {
response = nil // Don't append pings.
}
if isFin == 0 && receivedOpcode == .continueFrame && response == nil {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(WSError(type: .protocolError, message: "continue frame before a binary or text frame", code: Int(errCode)))
writeError(errCode)
return emptyBuffer
}
var isNew = false
if response == nil {
if receivedOpcode == .continueFrame {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(WSError(type: .protocolError, message: "first frame can't be a continue frame", code: Int(errCode)))
writeError(errCode)
return emptyBuffer
}
isNew = true
response = WSResponse()
response!.code = receivedOpcode!
response!.bytesLeft = Int(dataLength)
response!.buffer = NSMutableData(data: data)
} else {
if receivedOpcode == .continueFrame {
response!.bytesLeft = Int(dataLength)
} else {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(WSError(type: .protocolError, message: "second and beyond of fragment message must be a continue frame", code: Int(errCode)))
writeError(errCode)
return emptyBuffer
}
response!.buffer!.append(data)
}
if let response = response {
response.bytesLeft -= Int(len)
response.frameCount += 1
response.isFin = isFin > 0 ? true : false
if isNew {
readStack.append(response)
}
_ = processResponse(response)
}
let step = Int(offset + numericCast(len))
return buffer.fromOffset(step)
}
}
/**
Process all messages in the buffer if possible.
*/
private func processRawMessagesInBuffer(_ pointer: UnsafePointer<UInt8>, bufferLen: Int) {
var buffer = UnsafeBufferPointer(start: pointer, count: bufferLen)
repeat {
buffer = processOneRawMessage(inBuffer: buffer)
} while buffer.count >= 2
if buffer.count > 0 {
fragBuffer = Data(buffer: buffer)
}
}
/**
Process the finished response of a buffer.
*/
private func processResponse(_ response: WSResponse) -> Bool {
if response.isFin && response.bytesLeft <= 0 {
if response.code == .ping {
if respondToPingWithPong {
let data = response.buffer! // local copy so it is perverse for writing
dequeueWrite(data as Data, code: .pong)
}
} else if response.code == .textFrame {
guard let str = String(data: response.buffer! as Data, encoding: .utf8) else {
writeError(CloseCode.encoding.rawValue)
return false
}
if canDispatch {
callbackQueue.async { [weak self] in
guard let s = self else { return }
s.onText?(str)
s.delegate?.websocketDidReceiveMessage(socket: s, text: str)
s.advancedDelegate?.websocketDidReceiveMessage(socket: s, text: str, response: response)
}
}
} else if response.code == .binaryFrame {
if canDispatch {
let data = response.buffer! // local copy so it is perverse for writing
callbackQueue.async { [weak self] in
guard let s = self else { return }
s.onData?(data as Data)
s.delegate?.websocketDidReceiveData(socket: s, data: data as Data)
s.advancedDelegate?.websocketDidReceiveData(socket: s, data: data as Data, response: response)
}
}
}
readStack.removeLast()
return true
}
return false
}
/**
Write an error to the socket
*/
private func writeError(_ code: UInt16) {
let buf = NSMutableData(capacity: MemoryLayout<UInt16>.size)
let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self)
WebSocket.writeUint16(buffer, offset: 0, value: code)
dequeueWrite(Data(bytes: buffer, count: MemoryLayout<UInt16>.size), code: .connectionClose)
}
/**
Used to write things to the stream
*/
private func dequeueWrite(_ data: Data, code: OpCode, writeCompletion: (() -> ())? = nil) {
let operation = BlockOperation()
operation.addExecutionBlock { [weak self, weak operation] in
//stream isn't ready, let's wait
guard let s = self else { return }
guard let sOperation = operation else { return }
var offset = 2
var firstByte:UInt8 = s.FinMask | code.rawValue
var data = data
if [.textFrame, .binaryFrame].contains(code), let compressor = s.compressionState.compressor {
do {
data = try compressor.compress(data)
if s.compressionState.clientNoContextTakeover {
try compressor.reset()
}
firstByte |= s.RSV1Mask
} catch {
// TODO: report error? We can just send the uncompressed frame.
}
}
let dataLength = data.count
let frame = NSMutableData(capacity: dataLength + s.MaxFrameSize)
let buffer = UnsafeMutableRawPointer(frame!.mutableBytes).assumingMemoryBound(to: UInt8.self)
buffer[0] = firstByte
if dataLength < 126 {
buffer[1] = CUnsignedChar(dataLength)
} else if dataLength <= Int(UInt16.max) {
buffer[1] = 126
WebSocket.writeUint16(buffer, offset: offset, value: UInt16(dataLength))
offset += MemoryLayout<UInt16>.size
} else {
buffer[1] = 127
WebSocket.writeUint64(buffer, offset: offset, value: UInt64(dataLength))
offset += MemoryLayout<UInt64>.size
}
buffer[1] |= s.MaskMask
let maskKey = UnsafeMutablePointer<UInt8>(buffer + offset)
_ = SecRandomCopyBytes(kSecRandomDefault, Int(MemoryLayout<UInt32>.size), maskKey)
offset += MemoryLayout<UInt32>.size
for i in 0..<dataLength {
buffer[offset] = data[i] ^ maskKey[i % MemoryLayout<UInt32>.size]
offset += 1
}
var total = 0
while !sOperation.isCancelled {
if !s.readyToWrite {
s.doDisconnect(WSError(type: .outputStreamWriteError, message: "output stream had an error during write", code: 0))
break
}
let stream = s.stream
let writeBuffer = UnsafeRawPointer(frame!.bytes+total).assumingMemoryBound(to: UInt8.self)
let len = stream.write(data: Data(bytes: writeBuffer, count: offset-total))
if len <= 0 {
s.doDisconnect(WSError(type: .outputStreamWriteError, message: "output stream had an error during write", code: 0))
break
} else {
total += len
}
if total >= offset {
if let queue = self?.callbackQueue, let callback = writeCompletion {
queue.async {
callback()
}
}
break
}
}
}
writeQueue.addOperation(operation)
}
/**
Used to preform the disconnect delegate
*/
private func doDisconnect(_ error: Error?) {
guard !didDisconnect else { return }
didDisconnect = true
isConnecting = false
mutex.lock()
connected = false
mutex.unlock()
guard canDispatch else {return}
callbackQueue.async { [weak self] in
guard let s = self else { return }
s.onDisconnect?(error)
s.delegate?.websocketDidDisconnect(socket: s, error: error)
s.advancedDelegate?.websocketDidDisconnect(socket: s, error: error)
let userInfo = error.map{ [WebsocketDisconnectionErrorKeyName: $0] }
NotificationCenter.default.post(name: NSNotification.Name(WebsocketDidDisconnectNotification), object: self, userInfo: userInfo)
}
}
// MARK: - Deinit
deinit {
mutex.lock()
readyToWrite = false
cleanupStream()
mutex.unlock()
writeQueue.cancelAllOperations()
}
}
private extension String {
func sha1Base64() -> String {
let data = self.data(using: String.Encoding.utf8)!
var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH))
data.withUnsafeBytes { _ = CC_SHA1($0, CC_LONG(data.count), &digest) }
return Data(bytes: digest).base64EncodedString()
}
}
private extension Data {
init(buffer: UnsafeBufferPointer<UInt8>) {
self.init(bytes: buffer.baseAddress!, count: buffer.count)
}
}
private extension UnsafeBufferPointer {
func fromOffset(_ offset: Int) -> UnsafeBufferPointer<Element> {
return UnsafeBufferPointer<Element>(start: baseAddress?.advanced(by: offset), count: count - offset)
}
}
private let emptyBuffer = UnsafeBufferPointer<UInt8>(start: nil, count: 0)
#if swift(>=4)
#else
fileprivate extension String {
var count: Int {
return self.characters.count
}
}
#endif
| apache-2.0 |
Nimbow/Client-iOS | client/client/BinarySms.swift | 1 | 931 | //
// BinarySms.swift
// client
//
// Created by Awesome Developer on 23/01/16.
// Copyright © 2016 Nimbow. All rights reserved.
//
public final class BinarySms : Sms {
public var Data: NSData?
public var Udh: String?
public convenience init(from: String?, to: String?, data: NSData?, udh: String?) {
self.init(from: from, to: to)
Data = data
Udh = udh
}
override func ToSendSmsRequest() -> SendSmsRequest {
let request = super.ToSendSmsRequest()
request.Type = SmsType.Binary
request.Udh = Udh
if (Data == nil) { return request; }
var string = ""
var byte: UInt8 = 0
for i in 0 ..< Data!.length {
Data!.getBytes(&byte, range: NSMakeRange(i, 1))
string += String(format: "%04x", byte)
}
request.Text = string
return request
}
} | mit |
frtlupsvn/Vietnam-To-Go | VietNamToGoTests/VietNamToGoTests.swift | 1 | 991 | //
// VietNamToGoTests.swift
// VietNamToGoTests
//
// Created by Zoom Nguyen on 12/20/15.
// Copyright © 2015 Zoom Nguyen. All rights reserved.
//
import XCTest
@testable import VietNamToGo
class VietNamToGoTests: 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.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
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 |
alexames/flatbuffers | swift/Sources/FlatBuffers/NativeObject.swift | 4 | 2138 | /*
* Copyright 2021 Google Inc. 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.
*/
#if !os(WASI)
import Foundation
#else
import SwiftOverlayShims
#endif
/// NativeObject is a protocol that all of the `Object-API` generated code should be
/// conforming to since it allows developers the ease of use to pack and unpack their
/// Flatbuffers objects
public protocol NativeObject {}
extension NativeObject {
/// Serialize is a helper function that serailizes the data from the Object API to a bytebuffer directly th
/// - Parameter type: Type of the Flatbuffer object
/// - Returns: returns the encoded sized ByteBuffer
public func serialize<T: ObjectAPIPacker>(type: T.Type) -> ByteBuffer
where T.T == Self
{
var builder = FlatBufferBuilder(initialSize: 1024)
return serialize(builder: &builder, type: type.self)
}
/// Serialize is a helper function that serailizes the data from the Object API to a bytebuffer directly.
///
/// - Parameters:
/// - builder: A FlatBufferBuilder
/// - type: Type of the Flatbuffer object
/// - Returns: returns the encoded sized ByteBuffer
/// - Note: The `serialize(builder:type)` can be considered as a function that allows you to create smaller builder instead of the default `1024`.
/// It can be considered less expensive in terms of memory allocation
public func serialize<T: ObjectAPIPacker>(
builder: inout FlatBufferBuilder,
type: T.Type) -> ByteBuffer where T.T == Self
{
var s = self
let root = type.pack(&builder, obj: &s)
builder.finish(offset: root)
return builder.sizedBuffer
}
}
| apache-2.0 |
zapdroid/RXWeather | Pods/RxSwift/RxSwift/Observables/Implementations/Debounce.swift | 1 | 2748 | //
// Debounce.swift
// RxSwift
//
// Created by Krunoslav Zaher on 9/11/16.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
final class DebounceSink<O: ObserverType>
: Sink<O>
, ObserverType
, LockOwnerType
, SynchronizedOnType {
typealias Element = O.E
typealias ParentType = Debounce<Element>
private let _parent: ParentType
let _lock = RecursiveLock()
// state
private var _id = 0 as UInt64
private var _value: Element?
let cancellable = SerialDisposable()
init(parent: ParentType, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
let subscription = _parent._source.subscribe(self)
return Disposables.create(subscription, cancellable)
}
func on(_ event: Event<Element>) {
synchronizedOn(event)
}
func _synchronized_on(_ event: Event<Element>) {
switch event {
case let .next(element):
_id = _id &+ 1
let currentId = _id
_value = element
let scheduler = _parent._scheduler
let dueTime = _parent._dueTime
let d = SingleAssignmentDisposable()
cancellable.disposable = d
d.setDisposable(scheduler.scheduleRelative(currentId, dueTime: dueTime, action: propagate))
case .error:
_value = nil
forwardOn(event)
dispose()
case .completed:
if let value = _value {
_value = nil
forwardOn(.next(value))
}
forwardOn(.completed)
dispose()
}
}
func propagate(_ currentId: UInt64) -> Disposable {
_lock.lock(); defer { _lock.unlock() } // {
let originalValue = _value
if let value = originalValue, _id == currentId {
_value = nil
forwardOn(.next(value))
}
// }
return Disposables.create()
}
}
final class Debounce<Element>: Producer<Element> {
fileprivate let _source: Observable<Element>
fileprivate let _dueTime: RxTimeInterval
fileprivate let _scheduler: SchedulerType
init(source: Observable<Element>, dueTime: RxTimeInterval, scheduler: SchedulerType) {
_source = source
_dueTime = dueTime
_scheduler = scheduler
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
let sink = DebounceSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
| mit |
VincentPuget/vigenere | vigenere/class/MatrixViewController.swift | 1 | 4772 | //
// MainViewController.swift
// Vigenere
//
// Created by Vincent PUGET on 05/08/2015.
// Copyright (c) 2015 Vincent PUGET. All rights reserved.
//
import Cocoa
protocol MatrixProtocol
{
func matrixIsAvailable(_ isAvailable:Bool!) -> Void
}
class MatrixViewController: NSViewController {
@IBOutlet weak var buttonValidate: NSButton!
@IBOutlet weak var buttonCancel: NSButton!
@IBOutlet weak var tfMatrixName: NSTextField!
@IBOutlet var tvMatrix: NSTextView!
@IBOutlet weak var viewBackground: NSView!
var delegate:MatrixProtocol!
var isNewMatrix:Bool! = true;
var matrixObj:Matrix!;
override func viewWillAppear() {
self.view.wantsLayer = true
self.view.layer?.backgroundColor = NSColor(calibratedRed: 69/255, green: 69/255, blue: 69/255, alpha: 1).cgColor
self.viewBackground.layer?.backgroundColor = NSColor(calibratedRed: 35/255, green: 35/255, blue: 35/255, alpha: 1).cgColor
self.tvMatrix.textColor = NSColor.white
self.tvMatrix.insertionPointColor = NSColor.white
let color = NSColor.gray
let attrs = [NSForegroundColorAttributeName: color]
let placeHolderStr = NSAttributedString(string: NSLocalizedString("matrixName", tableName: "LocalizableStrings", comment: "Matrix name"), attributes: attrs)
self.tfMatrixName.placeholderAttributedString = placeHolderStr
self.tfMatrixName.focusRingType = NSFocusRingType.none
let fieldEditor: NSTextView! = self.tfMatrixName.window?.fieldEditor(true, for: self.tfMatrixName) as! NSTextView
fieldEditor.insertionPointColor = NSColor.white
let pstyle = NSMutableParagraphStyle()
pstyle.alignment = NSTextAlignment.center
self.buttonValidate.attributedTitle = NSAttributedString(string: NSLocalizedString("save", tableName: "LocalizableStrings", comment: "Save"), attributes: [ NSForegroundColorAttributeName : NSColor.white, NSParagraphStyleAttributeName : pstyle ])
self.buttonCancel.attributedTitle = NSAttributedString(string: NSLocalizedString("cancel", tableName: "LocalizableStrings", comment: "Cancel"), attributes: [ NSForegroundColorAttributeName : NSColor.white, NSParagraphStyleAttributeName : pstyle ])
let widthConstraint = NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 460)
self.view.addConstraint(widthConstraint)
let heightConstraint = NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 260)
self.view.addConstraint(heightConstraint)
}
override func viewDidAppear() {
super.viewDidAppear()
self.view.window?.title = "Vigenere"
self.view.window?.isMovableByWindowBackground = true
self.tfMatrixName.currentEditor()?.moveToEndOfLine(self)
}
override func viewDidLoad() {
super.viewDidLoad()
self.tvMatrix.delegate = self
self.tfMatrixName.delegate = self
matrixObj = DataSingleton.instance.getMatrixObject();
if(matrixObj != nil)
{
self.isNewMatrix = false;
self.tfMatrixName.stringValue = matrixObj.name
self.tvMatrix.string = matrixObj.matrix
}
else
{
self.isNewMatrix = true;
self.tfMatrixName.stringValue = ""
self.tvMatrix.string = ""
}
}
@IBAction func IBA_buttonCancel(_ sender: AnyObject) {
self.dismissViewController(self)
}
@IBAction func IBA_buttonValidate(_ sender: AnyObject) {
var saveIsOk = false;
if(self.isNewMatrix == true)
{
saveIsOk = DataSingleton.instance.saveNewMatrix(self.tfMatrixName.stringValue, matrix: self.tvMatrix.textStorage?.string)
}
else{
saveIsOk = DataSingleton.instance.saveThisMatrix(self.matrixObj, name: self.tfMatrixName.stringValue, matrix: self.tvMatrix.textStorage?.string)
}
self.delegate.matrixIsAvailable(saveIsOk)
self.dismissViewController(self)
}
}
extension MatrixViewController: NSTextFieldDelegate {
override func controlTextDidChange(_ obj: Notification) {
}
override func controlTextDidEndEditing(_ obj: Notification) {
}
}
extension MatrixViewController: NSTextViewDelegate {
func textDidChange(_ obj: Notification)
{
}
}
| mit |
practicalswift/swift | validation-test/Evolution/test_protocol_add_requirements.swift | 5 | 3793 | // RUN: %target-resilience-test
// REQUIRES: executable_test
import StdlibUnittest
import protocol_add_requirements
var ProtocolAddRequirementsTest = TestSuite("ProtocolAddRequirements")
struct Halogen : ElementProtocol {
var x: Int
func increment() -> Halogen {
return Halogen(x: x + 1)
}
}
func ==(h1: Halogen, h2: Halogen) -> Bool {
return h1.x == h2.x
}
struct AddMethods : AddMethodsProtocol {
func importantOperation() -> Halogen {
return Halogen(x: 0)
}
#if AFTER
func unimportantOperation() -> Halogen {
return Halogen(x: 10)
}
#endif
}
ProtocolAddRequirementsTest.test("AddMethodRequirements") {
let result = doSomething(AddMethods())
#if BEFORE
let expected = [0, 1, 2].map(Halogen.init)
#else
let expected = [0, 10, 11].map(Halogen.init)
#endif
}
struct AddConstructors : AddConstructorsProtocol, Equatable {
var name: String
init(name: String) {
self.name = name
}
}
func ==(a1: AddConstructors, a2: AddConstructors) -> Bool {
return a1.name == a2.name
}
ProtocolAddRequirementsTest.test("AddConstructorsProtocol") {
// Would be nice if [T?] was Equatable...
if getVersion() == 0 {
let result = testConstructorProtocol(AddConstructors.self)
expectEqual(result.count, 1)
expectEqual(result[0], AddConstructors(name: "Puff"))
} else {
let result = testConstructorProtocol(AddConstructors.self)
expectEqual(result.count, 3)
expectEqual(result[0], AddConstructors(name: "Meow meow"))
expectEqual(result[1], nil)
expectEqual(result[2], AddConstructors(name: "Robster the Lobster"))
}
}
class Box<T> {
var value: T
init(value: T) {
self.value = value
}
}
struct AddProperties : AddPropertiesProtocol {
var speedBox: Box<Int> = Box<Int>(value: 160)
var gearBox: Box<Int> = Box<Int>(value: 8000)
var topSpeed: Int {
get {
return speedBox.value
}
nonmutating set {
speedBox.value = newValue
}
}
var maxRPM: Int {
get {
return gearBox.value
}
set {
gearBox.value = newValue
}
}
}
ProtocolAddRequirementsTest.test("AddPropertyRequirements") {
var x = AddProperties()
do {
let expected = (getVersion() == 0
? [160, 8000]
: [160, 8000, 80, 40, 6000])
expectEqual(getProperties(&x), expected)
}
setProperties(&x)
do {
let expected = (getVersion() == 0
? [320, 15000]
: [320, 15000, 160, 80, 13000])
expectEqual(getProperties(&x), expected)
}
}
struct AddSubscript<Key : Hashable, Value> : AddSubscriptProtocol {
var dict: [Key : Value] = [:]
func get(key key: Key) -> Value {
return dict[key]!
}
mutating func set(key key: Key, value: Value) {
dict[key] = value
}
}
ProtocolAddRequirementsTest.test("AddSubscriptRequirements") {
var t = AddSubscript<String, Int>()
t.set(key: "B", value: 20)
doSomething(&t, k1: "A", k2: "B")
expectEqual(t.get(key: "A"), 20)
}
struct AddAssociatedType<T> : AddAssocTypesProtocol { }
ProtocolAddRequirementsTest.test("AddAssociatedTypeRequirements") {
let addString = AddAssociatedType<String>()
let stringResult = doSomethingWithAssocTypes(addString)
if getVersion() == 0 {
expectEqual("there are no associated types yet", stringResult)
} else {
expectEqual("Wrapper<AddAssociatedType<String>>", stringResult)
}
}
ProtocolAddRequirementsTest.test("AddAssociatedConformanceRequirements") {
let addString = AddAssociatedType<String>()
let stringResult = doSomethingWithAssocConformances(addString)
if getVersion() == 0 {
expectEqual("there are no associated conformances yet", stringResult)
} else {
expectEqual("I am a wrapper for AddAssociatedType<String>", stringResult)
}
}
runAllTests()
| apache-2.0 |
m0rb1u5/iOS_10_1 | iOS_15_1 Extension/TipoMasaWKController.swift | 1 | 1138 | //
// TipoMasaWKController.swift
// iOS_10_1
//
// Created by Juan Carlos Carbajal Ipenza on 18/04/16.
// Copyright © 2016 Juan Carlos Carbajal Ipenza. All rights reserved.
//
import WatchKit
import Foundation
class TipoMasaWKController: WKInterfaceController {
let delgada: String = "Delgada"
let crujiente: String = "Crujiente"
let gruesa: String = "Gruesa"
var valorContexto: Valor = Valor()
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
self.setTitle("Tipo de Masa")
valorContexto = context as! Valor
}
override func willActivate() {
super.willActivate()
}
override func didDeactivate() {
super.didDeactivate()
}
@IBAction func guardarDelgada() {
setContexto(delgada)
}
@IBAction func guardarCrujiente() {
setContexto(crujiente)
}
@IBAction func guardarGruesa() {
setContexto(gruesa)
}
func setContexto(opcion: String) {
valorContexto.masa = opcion
pushControllerWithName("idQueso", context: valorContexto)
print(opcion)
}
}
| gpl-3.0 |
fitpay/fitpay-ios-sdk | FitpaySDK/PaymentDevice/SyncQueue/PaymentDeviceStorage.swift | 1 | 133 | import Foundation
struct PaymentDeviceStorage {
var paymentDevice: PaymentDevice?
var user: User?
var device: Device?
}
| mit |
ljcoder2015/LJTool | LJToolDemo/LJToolDemo/Extension/LJTool+UIColorExtension.swift | 1 | 430 | //
// LJTool+UIColorExtension.swift
// IntelligentDoor
//
// Created by ljcoder on 2017/9/5.
// Copyright © 2017年 shanglv. All rights reserved.
//
import LJTool
import UIKit
extension LJTool where Base: UIColor {
// static var exYellow: UIColor {
// return UIColor.lj.color(0xf3c02f)
// }
//
// static var background: UIColor {
// return UIColor.lj.color(r: 240, g: 240, b: 248)
// }
}
| mit |
huonw/swift | test/stdlib/Reflection.swift | 5 | 5176 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -parse-stdlib %s -module-name Reflection -o %t/a.out
// RUN: %S/timeout.sh 360 %target-run %t/a.out | %FileCheck %s
// REQUIRES: executable_test
// FIXME: timeout wrapper is necessary because the ASan test runs for hours
//
// DO NOT add more tests to this file. Add them to test/1_stdlib/Runtime.swift.
//
import Swift
// A more interesting struct type.
struct Complex<T> {
let real, imag: T
}
// CHECK-LABEL: Complex:
print("Complex:")
// CHECK-NEXT: Reflection.Complex<Swift.Double>
// CHECK-NEXT: real: 1.5
// CHECK-NEXT: imag: 0.75
dump(Complex<Double>(real: 1.5, imag: 0.75))
// CHECK-NEXT: Reflection.Complex<Swift.Double>
// CHECK-NEXT: real: -1.5
// CHECK-NEXT: imag: -0.75
dump(Complex<Double>(real: -1.5, imag: -0.75))
// CHECK-NEXT: Reflection.Complex<Swift.Int>
// CHECK-NEXT: real: 22
// CHECK-NEXT: imag: 44
dump(Complex<Int>(real: 22, imag: 44))
// CHECK-NEXT: Reflection.Complex<Swift.String>
// CHECK-NEXT: real: "is this the real life?"
// CHECK-NEXT: imag: "is it just fantasy?"
dump(Complex<String>(real: "is this the real life?",
imag: "is it just fantasy?"))
// Test destructuring of a pure Swift class hierarchy.
class Good {
let x: UInt = 11
let y: String = "222"
}
class Better : Good {
let z: Double = 333.5
}
class Best : Better {
let w: String = "4444"
}
// CHECK-LABEL: Root class:
// CHECK-NEXT: Reflection.Good #0
// CHECK-NEXT: x: 11
// CHECK-NEXT: y: "222"
print("Root class:")
dump(Good())
// CHECK-LABEL: Subclass:
// CHECK-NEXT: Reflection.Best #0
// CHECK-NEXT: super: Reflection.Better
// CHECK-NEXT: super: Reflection.Good
// CHECK-NEXT: x: 11
// CHECK-NEXT: y: "222"
// CHECK-NEXT: z: 333.5
// CHECK-NEXT: w: "4444"
print("Subclass:")
dump(Best())
// Test protocol types, which reflect as their dynamic types.
// CHECK-LABEL: Any int:
// CHECK-NEXT: 1
print("Any int:")
var any: Any = 1
dump(any)
// CHECK-LABEL: Any class:
// CHECK-NEXT: Reflection.Best #0
// CHECK-NEXT: super: Reflection.Better
// CHECK-NEXT: super: Reflection.Good
// CHECK-NEXT: x: 11
// CHECK-NEXT: y: "222"
// CHECK-NEXT: z: 333.5
// CHECK-NEXT: w: "4444"
print("Any class:")
any = Best()
dump(any)
// CHECK-LABEL: second verse
// CHECK-NEXT: Reflection.Best #0
print("second verse same as the first:")
dump(any)
// CHECK-LABEL: Any double:
// CHECK-NEXT: 2.5
print("Any double:")
any = 2.5
dump(any)
// CHECK-LABEL: Character:
// CHECK-NEXT: "a"
print("Character:")
dump(Character("a"))
protocol Fooable {}
extension Int : Fooable {}
extension Double : Fooable {}
// CHECK-LABEL: Fooable int:
// CHECK-NEXT: 1
print("Fooable int:")
var fooable: Fooable = 1
dump(fooable)
// CHECK-LABEL: Fooable double:
// CHECK-NEXT: 2.5
print("Fooable double:")
fooable = 2.5
dump(fooable)
protocol Barrable : class {}
extension Best: Barrable {}
// CHECK-LABEL: Barrable class:
// CHECK-NEXT: Reflection.Best #0
// CHECK-NEXT: super: Reflection.Better
// CHECK-NEXT: super: Reflection.Good
// CHECK-NEXT: x: 11
// CHECK-NEXT: y: "222"
// CHECK-NEXT: z: 333.5
// CHECK-NEXT: w: "4444"
print("Barrable class:")
var barrable: Barrable = Best()
dump(barrable)
// CHECK-LABEL: second verse
// CHECK-NEXT: Reflection.Best #0
// CHECK-NEXT: super: Reflection.Better
// CHECK-NEXT: super: Reflection.Good
// CHECK-NEXT: x: 11
// CHECK-NEXT: y: "222"
// CHECK-NEXT: z: 333.5
// CHECK-NEXT: w: "4444"
print("second verse same as the first:")
dump(barrable)
// CHECK-NEXT: Logical: true
switch true.customPlaygroundQuickLook {
case .bool(let x): print("Logical: \(x)")
default: print("wrong quicklook type")
}
let intArray = [1,2,3,4,5]
// CHECK-NEXT: 5 elements
// CHECK-NEXT: 1
// CHECK-NEXT: 2
// CHECK-NEXT: 3
// CHECK-NEXT: 4
// CHECK-NEXT: 5
dump(intArray)
var justSomeFunction = { (x:Int) -> Int in return x + 1 }
// CHECK-NEXT: (Function)
dump(justSomeFunction as Any)
// CHECK-NEXT: Swift.String
dump(String.self)
// CHECK-NEXT: ▿
// CHECK-NEXT: from: 1.0
// CHECK-NEXT: through: 12.15
// CHECK-NEXT: by: 3.14
dump(stride(from: 1.0, through: 12.15, by: 3.14))
// CHECK-NEXT: nil
var nilUnsafeMutablePointerString: UnsafeMutablePointer<String>?
dump(nilUnsafeMutablePointerString)
// CHECK-NEXT: 123456
// CHECK-NEXT: - pointerValue: 1193046
var randomUnsafeMutablePointerString = UnsafeMutablePointer<String>(
bitPattern: 0x123456)!
dump(randomUnsafeMutablePointerString)
// CHECK-NEXT: Hello panda
var sanePointerString = UnsafeMutablePointer<String>.allocate(capacity: 1)
sanePointerString.initialize(to: "Hello panda")
dump(sanePointerString.pointee)
sanePointerString.deinitialize(count: 1)
sanePointerString.deallocate()
// Don't crash on types with opaque metadata. rdar://problem/19791252
// CHECK-NEXT: (Opaque Value)
var rawPointer = unsafeBitCast(0 as Int, to: Builtin.RawPointer.self)
dump(rawPointer)
// CHECK-LABEL: and now our song is done
print("and now our song is done")
| apache-2.0 |
huonw/swift | test/SILOptimizer/inout_deshadow_integration.swift | 5 | 3080 | // RUN: %target-swift-frontend %s -emit-sil | %FileCheck %s
// This is an integration check for the inout-deshadow pass, verifying that it
// deshadows the inout variables in certain cases. These test should not be
// very specific (as they are running the parser, silgen and other sil
// diagnostic passes), they should just check the inout shadow got removed.
// CHECK-LABEL: sil hidden @{{.*}}exploded_trivial_type_dead
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
func exploded_trivial_type_dead(a: inout Int) {
}
// CHECK-LABEL: sil hidden @{{.*}}exploded_trivial_type_returned
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
func exploded_trivial_type_returned(a: inout Int) -> Int {
return a
}
// CHECK-LABEL: sil hidden @{{.*}}exploded_trivial_type_stored
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
func exploded_trivial_type_stored(a: inout Int) {
a = 12
}
// CHECK-LABEL: sil hidden @{{.*}}exploded_trivial_type_stored_returned
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
func exploded_trivial_type_stored_returned(a: inout Int) -> Int {
a = 12
return a
}
// CHECK-LABEL: sil hidden @{{.*}}exploded_nontrivial_type_dead
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
func exploded_nontrivial_type_dead(a: inout String) {
}
// CHECK-LABEL: sil hidden @{{.*}}exploded_nontrivial_type_returned
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
func exploded_nontrivial_type_returned(a: inout String) -> String {
return a
}
// CHECK-LABEL: sil hidden @{{.*}}exploded_nontrivial_type_stored
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
func exploded_nontrivial_type_stored(a: inout String) {
a = "x"
}
// CHECK-LABEL: sil hidden @{{.*}}exploded_nontrivial_type_stored_returned
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
func exploded_nontrivial_type_stored_returned(a: inout String) -> String {
a = "x"
return a
}
// Use an external function so inout deshadowing cannot see its body.
@_silgen_name("takesNoEscapeClosure")
func takesNoEscapeClosure(fn : () -> Int)
struct StructWithMutatingMethod {
var x = 42
// We should be able to deshadow this. The closure is capturing self, but it
// is itself noescape.
mutating func mutatingMethod() {
takesNoEscapeClosure { x = 42; return x }
}
mutating func testStandardLibraryOperators() {
if x != 4 || x != 0 {
testStandardLibraryOperators()
}
}
}
// CHECK-LABEL: sil hidden @$S26inout_deshadow_integration24StructWithMutatingMethodV08mutatingG0{{[_0-9a-zA-Z]*}}F : $@convention(method) (@inout StructWithMutatingMethod) -> () {
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
// CHECK-LABEL: sil hidden @$S26inout_deshadow_integration24StructWithMutatingMethodV28testStandardLibraryOperators{{[_0-9a-zA-Z]*}}F : $@convention(method) (@inout StructWithMutatingMethod) -> () {
// CHECK-NOT: alloc_box $<τ_0_0> { var τ_0_0 } <StructWithMutatingMethod>
// CHECK-NOT: alloc_stack $StructWithMutatingMethod
// CHECK: }
| apache-2.0 |
faimin/ZDOpenSourceDemo | ZDOpenSourceSwiftDemo/Pods/Toast-Swift/Toast/Toast.swift | 4 | 30625 | //
// Toast.swift
// Toast-Swift
//
// Copyright (c) 2015-2019 Charles Scalesse.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
import ObjectiveC
/**
Toast is a Swift extension that adds toast notifications to the `UIView` object class.
It is intended to be simple, lightweight, and easy to use. Most toast notifications
can be triggered with a single line of code.
The `makeToast` methods create a new view and then display it as toast.
The `showToast` methods display any view as toast.
*/
public extension UIView {
/**
Keys used for associated objects.
*/
private struct ToastKeys {
static var timer = "com.toast-swift.timer"
static var duration = "com.toast-swift.duration"
static var point = "com.toast-swift.point"
static var completion = "com.toast-swift.completion"
static var activeToasts = "com.toast-swift.activeToasts"
static var activityView = "com.toast-swift.activityView"
static var queue = "com.toast-swift.queue"
}
/**
Swift closures can't be directly associated with objects via the
Objective-C runtime, so the (ugly) solution is to wrap them in a
class that can be used with associated objects.
*/
private class ToastCompletionWrapper {
let completion: ((Bool) -> Void)?
init(_ completion: ((Bool) -> Void)?) {
self.completion = completion
}
}
private enum ToastError: Error {
case missingParameters
}
private var activeToasts: NSMutableArray {
get {
if let activeToasts = objc_getAssociatedObject(self, &ToastKeys.activeToasts) as? NSMutableArray {
return activeToasts
} else {
let activeToasts = NSMutableArray()
objc_setAssociatedObject(self, &ToastKeys.activeToasts, activeToasts, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return activeToasts
}
}
}
private var queue: NSMutableArray {
get {
if let queue = objc_getAssociatedObject(self, &ToastKeys.queue) as? NSMutableArray {
return queue
} else {
let queue = NSMutableArray()
objc_setAssociatedObject(self, &ToastKeys.queue, queue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return queue
}
}
}
// MARK: - Make Toast Methods
/**
Creates and presents a new toast view.
@param message The message to be displayed
@param duration The toast duration
@param position The toast's position
@param title The title
@param image The image
@param style The style. The shared style will be used when nil
@param completion The completion closure, executed after the toast view disappears.
didTap will be `true` if the toast view was dismissed from a tap.
*/
func makeToast(_ message: String?, duration: TimeInterval = ToastManager.shared.duration, position: ToastPosition = ToastManager.shared.position, title: String? = nil, image: UIImage? = nil, style: ToastStyle = ToastManager.shared.style, completion: ((_ didTap: Bool) -> Void)? = nil) {
do {
let toast = try toastViewForMessage(message, title: title, image: image, style: style)
showToast(toast, duration: duration, position: position, completion: completion)
} catch ToastError.missingParameters {
print("Error: message, title, and image are all nil")
} catch {}
}
/**
Creates a new toast view and presents it at a given center point.
@param message The message to be displayed
@param duration The toast duration
@param point The toast's center point
@param title The title
@param image The image
@param style The style. The shared style will be used when nil
@param completion The completion closure, executed after the toast view disappears.
didTap will be `true` if the toast view was dismissed from a tap.
*/
func makeToast(_ message: String?, duration: TimeInterval = ToastManager.shared.duration, point: CGPoint, title: String?, image: UIImage?, style: ToastStyle = ToastManager.shared.style, completion: ((_ didTap: Bool) -> Void)?) {
do {
let toast = try toastViewForMessage(message, title: title, image: image, style: style)
showToast(toast, duration: duration, point: point, completion: completion)
} catch ToastError.missingParameters {
print("Error: message, title, and image cannot all be nil")
} catch {}
}
// MARK: - Show Toast Methods
/**
Displays any view as toast at a provided position and duration. The completion closure
executes when the toast view completes. `didTap` will be `true` if the toast view was
dismissed from a tap.
@param toast The view to be displayed as toast
@param duration The notification duration
@param position The toast's position
@param completion The completion block, executed after the toast view disappears.
didTap will be `true` if the toast view was dismissed from a tap.
*/
func showToast(_ toast: UIView, duration: TimeInterval = ToastManager.shared.duration, position: ToastPosition = ToastManager.shared.position, completion: ((_ didTap: Bool) -> Void)? = nil) {
let point = position.centerPoint(forToast: toast, inSuperview: self)
showToast(toast, duration: duration, point: point, completion: completion)
}
/**
Displays any view as toast at a provided center point and duration. The completion closure
executes when the toast view completes. `didTap` will be `true` if the toast view was
dismissed from a tap.
@param toast The view to be displayed as toast
@param duration The notification duration
@param point The toast's center point
@param completion The completion block, executed after the toast view disappears.
didTap will be `true` if the toast view was dismissed from a tap.
*/
func showToast(_ toast: UIView, duration: TimeInterval = ToastManager.shared.duration, point: CGPoint, completion: ((_ didTap: Bool) -> Void)? = nil) {
objc_setAssociatedObject(toast, &ToastKeys.completion, ToastCompletionWrapper(completion), .OBJC_ASSOCIATION_RETAIN_NONATOMIC);
if ToastManager.shared.isQueueEnabled, activeToasts.count > 0 {
objc_setAssociatedObject(toast, &ToastKeys.duration, NSNumber(value: duration), .OBJC_ASSOCIATION_RETAIN_NONATOMIC);
objc_setAssociatedObject(toast, &ToastKeys.point, NSValue(cgPoint: point), .OBJC_ASSOCIATION_RETAIN_NONATOMIC);
queue.add(toast)
} else {
showToast(toast, duration: duration, point: point)
}
}
// MARK: - Hide Toast Methods
/**
Hides the active toast. If there are multiple toasts active in a view, this method
hides the oldest toast (the first of the toasts to have been presented).
@see `hideAllToasts()` to remove all active toasts from a view.
@warning This method has no effect on activity toasts. Use `hideToastActivity` to
hide activity toasts.
*/
func hideToast() {
guard let activeToast = activeToasts.firstObject as? UIView else { return }
hideToast(activeToast)
}
/**
Hides an active toast.
@param toast The active toast view to dismiss. Any toast that is currently being displayed
on the screen is considered active.
@warning this does not clear a toast view that is currently waiting in the queue.
*/
func hideToast(_ toast: UIView) {
guard activeToasts.contains(toast) else { return }
hideToast(toast, fromTap: false)
}
/**
Hides all toast views.
@param includeActivity If `true`, toast activity will also be hidden. Default is `false`.
@param clearQueue If `true`, removes all toast views from the queue. Default is `true`.
*/
func hideAllToasts(includeActivity: Bool = false, clearQueue: Bool = true) {
if clearQueue {
clearToastQueue()
}
activeToasts.compactMap { $0 as? UIView }
.forEach { hideToast($0) }
if includeActivity {
hideToastActivity()
}
}
/**
Removes all toast views from the queue. This has no effect on toast views that are
active. Use `hideAllToasts(clearQueue:)` to hide the active toasts views and clear
the queue.
*/
func clearToastQueue() {
queue.removeAllObjects()
}
// MARK: - Activity Methods
/**
Creates and displays a new toast activity indicator view at a specified position.
@warning Only one toast activity indicator view can be presented per superview. Subsequent
calls to `makeToastActivity(position:)` will be ignored until `hideToastActivity()` is called.
@warning `makeToastActivity(position:)` works independently of the `showToast` methods. Toast
activity views can be presented and dismissed while toast views are being displayed.
`makeToastActivity(position:)` has no effect on the queueing behavior of the `showToast` methods.
@param position The toast's position
*/
func makeToastActivity(_ position: ToastPosition) {
// sanity
guard objc_getAssociatedObject(self, &ToastKeys.activityView) as? UIView == nil else { return }
let toast = createToastActivityView()
let point = position.centerPoint(forToast: toast, inSuperview: self)
makeToastActivity(toast, point: point)
}
/**
Creates and displays a new toast activity indicator view at a specified position.
@warning Only one toast activity indicator view can be presented per superview. Subsequent
calls to `makeToastActivity(position:)` will be ignored until `hideToastActivity()` is called.
@warning `makeToastActivity(position:)` works independently of the `showToast` methods. Toast
activity views can be presented and dismissed while toast views are being displayed.
`makeToastActivity(position:)` has no effect on the queueing behavior of the `showToast` methods.
@param point The toast's center point
*/
func makeToastActivity(_ point: CGPoint) {
// sanity
guard objc_getAssociatedObject(self, &ToastKeys.activityView) as? UIView == nil else { return }
let toast = createToastActivityView()
makeToastActivity(toast, point: point)
}
/**
Dismisses the active toast activity indicator view.
*/
func hideToastActivity() {
if let toast = objc_getAssociatedObject(self, &ToastKeys.activityView) as? UIView {
UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: [.curveEaseIn, .beginFromCurrentState], animations: {
toast.alpha = 0.0
}) { _ in
toast.removeFromSuperview()
objc_setAssociatedObject(self, &ToastKeys.activityView, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
// MARK: - Private Activity Methods
private func makeToastActivity(_ toast: UIView, point: CGPoint) {
toast.alpha = 0.0
toast.center = point
objc_setAssociatedObject(self, &ToastKeys.activityView, toast, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
self.addSubview(toast)
UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: .curveEaseOut, animations: {
toast.alpha = 1.0
})
}
private func createToastActivityView() -> UIView {
let style = ToastManager.shared.style
let activityView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: style.activitySize.width, height: style.activitySize.height))
activityView.backgroundColor = style.activityBackgroundColor
activityView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin]
activityView.layer.cornerRadius = style.cornerRadius
if style.displayShadow {
activityView.layer.shadowColor = style.shadowColor.cgColor
activityView.layer.shadowOpacity = style.shadowOpacity
activityView.layer.shadowRadius = style.shadowRadius
activityView.layer.shadowOffset = style.shadowOffset
}
let activityIndicatorView = UIActivityIndicatorView(style: .whiteLarge)
activityIndicatorView.center = CGPoint(x: activityView.bounds.size.width / 2.0, y: activityView.bounds.size.height / 2.0)
activityView.addSubview(activityIndicatorView)
activityIndicatorView.color = style.activityIndicatorColor
activityIndicatorView.startAnimating()
return activityView
}
// MARK: - Private Show/Hide Methods
private func showToast(_ toast: UIView, duration: TimeInterval, point: CGPoint) {
toast.center = point
toast.alpha = 0.0
if ToastManager.shared.isTapToDismissEnabled {
let recognizer = UITapGestureRecognizer(target: self, action: #selector(UIView.handleToastTapped(_:)))
toast.addGestureRecognizer(recognizer)
toast.isUserInteractionEnabled = true
toast.isExclusiveTouch = true
}
activeToasts.add(toast)
self.addSubview(toast)
UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: [.curveEaseOut, .allowUserInteraction], animations: {
toast.alpha = 1.0
}) { _ in
let timer = Timer(timeInterval: duration, target: self, selector: #selector(UIView.toastTimerDidFinish(_:)), userInfo: toast, repeats: false)
RunLoop.main.add(timer, forMode: .common)
objc_setAssociatedObject(toast, &ToastKeys.timer, timer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
private func hideToast(_ toast: UIView, fromTap: Bool) {
if let timer = objc_getAssociatedObject(toast, &ToastKeys.timer) as? Timer {
timer.invalidate()
}
UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: [.curveEaseIn, .beginFromCurrentState], animations: {
toast.alpha = 0.0
}) { _ in
toast.removeFromSuperview()
self.activeToasts.remove(toast)
if let wrapper = objc_getAssociatedObject(toast, &ToastKeys.completion) as? ToastCompletionWrapper, let completion = wrapper.completion {
completion(fromTap)
}
if let nextToast = self.queue.firstObject as? UIView, let duration = objc_getAssociatedObject(nextToast, &ToastKeys.duration) as? NSNumber, let point = objc_getAssociatedObject(nextToast, &ToastKeys.point) as? NSValue {
self.queue.removeObject(at: 0)
self.showToast(nextToast, duration: duration.doubleValue, point: point.cgPointValue)
}
}
}
// MARK: - Events
@objc
private func handleToastTapped(_ recognizer: UITapGestureRecognizer) {
guard let toast = recognizer.view else { return }
hideToast(toast, fromTap: true)
}
@objc
private func toastTimerDidFinish(_ timer: Timer) {
guard let toast = timer.userInfo as? UIView else { return }
hideToast(toast)
}
// MARK: - Toast Construction
/**
Creates a new toast view with any combination of message, title, and image.
The look and feel is configured via the style. Unlike the `makeToast` methods,
this method does not present the toast view automatically. One of the `showToast`
methods must be used to present the resulting view.
@warning if message, title, and image are all nil, this method will throw
`ToastError.missingParameters`
@param message The message to be displayed
@param title The title
@param image The image
@param style The style. The shared style will be used when nil
@throws `ToastError.missingParameters` when message, title, and image are all nil
@return The newly created toast view
*/
func toastViewForMessage(_ message: String?, title: String?, image: UIImage?, style: ToastStyle) throws -> UIView {
// sanity
guard message != nil || title != nil || image != nil else {
throw ToastError.missingParameters
}
var messageLabel: UILabel?
var titleLabel: UILabel?
var imageView: UIImageView?
let wrapperView = UIView()
wrapperView.backgroundColor = style.backgroundColor
wrapperView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin]
wrapperView.layer.cornerRadius = style.cornerRadius
if style.displayShadow {
wrapperView.layer.shadowColor = UIColor.black.cgColor
wrapperView.layer.shadowOpacity = style.shadowOpacity
wrapperView.layer.shadowRadius = style.shadowRadius
wrapperView.layer.shadowOffset = style.shadowOffset
}
if let image = image {
imageView = UIImageView(image: image)
imageView?.contentMode = .scaleAspectFit
imageView?.frame = CGRect(x: style.horizontalPadding, y: style.verticalPadding, width: style.imageSize.width, height: style.imageSize.height)
}
var imageRect = CGRect.zero
if let imageView = imageView {
imageRect.origin.x = style.horizontalPadding
imageRect.origin.y = style.verticalPadding
imageRect.size.width = imageView.bounds.size.width
imageRect.size.height = imageView.bounds.size.height
}
if let title = title {
titleLabel = UILabel()
titleLabel?.numberOfLines = style.titleNumberOfLines
titleLabel?.font = style.titleFont
titleLabel?.textAlignment = style.titleAlignment
titleLabel?.lineBreakMode = .byTruncatingTail
titleLabel?.textColor = style.titleColor
titleLabel?.backgroundColor = UIColor.clear
titleLabel?.text = title;
let maxTitleSize = CGSize(width: (self.bounds.size.width * style.maxWidthPercentage) - imageRect.size.width, height: self.bounds.size.height * style.maxHeightPercentage)
let titleSize = titleLabel?.sizeThatFits(maxTitleSize)
if let titleSize = titleSize {
titleLabel?.frame = CGRect(x: 0.0, y: 0.0, width: titleSize.width, height: titleSize.height)
}
}
if let message = message {
messageLabel = UILabel()
messageLabel?.text = message
messageLabel?.numberOfLines = style.messageNumberOfLines
messageLabel?.font = style.messageFont
messageLabel?.textAlignment = style.messageAlignment
messageLabel?.lineBreakMode = .byTruncatingTail;
messageLabel?.textColor = style.messageColor
messageLabel?.backgroundColor = UIColor.clear
let maxMessageSize = CGSize(width: (self.bounds.size.width * style.maxWidthPercentage) - imageRect.size.width, height: self.bounds.size.height * style.maxHeightPercentage)
let messageSize = messageLabel?.sizeThatFits(maxMessageSize)
if let messageSize = messageSize {
let actualWidth = min(messageSize.width, maxMessageSize.width)
let actualHeight = min(messageSize.height, maxMessageSize.height)
messageLabel?.frame = CGRect(x: 0.0, y: 0.0, width: actualWidth, height: actualHeight)
}
}
var titleRect = CGRect.zero
if let titleLabel = titleLabel {
titleRect.origin.x = imageRect.origin.x + imageRect.size.width + style.horizontalPadding
titleRect.origin.y = style.verticalPadding
titleRect.size.width = titleLabel.bounds.size.width
titleRect.size.height = titleLabel.bounds.size.height
}
var messageRect = CGRect.zero
if let messageLabel = messageLabel {
messageRect.origin.x = imageRect.origin.x + imageRect.size.width + style.horizontalPadding
messageRect.origin.y = titleRect.origin.y + titleRect.size.height + style.verticalPadding
messageRect.size.width = messageLabel.bounds.size.width
messageRect.size.height = messageLabel.bounds.size.height
}
let longerWidth = max(titleRect.size.width, messageRect.size.width)
let longerX = max(titleRect.origin.x, messageRect.origin.x)
let wrapperWidth = max((imageRect.size.width + (style.horizontalPadding * 2.0)), (longerX + longerWidth + style.horizontalPadding))
let wrapperHeight = max((messageRect.origin.y + messageRect.size.height + style.verticalPadding), (imageRect.size.height + (style.verticalPadding * 2.0)))
wrapperView.frame = CGRect(x: 0.0, y: 0.0, width: wrapperWidth, height: wrapperHeight)
if let titleLabel = titleLabel {
titleRect.size.width = longerWidth
titleLabel.frame = titleRect
wrapperView.addSubview(titleLabel)
}
if let messageLabel = messageLabel {
messageRect.size.width = longerWidth
messageLabel.frame = messageRect
wrapperView.addSubview(messageLabel)
}
if let imageView = imageView {
wrapperView.addSubview(imageView)
}
return wrapperView
}
}
// MARK: - Toast Style
/**
`ToastStyle` instances define the look and feel for toast views created via the
`makeToast` methods as well for toast views created directly with
`toastViewForMessage(message:title:image:style:)`.
@warning `ToastStyle` offers relatively simple styling options for the default
toast view. If you require a toast view with more complex UI, it probably makes more
sense to create your own custom UIView subclass and present it with the `showToast`
methods.
*/
public struct ToastStyle {
public init() {}
/**
The background color. Default is `.black` at 80% opacity.
*/
public var backgroundColor: UIColor = UIColor.black.withAlphaComponent(0.8)
/**
The title color. Default is `UIColor.whiteColor()`.
*/
public var titleColor: UIColor = .white
/**
The message color. Default is `.white`.
*/
public var messageColor: UIColor = .white
/**
A percentage value from 0.0 to 1.0, representing the maximum width of the toast
view relative to it's superview. Default is 0.8 (80% of the superview's width).
*/
public var maxWidthPercentage: CGFloat = 0.8 {
didSet {
maxWidthPercentage = max(min(maxWidthPercentage, 1.0), 0.0)
}
}
/**
A percentage value from 0.0 to 1.0, representing the maximum height of the toast
view relative to it's superview. Default is 0.8 (80% of the superview's height).
*/
public var maxHeightPercentage: CGFloat = 0.8 {
didSet {
maxHeightPercentage = max(min(maxHeightPercentage, 1.0), 0.0)
}
}
/**
The spacing from the horizontal edge of the toast view to the content. When an image
is present, this is also used as the padding between the image and the text.
Default is 10.0.
*/
public var horizontalPadding: CGFloat = 10.0
/**
The spacing from the vertical edge of the toast view to the content. When a title
is present, this is also used as the padding between the title and the message.
Default is 10.0. On iOS11+, this value is added added to the `safeAreaInset.top`
and `safeAreaInsets.bottom`.
*/
public var verticalPadding: CGFloat = 10.0
/**
The corner radius. Default is 10.0.
*/
public var cornerRadius: CGFloat = 10.0;
/**
The title font. Default is `.boldSystemFont(16.0)`.
*/
public var titleFont: UIFont = .boldSystemFont(ofSize: 16.0)
/**
The message font. Default is `.systemFont(ofSize: 16.0)`.
*/
public var messageFont: UIFont = .systemFont(ofSize: 16.0)
/**
The title text alignment. Default is `NSTextAlignment.Left`.
*/
public var titleAlignment: NSTextAlignment = .left
/**
The message text alignment. Default is `NSTextAlignment.Left`.
*/
public var messageAlignment: NSTextAlignment = .left
/**
The maximum number of lines for the title. The default is 0 (no limit).
*/
public var titleNumberOfLines = 0
/**
The maximum number of lines for the message. The default is 0 (no limit).
*/
public var messageNumberOfLines = 0
/**
Enable or disable a shadow on the toast view. Default is `false`.
*/
public var displayShadow = false
/**
The shadow color. Default is `.black`.
*/
public var shadowColor: UIColor = .black
/**
A value from 0.0 to 1.0, representing the opacity of the shadow.
Default is 0.8 (80% opacity).
*/
public var shadowOpacity: Float = 0.8 {
didSet {
shadowOpacity = max(min(shadowOpacity, 1.0), 0.0)
}
}
/**
The shadow radius. Default is 6.0.
*/
public var shadowRadius: CGFloat = 6.0
/**
The shadow offset. The default is 4 x 4.
*/
public var shadowOffset = CGSize(width: 4.0, height: 4.0)
/**
The image size. The default is 80 x 80.
*/
public var imageSize = CGSize(width: 80.0, height: 80.0)
/**
The size of the toast activity view when `makeToastActivity(position:)` is called.
Default is 100 x 100.
*/
public var activitySize = CGSize(width: 100.0, height: 100.0)
/**
The fade in/out animation duration. Default is 0.2.
*/
public var fadeDuration: TimeInterval = 0.2
/**
Activity indicator color. Default is `.white`.
*/
public var activityIndicatorColor: UIColor = .white
/**
Activity background color. Default is `.black` at 80% opacity.
*/
public var activityBackgroundColor: UIColor = UIColor.black.withAlphaComponent(0.8)
}
// MARK: - Toast Manager
/**
`ToastManager` provides general configuration options for all toast
notifications. Backed by a singleton instance.
*/
public class ToastManager {
/**
The `ToastManager` singleton instance.
*/
public static let shared = ToastManager()
/**
The shared style. Used whenever toastViewForMessage(message:title:image:style:) is called
with with a nil style.
*/
public var style = ToastStyle()
/**
Enables or disables tap to dismiss on toast views. Default is `true`.
*/
public var isTapToDismissEnabled = true
/**
Enables or disables queueing behavior for toast views. When `true`,
toast views will appear one after the other. When `false`, multiple toast
views will appear at the same time (potentially overlapping depending
on their positions). This has no effect on the toast activity view,
which operates independently of normal toast views. Default is `false`.
*/
public var isQueueEnabled = false
/**
The default duration. Used for the `makeToast` and
`showToast` methods that don't require an explicit duration.
Default is 3.0.
*/
public var duration: TimeInterval = 3.0
/**
Sets the default position. Used for the `makeToast` and
`showToast` methods that don't require an explicit position.
Default is `ToastPosition.Bottom`.
*/
public var position: ToastPosition = .bottom
}
// MARK: - ToastPosition
public enum ToastPosition {
case top
case center
case bottom
fileprivate func centerPoint(forToast toast: UIView, inSuperview superview: UIView) -> CGPoint {
let topPadding: CGFloat = ToastManager.shared.style.verticalPadding + superview.csSafeAreaInsets.top
let bottomPadding: CGFloat = ToastManager.shared.style.verticalPadding + superview.csSafeAreaInsets.bottom
switch self {
case .top:
return CGPoint(x: superview.bounds.size.width / 2.0, y: (toast.frame.size.height / 2.0) + topPadding)
case .center:
return CGPoint(x: superview.bounds.size.width / 2.0, y: superview.bounds.size.height / 2.0)
case .bottom:
return CGPoint(x: superview.bounds.size.width / 2.0, y: (superview.bounds.size.height - (toast.frame.size.height / 2.0)) - bottomPadding)
}
}
}
// MARK: - Private UIView Extensions
private extension UIView {
var csSafeAreaInsets: UIEdgeInsets {
if #available(iOS 11.0, *) {
return self.safeAreaInsets
} else {
return .zero
}
}
}
| mit |
travismmorgan/TMPasscodeLock | TMPasscodeLock/TMPasscodeLockController.swift | 1 | 4076 | //
// TMPasscodeLockController.swift
// TMPasscodeLock
//
// Created by Travis Morgan on 1/16/17.
// Copyright © 2017 Travis Morgan. All rights reserved.
//
import UIKit
public enum TMPasscodeLockState {
case enter
case set
case change
case remove
}
public enum TMPasscodeLockStyle {
case basic
}
public protocol TMPasscodeLockControllerDelegate: class {
func passcodeLockController(passcodeLockController: TMPasscodeLockController, didFinishFor state: TMPasscodeLockState)
func passcodeLockControllerDidCancel(passcodeLockController: TMPasscodeLockController)
}
public class TMPasscodeLockController: NSObject, TMPasscodeLockViewControllerDelegate {
public weak var delegate: TMPasscodeLockControllerDelegate?
public var style: TMPasscodeLockStyle = .basic
public var state: TMPasscodeLockState = .set
public var isPresented: Bool {
get {
return rootViewController != nil
}
}
fileprivate var passcodeLockViewController: TMPasscodeLockViewController?
fileprivate var mainWindow: UIWindow?
fileprivate var rootViewController: UIViewController?
public convenience init(style: TMPasscodeLockStyle, state: TMPasscodeLockState) {
self.init()
self.style = style
self.state = state
}
public func presentIn(window: UIWindow, animated: Bool) {
guard !isPresented else { return }
if (state != .set) && !TMPasscodeLock.isPasscodeSet {
print("Passcode not set")
return
}
mainWindow = window
rootViewController = mainWindow?.rootViewController
passcodeLockViewController = TMPasscodeLockViewController(style: style, state: state)
passcodeLockViewController?.delegate = self
if animated {
UIView.transition(with: window, duration: CATransaction.animationDuration(), options: .transitionCrossDissolve, animations: {
self.mainWindow?.rootViewController = UINavigationController(rootViewController: self.passcodeLockViewController!)
}, completion: nil)
} else {
self.mainWindow?.rootViewController = UINavigationController(rootViewController: passcodeLockViewController!)
}
}
public func presentIn(viewController: UIViewController, animated: Bool) {
passcodeLockViewController = TMPasscodeLockViewController(style: style, state: state)
passcodeLockViewController?.delegate = self
viewController.present(UINavigationController(rootViewController: passcodeLockViewController!), animated: animated, completion: nil)
}
public func dismiss(animated: Bool) {
if mainWindow != nil {
if animated {
UIView.transition(from: self.mainWindow!.rootViewController!.view, to: self.rootViewController!.view, duration: CATransaction.animationDuration(), options: .transitionCrossDissolve, completion: { (finished) in
if finished {
self.mainWindow?.rootViewController = self.rootViewController
self.mainWindow = nil
self.rootViewController = nil
self.passcodeLockViewController = nil
}
})
} else {
mainWindow?.rootViewController = rootViewController
mainWindow = nil
rootViewController = nil
passcodeLockViewController = nil
}
} else {
passcodeLockViewController?.dismiss(animated: animated, completion: nil)
}
}
func passcodeLockViewControllerDidCancel() {
delegate?.passcodeLockControllerDidCancel(passcodeLockController: self)
dismiss(animated: true)
}
func passcodeLockViewControllerDidFinish(state: TMPasscodeLockState) {
delegate?.passcodeLockController(passcodeLockController: self, didFinishFor: state)
dismiss(animated: true)
}
}
| mit |
crossroadlabs/Boilerplate | Sources/Boilerplate/Optional.swift | 2 | 1265 | //===--- Optional.swift ------------------------------------------------------===//
//Copyright (c) 2016 Daniel Leping (dileping)
//
//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
public extension Optional {
func getOr(else el:@autoclosure () throws -> Wrapped) rethrows -> Wrapped {
return try self ?? el()
}
func getOr(else el:() throws -> Wrapped) rethrows -> Wrapped {
return try self ?? el()
}
func or(else el:@autoclosure () throws -> Wrapped?) rethrows -> Wrapped? {
return try self ?? el()
}
func or(else el:() throws -> Wrapped?) rethrows -> Wrapped? {
return try self ?? el()
}
}
| apache-2.0 |
hyperconnect/Bond | Bond/Bond+UITextField.swift | 1 | 4200 | //
// Bond+UITextField.swift
// Bond
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Srdan Rasic (@srdanrasic)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
@objc class TextFieldDynamicHelper
{
weak var control: UITextField?
var listener: (String -> Void)?
init(control: UITextField) {
self.control = control
control.addTarget(self, action: Selector("editingChanged:"), forControlEvents: .EditingChanged)
}
func editingChanged(control: UITextField) {
self.listener?(control.text ?? "")
}
deinit {
control?.removeTarget(self, action: nil, forControlEvents: .EditingChanged)
}
}
class TextFieldDynamic<T>: InternalDynamic<String>
{
let helper: TextFieldDynamicHelper
init(control: UITextField) {
self.helper = TextFieldDynamicHelper(control: control)
super.init(control.text ?? "")
self.helper.listener = { [unowned self] in
self.updatingFromSelf = true
self.value = $0
self.updatingFromSelf = false
}
}
}
private var textDynamicHandleUITextField: UInt8 = 0;
extension UITextField /*: Dynamical, Bondable */ {
public var dynText: Dynamic<String> {
if let d: AnyObject = objc_getAssociatedObject(self, &textDynamicHandleUITextField) {
return (d as? Dynamic<String>)!
} else {
let d = TextFieldDynamic<String>(control: self)
let bond = Bond<String>() { [weak self, weak d] v in
if let s = self, d = d where !d.updatingFromSelf {
s.text = v
}
}
d.bindTo(bond, fire: false, strongly: false)
d.retain(bond)
objc_setAssociatedObject(self, &textDynamicHandleUITextField, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
return d
}
}
public var designatedDynamic: Dynamic<String> {
return self.dynText
}
public var designatedBond: Bond<String> {
return self.dynText.valueBond
}
}
public func ->> (left: UITextField, right: Bond<String>) {
left.designatedDynamic ->> right
}
public func ->> <U: Bondable where U.BondType == String>(left: UITextField, right: U) {
left.designatedDynamic ->> right.designatedBond
}
public func ->> (left: UITextField, right: UITextField) {
left.designatedDynamic ->> right.designatedBond
}
public func ->> (left: UITextField, right: UILabel) {
left.designatedDynamic ->> right.designatedBond
}
public func ->> (left: UITextField, right: UITextView) {
left.designatedDynamic ->> right.designatedBond
}
public func ->> <T: Dynamical where T.DynamicType == String>(left: T, right: UITextField) {
left.designatedDynamic ->> right.designatedBond
}
public func ->> (left: Dynamic<String>, right: UITextField) {
left ->> right.designatedBond
}
public func <->> (left: UITextField, right: UITextField) {
left.designatedDynamic <->> right.designatedDynamic
}
public func <->> (left: Dynamic<String>, right: UITextField) {
left <->> right.designatedDynamic
}
public func <->> (left: UITextField, right: Dynamic<String>) {
left.designatedDynamic <->> right
}
public func <->> (left: UITextField, right: UITextView) {
left.designatedDynamic <->> right.designatedDynamic
}
| mit |
MichaelGuoXY/AccelDraw2 | AccelDraw2/AccelDraw2/DetailViewController.swift | 1 | 878 | //
// DetailViewController.swift
// AccelDraw2
//
// Created by Guo Xiaoyu on 2/16/16.
// Copyright © 2016 Xiaoyu Guo. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit |
ABTSoftware/SciChartiOSTutorial | v2.x/Sandbox/SciChart_Boilerplate_Swift_customTooltipDataView/SciChart_Boilerplate_Swift/ChartView.swift | 1 | 2943 | //
// SCSLineChartView.swift
// SciChartSwiftDemo
//
// Created by Mykola Hrybeniuk on 5/30/16.
// Copyright © 2016 SciChart Ltd. All rights reserved.
//
import UIKit
import SciChart
class CustomSeriesDataView : SCIXySeriesDataView {
static override func createInstance() -> SCITooltipDataView! {
let view : CustomSeriesDataView = (Bundle.main.loadNibNamed("CustomSeriesDataView", owner: nil, options: nil)![0] as? CustomSeriesDataView)!
view.translatesAutoresizingMaskIntoConstraints = false
return view
}
override func setData(_ data: SCISeriesInfo!) {
let series : SCIRenderableSeriesProtocol = data.renderableSeries()
let xAxis = series.xAxis
let yAxis = series.yAxis
self.nameLabel.text = data.seriesName()
var xFormattedValue : String? = data.fortmatterdValue(fromSeriesInfo: data.xValue(), for: series.dataSeries.xType())
if (xFormattedValue == nil) {
xFormattedValue = xAxis?.formatCursorText(data.xValue())
}
var yFormattedValue : String? = data.fortmatterdValue(fromSeriesInfo: data.yValue(), for: series.dataSeries.yType())
if (yFormattedValue == nil) {
yFormattedValue = yAxis?.formatCursorText(data.yValue())
}
self.dataLabel.text = String(format: "Custom-X: %@ Custom-Y %@", xFormattedValue!, yFormattedValue!)
self.invalidateIntrinsicContentSize()
}
}
class CustomSeriesInfo : SCIXySeriesInfo {
override func createDataSeriesView() -> SCITooltipDataView! {
let view : CustomSeriesDataView = CustomSeriesDataView.createInstance() as! CustomSeriesDataView
view.setData(self)
return view;
}
}
class CustomLineSeries : SCIFastLineRenderableSeries {
override func toSeriesInfo(withHitTest info: SCIHitTestInfo) -> SCISeriesInfo! {
return CustomSeriesInfo(series: self, hitTest: info)
}
}
class ChartView: SCIChartSurface {
var data1 : SCIXyDataSeries! = nil
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let xAxis = SCINumericAxis()
xAxis.axisId = "XAxis"
let yAxis = SCINumericAxis()
yAxis.axisId = "YAxis"
self.xAxes.add(xAxis)
self.yAxes.add(yAxis)
self.chartModifiers.add(SCIRolloverModifier())
addSeries()
}
private func addSeries() {
data1 = SCIXyDataSeries(xType: .float, yType: .float)
for i in 0...10 {
data1.appendX(SCIGeneric(i), y: SCIGeneric((i % 3) * 2))
}
let renderSeries1 = CustomLineSeries()
renderSeries1.dataSeries = data1
renderSeries1.xAxisId = "XAxis"
renderSeries1.yAxisId = "YAxis"
self.renderableSeries.add(renderSeries1)
self.invalidateElement()
}
}
| mit |
fespinoza/linked-ideas-osx | LinkedIdeas-Shared/Sources/ViewModels/DrawableConcept.swift | 1 | 1271 | //
// File.swift
// LinkedIdeas
//
// Created by Felipe Espinoza Castillo on 16/02/2017.
// Copyright © 2017 Felipe Espinoza Dev. All rights reserved.
//
#if os(iOS)
import UIKit
public typealias BezierPath = UIBezierPath
extension CGRect {
func fill() {
BezierPath(rect: self).fill()
}
}
#else
import AppKit
public typealias BezierPath = NSBezierPath
#endif
public struct DrawableConcept: DrawableElement {
let concept: Concept
public init(concept: Concept) {
self.concept = concept
}
public var drawingBounds: CGRect { return concept.area }
public func draw() {
drawBackground()
concept.draw()
drawSelectedRing()
drawForDebug()
}
func drawBackground() {
Color.white.set()
drawingBounds.fill()
}
func drawSelectedRing() {
guard concept.isSelected else {
return
}
Color(red: 146/255, green: 178/255, blue: 254/255, alpha: 1).set()
let bezierPath = BezierPath(rect: drawingBounds)
bezierPath.lineWidth = 1
bezierPath.stroke()
concept.leftHandler?.draw()
concept.rightHandler?.draw()
}
public func drawForDebug() {
if isDebugging() {
drawDebugHelpers()
drawCenteredDotAtPoint(concept.centerPoint, color: Color.red)
}
}
}
| mit |
jtbandes/swift | test/ClangImporter/subclass_existentials_swift3.swift | 12 | 959 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -verify -o - -primary-file %s -swift-version 3
// REQUIRES: objc_interop
import Foundation
// FIXME: Consider better diagnostics here.
class SwiftLaundryService : NSLaundry {
// expected-error@-1 {{type 'SwiftLaundryService' does not conform to protocol 'NSLaundry'}}
var g: (Garment & Coat)? = nil
func wash(_ g: Garment & Coat) { // expected-note {{candidate has non-matching type '(Coat & Garment) -> ()'}}
self.g = g
}
func bleach(_ g: Garment & Coat & Cotton) {} // expected-note {{candidate has non-matching type '(Coat & Cotton & Garment) -> ()'}}
func dry() -> Garment & Coat { // expected-note {{candidate has non-matching type '() -> Coat & Garment'}}
return g!
}
}
class OldSwiftLaundryService : NSLaundry {
var g: Coat? = nil
func wash(_ g: Coat) {
self.g = g
}
func bleach(_ g: Coat) {}
func dry() -> Coat {
return g!
}
}
| apache-2.0 |
PureSwift/Bluetooth | Sources/BluetoothGATT/GATTAlertCategory.swift | 1 | 2000 | //
// GATTAlertCategory.swift
// Bluetooth
//
// Created by Carlos Duclos on 6/13/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
/**
Categories of alerts/messages.
The value of the characteristic is an unsigned 8 bit integer that has a fixed point exponent of 0.
The Alert Category ID characteristic defines the predefined categories of messages as an enumeration.
- Example:
The value 0x01 is interpreted as “Email”
- SeeAlso: [New Alert](https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.new_alert.xml)
*/
@frozen
public enum GATTAlertCategory: UInt8, GATTCharacteristic {
internal static let length = 1
public static var uuid: BluetoothUUID { return .alertCategoryId }
/// Simple Alert: General text alert or non-text alert
case simpleAlert = 0
/// Email: Alert when Email messages arrives
case email
/// News: News feeds such as RSS, Atom
case news
/// Call: Incoming call
case call
/// Missed call: Missed Call
case missedCall
/// SMS/MMS: SMS/MMS message arrives
case sms
/// Voice mail: Voice mail
case voiceMail
/// Schedule: Alert occurred on calendar, planner
case schedule
/// High Prioritized Alert: Alert that should be handled as high priority
case highPrioritizedAlert
/// Instant Message: Alert for incoming instant messages
case instantMessage
public init?(data: Data) {
guard data.count == type(of: self).length
else { return nil }
self.init(rawValue: data[0])
}
public var data: Data {
return Data([rawValue])
}
}
extension GATTAlertCategory: Equatable {
public static func == (lhs: GATTAlertCategory,
rhs: GATTAlertCategory) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
| mit |
PureSwift/Bluetooth | Sources/Bluetooth/ClassOfDevice.swift | 1 | 17545 | //
// ClassOfDevice.swift
// Bluetooth
//
// Created by Alsey Coleman Miller on 6/1/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
public struct ClassOfDevice: Equatable {
internal static let length = 3
public var formatType: FormatType
public var majorServiceClass: BitMaskOptionSet<MajorServiceClass>
public var majorDeviceClass: MajorDeviceClass
public init(formatType: FormatType,
majorServiceClass: BitMaskOptionSet<MajorServiceClass>,
majorDeviceClass: MajorDeviceClass) {
self.formatType = formatType
self.majorServiceClass = majorServiceClass
self.majorDeviceClass = majorDeviceClass
}
public init?(data: Data) {
guard data.count == type(of: self).length
else { return nil }
guard let formatType = FormatType(rawValue: (data[0] << 6) >> 6)
else { return nil }
self.formatType = formatType
let majorServiceValue = UInt16(littleEndian: UInt16(bytes: (data[1], data[2]))) >> 5
self.majorServiceClass = BitMaskOptionSet<MajorServiceClass>(rawValue: majorServiceValue)
let majorDeviceClassType = MajorDeviceClassType(rawValue: (data[1] << 3) >> 3) ?? MajorDeviceClassType.miscellaneous
switch majorDeviceClassType {
case .miscellaneous:
self.majorDeviceClass = .miscellaneous
case .computer:
self.majorDeviceClass = .computer(Computer(rawValue: data[0] >> 2) ?? .uncategorized)
case .phone:
self.majorDeviceClass = .phone(Phone(rawValue: data[0] >> 2) ?? .uncategorized)
case .lanNetwork:
self.majorDeviceClass = .lanNetwork(NetworkAccessPoint(rawValue: data[0] >> 2) ?? .fullyAvailable)
case .audioVideo:
self.majorDeviceClass = .audioVideo(AudioVideo(rawValue: data[0] >> 2) ?? .uncategorized)
case .peripheral:
self.majorDeviceClass = .peripheral(PeripheralKeyboardPointing(rawValue: data[0] >> 6) ?? .notKeyboard,
PeripheralDevice(rawValue: (data[0] << 2) >> 4) ?? .uncategorized)
case .imaging:
self.majorDeviceClass = .imaging(BitMaskOptionSet<Imaging>(rawValue: data[0] >> 4))
case .wearable:
self.majorDeviceClass = .wearable(Wearable(rawValue: data[0] >> 2) ?? .uncategorized)
case .toy:
self.majorDeviceClass = .toy(Toy(rawValue: data[0] >> 2) ?? .uncategorized)
case .health:
self.majorDeviceClass = .health(Health(rawValue: data[0] >> 2) ?? .uncategorized)
case .uncategorized:
self.majorDeviceClass = .uncategorized
}
}
public var data: Data {
// combine Format Type with Major Device Class
let firstByte = formatType.rawValue | (majorDeviceClass.minorClassValue << 2)
// get first 3 bits of the Mejor Service Class
let majorServiceClass3Bits = (majorServiceClass.rawValue.bytes.0 << 5) /// e.g. 11100000
// combine part of the Major Device Class of part with the Major Service Class
let secondByte = majorDeviceClass.type.rawValue | majorServiceClass3Bits
let thirdByte = (majorServiceClass.rawValue.bytes.1 << 5) | (majorServiceClass.rawValue.bytes.0 >> 3)
return Data([firstByte, secondByte, thirdByte])
}
}
extension ClassOfDevice {
public struct FormatType: RawRepresentable, Equatable, Hashable {
public static let min = FormatType(0b00)
public static let max = FormatType(0b11)
public let rawValue: UInt8
public init?(rawValue: UInt8) {
guard rawValue <= type(of: self).max.rawValue, rawValue >= type(of: self).min.rawValue
else { return nil }
self.rawValue = rawValue
}
private init(_ unsafe: UInt8) {
self.rawValue = unsafe
}
}
}
public extension ClassOfDevice {
enum MajorServiceClass: UInt16, BitMaskOption {
/// Limited Discoverable Mode [Ref #1]
case limitedDiscoverable = 0b01
/// Positioning (Location identification)
case positioning = 0b1000
/// Networking (LAN, Ad hoc, ...)
case networking = 0b10000
/// Rendering (Printing, Speakers, ...)
case rendering = 0b100000
/// Capturing (Scanner, Microphone, ...)
case capturing = 0b1000000
/// Object Transfer (v-Inbox, v-Folder, ...)
case objectTransfer = 0b10000000
/// Audio (Speaker, Microphone, Headset service, ...)
case audio = 0b1_00000000
/// Telephony (Cordless telephony, Modem, Headset service, ...)
case telephony = 0b10_00000000
/// Information (WEB-server, WAP-server, ...)
case information = 0b100_00000000
public static let allCases: [MajorServiceClass] = [
.limitedDiscoverable,
.positioning,
.networking,
.rendering,
.capturing,
.objectTransfer,
.audio,
.telephony,
.information
]
}
}
public extension ClassOfDevice {
enum MajorDeviceClass: Equatable {
/// Miscellaneous
case miscellaneous
/// Computer (desktop, notebook, PDA, organizer, ... )
case computer(Computer)
/// Phone (cellular, cordless, pay phone, modem, ...)
case phone(Phone)
/// Networking (LAN, Ad hoc, ...)
case lanNetwork(NetworkAccessPoint)
/// Audio/Video (headset, speaker, stereo, video display, VCR, ...
case audioVideo(AudioVideo)
/// Peripheral (mouse, joystick, keyboard, ... )
case peripheral(PeripheralKeyboardPointing, PeripheralDevice)
/// Imaging (printer, scanner, camera, display, ...)
case imaging(BitMaskOptionSet<Imaging>)
/// Wearable
case wearable(Wearable)
/// Toy
case toy(Toy)
/// Health
case health(Health)
/// Uncategorized: device code not specified
case uncategorized
var type: MajorDeviceClassType {
switch self {
case .miscellaneous: return .miscellaneous
case .computer: return .computer
case .phone: return .phone
case .lanNetwork: return .lanNetwork
case .audioVideo: return .audioVideo
case .peripheral: return .peripheral
case .imaging: return .imaging
case .wearable: return .wearable
case .toy: return .toy
case .health: return .health
case .uncategorized: return .uncategorized
}
}
var minorClassValue: UInt8 {
switch self {
case .miscellaneous:
return 0
case .computer(let computer):
return computer.rawValue
case .phone(let phone):
return phone.rawValue
case .lanNetwork(let network):
return network.rawValue
case .audioVideo(let audioVideo):
return audioVideo.rawValue
case .peripheral(let keyboardPointing, let device):
return (keyboardPointing.rawValue << 4) | device.rawValue
case .imaging(let imaging):
return imaging.rawValue
case .wearable(let wearable):
return wearable.rawValue
case .toy(let toy):
return toy.rawValue
case .health(let health):
return health.rawValue
case .uncategorized:
return MajorDeviceClassType.uncategorized.rawValue
}
}
}
enum MajorDeviceClassType: UInt8 {
/// Miscellaneous
case miscellaneous = 0b00
/// Computer (desktop, notebook, PDA, organizer, ... )
case computer = 0b1
/// Phone (cellular, cordless, pay phone, modem, ...)
case phone = 0b10
/// LAN /Network Access point
case lanNetwork = 0b11
/// Audio/Video (headset, speaker, stereo, video display, VCR, ...
case audioVideo = 0b100
/// Peripheral (mouse, joystick, keyboard, ... )
case peripheral = 0b101
/// Imaging (printer, scanner, camera, display, ...)
case imaging = 0b110
/// Wearable
case wearable = 0b111
/// Toy
case toy = 0b1000
/// Health
case health = 0b1001
/// Uncategorized: device code not specified
case uncategorized = 0b11111
}
}
public extension ClassOfDevice {
typealias Computer = MinorDeviceClass.Computer
typealias Phone = MinorDeviceClass.Phone
typealias NetworkAccessPoint = MinorDeviceClass.NetworkAccessPoint
typealias AudioVideo = MinorDeviceClass.AudioVideo
typealias PeripheralKeyboardPointing = MinorDeviceClass.PeripheralKeyboardPointing
typealias PeripheralDevice = MinorDeviceClass.PeripheralDevice
typealias Imaging = MinorDeviceClass.Imaging
typealias Wearable = MinorDeviceClass.Wearable
typealias Toy = MinorDeviceClass.Toy
typealias Health = MinorDeviceClass.Health
enum MinorDeviceClass {}
}
public extension ClassOfDevice.MinorDeviceClass {
enum Computer: UInt8 {
/// Uncategorized
case uncategorized = 0b00
/// Desktop workstation
case desktopWorkstation = 0b01
/// Server-class computer
case serverClassComputer = 0b10
/// Laptop
case laptop = 0b11
/// Handheld PC/PDA (clamshell)
case handHeld = 0b100
/// Palm-size PC/PDA
case palmSize = 0b101
/// Wearable computer (watch size)
case wearable = 0b110
// Tablet
case tablet = 0b111
}
}
public extension ClassOfDevice.MinorDeviceClass {
enum Phone: UInt8 {
/// Uncategorized, code for device not assigned
case uncategorized = 0b00
/// Cellular
case celullar = 0b01
/// Cordless
case cordless = 0b10
/// Smartphone
case smartphone = 0b11
/// Wired modem or voice gateway
case wiredModem = 0b100
/// Common ISDN access
case commonISDNAccess = 0b101
}
}
public extension ClassOfDevice.MinorDeviceClass {
enum NetworkAccessPoint: UInt8 {
/// Fully available
case fullyAvailable = 0b00
/// 1% to 17% utilized
case from1To17Used = 0b01
/// 17% to 33% utilized
case from17To33Used = 0b10
/// 33% to 50% utilized
case from33To50Used = 0b11
/// 50% to 67% utilized
case from50to67Used = 0b100
/// 67% to 83% utilized
case from67to83Used = 0b101
/// 83% to 99% utilized
case from83to99Used = 0b110
/// No service available
case noServiceAvailable = 0b111
}
}
public extension ClassOfDevice.MinorDeviceClass {
enum AudioVideo: UInt8 {
/// Uncategorized, code not assigned
case uncategorized = 0b00
/// Wearable Headset Device
case wearableHeadSet = 0b01
/// Hands-free Device
case handsFree = 0b10
/// Microphone
case microphone = 0b100
/// Loudspeaker
case loudspeaker = 0b101
/// Headphones
case headphones = 0b110
/// Portable Audio
case portableAudio = 0b111
/// Car audio
case carAudio = 0b1000
/// Set-top box
case setTopBox = 0b1001
/// HiFi Audio Device
case hifiAudio = 0b1010
/// VCR
case vcr = 0b1011
/// Video Camera
case videoCamera = 0b1100
/// Camcorder
case camcorder = 0b1101
/// Video Monitor
case videoMonitor = 0b1110
/// Video Display and Loudspeaker
case videoDisplayLoudspeaker = 0b1111
/// Video Conferencing
case videoConferencing = 0b10000
/// Gaming/Toy
case gamingToy = 0b10010
}
}
public extension ClassOfDevice.MinorDeviceClass {
enum PeripheralKeyboardPointing: UInt8 {
/// Not Keyboard / Not Pointing Device
case notKeyboard = 0b00
/// Keyboard
case keyboard = 0b01
/// Pointing device
case pointingDevice = 0b10
/// Combo keyboard/pointing device
case comboKeyboardPointingDevice = 0b11
}
enum PeripheralDevice: UInt8 {
/// Uncategorized device
case uncategorized = 0b00
/// Joystick
case joystick = 0b01
/// Gamepad
case gamepad = 0b10
/// Remote control
case remoteControl = 0b11
/// Sensing Device
case sensingDevice = 0b100
/// Digitizer Tablet
case digitizerTablet = 0b101
/// Card Reader (e.g. SIM Card Reader)
case cardReader = 0b110
/// Digital Pen
case digitalPen = 0b111
/// Handheld scanner for bar-codes, RFID, etc.
case handheldScannerBarCodes = 0b1000
/// Handheld gestural input device (e.g., "wand" form factor)
case handheldGesturalInput = 0b1001
}
}
public extension ClassOfDevice.MinorDeviceClass {
enum Imaging: UInt8, BitMaskOption {
/// Uncategorized
case uncategorized = 0b00
/// Display
case display = 0b01
/// Camera
case camera = 0b10
/// Scanner
case scanner = 0b100
/// Printer
case printer = 0b1000
public static let allCases: [ClassOfDevice.MinorDeviceClass.Imaging] = [
.uncategorized,
.display,
.camera,
.scanner,
.printer
]
}
}
public extension ClassOfDevice.MinorDeviceClass {
enum Wearable: UInt8 {
/// Uncategorized
case uncategorized = 0b00
/// Wristwatch
case wristwatch = 0b01
/// Pager
case pager = 0b10
/// Jacket
case jacket = 0b11
/// Helmet
case helmet = 0b100
/// Glasses
case glasses = 0b101
}
}
public extension ClassOfDevice.MinorDeviceClass {
enum Toy: UInt8 {
/// Uncategorized
case uncategorized = 0b00
/// Robot
case robot = 0b01
/// Vehicle
case vehicle = 0b10
/// Doll / Action figure
case actionFigure = 0b11
/// Controller
case controller = 0b100
/// Game
case game = 0b101
}
}
public extension ClassOfDevice.MinorDeviceClass {
enum Health: UInt8 {
/// Uncategorized
case uncategorized = 0b00
/// Blood Pressure Monitor
case bloodPressureMonitor = 0b01
/// Thermometer
case thermometer = 0b10
/// Weighing Scale
case weighingScale = 0b11
/// Glucose Meter
case glucoseMeter = 0b100
/// Pulse Oximeter
case pulseOximeter = 0b101
/// Heart/Pulse Rate Monitor
case heartRateMonitor = 0b110
/// Health Data Display
case healthDataDisplay = 0b111
/// Step Counter
case stepCounter = 0b1000
/// Body Composition Analyzer
case bodyCompositionAnalyzer = 0b1001
/// Peak Flow Monitor
case peakFlowMonitor = 0b1010
/// Medication Monitor
case medicationMonitor = 0b1011
/// Knee Prosthesis
case kneeProsthesis = 0b1100
/// Ankle Prosthesis
case ankleProsthesis = 0b1101
/// Generic Health Manager
case genericHealthManager = 0b1110
/// Personal Mobility Device
case personalMobilityDevice = 0b1111
}
}
| mit |
neerajgoyal12/NCore | Example/NCore/Config.swift | 1 | 733 | //
// Config.swift
// NCore_Example
//
// Created by Neeraj Goyal on 13/10/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Foundation
final class Config {
static let sharedConfig = Config()
var configuration: Dictionary<String, NSObject>!
var currentConfiguration: String!
private init() {
currentConfiguration = Bundle.main.object(forInfoDictionaryKey: "Config") as! String
let path: String? = Bundle.main.path(forResource: "Config", ofType: ".plist")
configuration = NSDictionary(contentsOfFile: path!)?.object(forKey: currentConfiguration) as! Dictionary<String, NSObject>
debugPrint("""
configuration : \(configuration)
""")
}
}
| mit |
lojals/curiosity_reader | curiosity_reader/curiosity_reader/src/views/ProfileVC.swift | 1 | 824 | //
// ProfileVC.swift
// curiosity_reader
//
// Created by Jorge Raul Ovalle Zuleta on 5/16/15.
// Copyright (c) 2015 Olinguito. All rights reserved.
//
import UIKit
class ProfileVC: GenericVC {
override func viewDidLoad() {
super.viewDidLoad()
navBar.setType(3)
navBar.title.text = "Perfil"
navBar.title.font = UIFont.fontBold(20)
navBar.btnBack.addTarget(self, action: Selector("interactMenu"), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(menuView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
actView = 1
self.menuView.setColor(actView+3330)
}
}
| gpl-2.0 |
icepy/APNGKit | APNGKitDemo/AppDelegate.swift | 11 | 3350 | //
// AppDelegate.swift
// APNGKitDemo
//
// Created by Wei Wang on 15/8/29.
//
// Copyright (c) 2015 Wei Wang <onevcat@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
application.statusBarStyle = .LightContent
UINavigationBar.appearance().tintColor = UIColor.whiteColor()
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 |
austinzheng/swift-compiler-crashes | crashes-duplicates/24583-swift-typebase-gettypeofmember.swift | 9 | 283 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class A{
func b{
struct A{
class a{
{
}
}
protocol a{
func a{}
typealias e:a
}
}
}
class a{
enum S<>:A
protocol A
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/15697-swift-sourcemanager-getmessage.swift | 11 | 251 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
[ {
struct A {
enum S {
class B {
let a {
if true {
{
{
{
case
var {
class
case ,
| mit |
eurofurence/ef-app_ios | Packages/EurofurenceModel/Tests/EurofurenceModelTests/Test Doubles/Configurable Dependencies/CapturingMapCoordinateRender.swift | 2 | 762 | import EurofurenceModel
import Foundation
class CapturingMapCoordinateRender: MapCoordinateRender {
private struct Request: Hashable {
var graphic: Data
var x: Int
var y: Int
var radius: Int
}
private var requestsToResponses = [Request: Data]()
func render(x: Int, y: Int, radius: Int, onto data: Data) -> Data {
let request = Request(graphic: data, x: x, y: y, radius: radius)
return requestsToResponses[request] ?? .random
}
}
extension CapturingMapCoordinateRender {
func stub(_ data: Data, forGraphic graphic: Data, atX x: Int, y: Int, radius: Int) {
let request = Request(graphic: graphic, x: x, y: y, radius: radius)
requestsToResponses[request] = data
}
}
| mit |
plivesey/SwiftGen | Pods/Stencil/Sources/Variable.swift | 6 | 4518 | import Foundation
typealias Number = Float
class FilterExpression : Resolvable {
let filters: [(FilterType, [Variable])]
let variable: Variable
init(token: String, parser: TokenParser) throws {
let bits = token.characters.split(separator: "|").map({ String($0).trim(character: " ") })
if bits.isEmpty {
filters = []
variable = Variable("")
throw TemplateSyntaxError("Variable tags must include at least 1 argument")
}
variable = Variable(bits[0])
let filterBits = bits[bits.indices.suffix(from: 1)]
do {
filters = try filterBits.map {
let (name, arguments) = parseFilterComponents(token: $0)
let filter = try parser.findFilter(name)
return (filter, arguments)
}
} catch {
filters = []
throw error
}
}
func resolve(_ context: Context) throws -> Any? {
let result = try variable.resolve(context)
return try filters.reduce(result) { x, y in
let arguments = try y.1.map { try $0.resolve(context) }
return try y.0.invoke(value: x, arguments: arguments)
}
}
}
/// A structure used to represent a template variable, and to resolve it in a given context.
public struct Variable : Equatable, Resolvable {
public let variable: String
/// Create a variable with a string representing the variable
public init(_ variable: String) {
self.variable = variable
}
fileprivate func lookup() -> [String] {
return variable.characters.split(separator: ".").map(String.init)
}
/// Resolve the variable in the given context
public func resolve(_ context: Context) throws -> Any? {
var current: Any? = context
if (variable.hasPrefix("'") && variable.hasSuffix("'")) || (variable.hasPrefix("\"") && variable.hasSuffix("\"")) {
// String literal
return variable[variable.characters.index(after: variable.startIndex) ..< variable.characters.index(before: variable.endIndex)]
}
if let number = Number(variable) {
// Number literal
return number
}
for bit in lookup() {
current = normalize(current)
if let context = current as? Context {
current = context[bit]
} else if let dictionary = current as? [String: Any] {
current = dictionary[bit]
} else if let array = current as? [Any] {
if let index = Int(bit) {
if index >= 0 && index < array.count {
current = array[index]
} else {
current = nil
}
} else if bit == "first" {
current = array.first
} else if bit == "last" {
current = array.last
} else if bit == "count" {
current = array.count
}
} else if let object = current as? NSObject { // NSKeyValueCoding
#if os(Linux)
return nil
#else
current = object.value(forKey: bit)
#endif
} else if let value = current {
let mirror = Mirror(reflecting: value)
current = mirror.descendant(bit)
if current == nil {
return nil
}
} else {
return nil
}
}
if let resolvable = current as? Resolvable {
current = try resolvable.resolve(context)
} else if let node = current as? NodeType {
current = try node.render(context)
}
return normalize(current)
}
}
public func ==(lhs: Variable, rhs: Variable) -> Bool {
return lhs.variable == rhs.variable
}
func normalize(_ current: Any?) -> Any? {
if let current = current as? Normalizable {
return current.normalize()
}
return current
}
protocol Normalizable {
func normalize() -> Any?
}
extension Array : Normalizable {
func normalize() -> Any? {
return map { $0 as Any }
}
}
extension NSArray : Normalizable {
func normalize() -> Any? {
return map { $0 as Any }
}
}
extension Dictionary : Normalizable {
func normalize() -> Any? {
var dictionary: [String: Any] = [:]
for (key, value) in self {
if let key = key as? String {
dictionary[key] = Stencil.normalize(value)
} else if let key = key as? CustomStringConvertible {
dictionary[key.description] = Stencil.normalize(value)
}
}
return dictionary
}
}
func parseFilterComponents(token: String) -> (String, [Variable]) {
var components = token.smartSplit(separator: ":")
let name = components.removeFirst()
let variables = components
.joined(separator: ":")
.smartSplit(separator: ",")
.map { Variable($0) }
return (name, variables)
}
| mit |
jecht83/Flappy-Swift | Flappy-Swift/GameViewController.swift | 1 | 1828 | //
// GameViewController.swift
// Flappy Swift
//
// Created by Julio Montoya on 05/01/16.
// Copyright (c) 2016 Julio Montoya. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import SpriteKit
class GameViewController: UIViewController {
// MARK: - Outlets
@IBOutlet weak var skView: SKView!
// MARK: - Properties
override var prefersStatusBarHidden : Bool {
return true
}
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
constructScene()
}
// MARK: - Initializers
private func constructScene() {
skView.showsFPS = true
skView.showsNodeCount = true
// skView.showsPhysics = true
let scene = GameScene(size: skView.bounds.size)
skView.presentScene(scene)
}
}
| mit |
daggmano/photo-management-studio | src/Client/OSX/PMS-2/Photo Management Studio/Photo Management Studio/NSImageExtensions.swift | 1 | 820 | //
// NSImageExtensions.swift
// Photo Management Studio
//
// Created by Darren Oster on 28/04/2016.
// Copyright © 2016 Criterion Software. All rights reserved.
//
import Cocoa
extension NSImage {
func saveAsJpegWithPath(filePath: String) -> Void {
// Cache the reduced image
if let imageData = self.TIFFRepresentation {
if let imageRep = NSBitmapImageRep(data: imageData) {
let imageProps: [String: AnyObject] = [NSImageCompressionFactor: NSNumber(float: 1.0)]
let jpegData = imageRep.representationUsingType(.NSJPEGFileType, properties: imageProps)
do {
try jpegData?.writeToFile(filePath, options: .DataWritingWithoutOverwriting)
} catch {}
}
}
}
}
| mit |
gvzq/iOS-Twitter | Twitter/ProfileViewController.swift | 1 | 2913 | //
// ProfileViewController.swift
// Twitter
//
// Created by Gerardo Vazquez on 2/24/16.
// Copyright © 2016 Gerardo Vazquez. All rights reserved.
//
import UIKit
class ProfileViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var screenNameLabel: UILabel!
@IBOutlet weak var tweetsCountLabel: UILabel!
@IBOutlet weak var followingCountLabel: UILabel!
@IBOutlet weak var followersCountLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
var user: User!
var tweets: [Tweet]?
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
self.tableView.separatorInset = UIEdgeInsetsZero
profileImageView.setImageWithURL(NSURL(string: (user?.profileImageUrl)!)!)
nameLabel.text = user?.name
screenNameLabel.text = user?.screenName
let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
tweetsCountLabel.text = formatter.stringFromNumber((user?.tweetsCount)!)
followingCountLabel.text = formatter.stringFromNumber((user?.followingCount)!)
followersCountLabel.text = formatter.stringFromNumber((user?.followersCount)!)
TwitterClient.sharedInstance.userTimeLineWithParams(user.screenName, params: nil, completion: {(tweets, error) -> () in
print(self.user.screenName)
self.tweets = tweets
self.tableView.reloadData()
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
if tweets != nil {
return tweets!.count
} else {
return 0
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("UserTweetCell", forIndexPath: indexPath) as! UserTweetCell
cell.tweet = tweets![indexPath.row]
cell.selectionStyle = .Default
let backgroundView = UIView()
backgroundView.backgroundColor = UIColor.whiteColor()
cell.selectedBackgroundView = backgroundView
return cell
}
/*
// 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.
}
*/
}
| apache-2.0 |
apple/swift | validation-test/compiler_crashers_fixed/27612-swift-typechecker-checkunsupportedprotocoltype.swift | 65 | 475 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
class B
a{
struct S<T where g:d{class c{
class b{
let b=1
}protocol A{
var:B
| apache-2.0 |
githubxiangdong/DouYuZB | DouYuZB/DouYuZB/Classes/Home/View/AmuseMenuView.swift | 1 | 3153 | //
// AmuseMenuView.swift
// DouYuZB
//
// Created by new on 2017/5/16.
// Copyright © 2017年 9-kylins. All rights reserved.
//
import UIKit
private let kMenuCellID = "kMenuCellID"
class AmuseMenuView: UIView {
//MARK:- 定义属性
var groupModels : [AnchorGroupModel]? {
didSet {
collectionView.reloadData()
}
}
//MARK:- 控件属性
@IBOutlet var collectionView: UICollectionView!
@IBOutlet var pageControl: UIPageControl!
//MARK:- 系统回调函数
override func awakeFromNib() {
super.awakeFromNib()
// 设置该控件不随着父控件的拉伸而拉伸
autoresizingMask = UIViewAutoresizing()
collectionView.register(UINib(nibName: "AmuseMenuCell", bundle: nil), forCellWithReuseIdentifier: kMenuCellID)
//MARK:- 不能在这里面设置layout的尺寸,collectionView的frame是不对的在这里面
}
//MARK:- 在layoutSubviews()里面设置layout
override func layoutSubviews() {
super.layoutSubviews()
// 根据collectionView的layout设置layout.itemSize
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = collectionView.bounds.size
}
}
//MARK:- 快速创建AmuseMenuView的方法
extension AmuseMenuView {
class func amuseMenuView() -> AmuseMenuView {
return Bundle.main.loadNibNamed("AmuseMenuView", owner: nil, options: nil)?.first as! AmuseMenuView
}
}
//MARK:- 实现collectionView的数据源协议
extension AmuseMenuView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if groupModels == nil { return 0 }
let pageNum = (groupModels!.count - 1) / 8 + 1
pageControl.numberOfPages = pageNum
return pageNum
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kMenuCellID, for: indexPath) as! AmuseMenuCell
setupCellDataWithCell(cell: cell, indexPath: indexPath)
return cell
}
private func setupCellDataWithCell(cell : AmuseMenuCell, indexPath : IndexPath) {
// 0页:0~7
// 1页:8~15
// 2页:16~23
// 1, 取出起始位置和终点位置
let startIndex = indexPath.item * 8
var endIndex = (indexPath.item + 1) * 8 - 1
// 2, 判断越界的问题
if endIndex > groupModels!.count - 1 { // 这个地方可以强制解包,因为如果是0的话,就不会到这个方法里面
endIndex = groupModels!.count - 1
}
// 3, 给cell赋值
cell.groupModels = Array(groupModels![startIndex...endIndex])// 数组范围的写法
}
}
//MARK:- 实现collectionView的代理方法
extension AmuseMenuView : UICollectionViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
pageControl.currentPage = Int(scrollView.contentOffset.x / kScreenW)
}
}
| mit |
tensorflow/swift | Sources/SIL/SILPrinter.swift | 1 | 21968 | // Copyright 2019 The TensorFlow 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.
class SILPrinter: Printer {
func print(_ module: Module) {
print(module.functions, "\n\n") { print($0) }
}
func print(_ function: Function) {
print("sil ")
print(function.linkage)
print(whenEmpty: false, "", function.attributes, " ", " ") { print($0) }
print("@")
print(function.name)
print(" : ")
print(function.type)
print(whenEmpty: false, " {\n", function.blocks, "\n", "}") { print($0) }
}
func print(_ block: Block) {
print(block.identifier)
print(whenEmpty: false, "(", block.arguments, ", ", ")") { print($0) }
print(":")
indent()
print(block.operatorDefs) { print("\n"); print($0) }
print("\n")
print(block.terminatorDef)
print("\n")
unindent()
}
func print(_ operatorDef: OperatorDef) {
print(operatorDef.result, " = ") { print($0) }
print(operatorDef.operator)
print(operatorDef.sourceInfo) { print($0) }
}
func print(_ terminatorDef: TerminatorDef) {
print(terminatorDef.terminator)
print(terminatorDef.sourceInfo) { print($0) }
}
func print(_ op: Operator) {
switch op {
case let .allocStack(type, attributes):
print("alloc_stack ")
print(type)
print(whenEmpty: false, ", ", attributes, ", ", "") { print($0) }
case let .apply(nothrow, value, substitutions, arguments, type):
print("apply ")
print(when: nothrow, "[nothrow] ")
print(value)
print(whenEmpty: false, "<", substitutions, ", ", ">") { naked($0) }
print("(", arguments, ", ", ")") { print($0) }
print(" : ")
print(type)
case let .beginAccess(access, enforcement, noNestedConflict, builtin, operand):
print("begin_access ")
print("[")
print(access)
print("] ")
print("[")
print(enforcement)
print("] ")
print(when: noNestedConflict, "[noNestedConflict] ")
print(when: builtin, "[builtin] ")
print(operand)
case let .beginApply(nothrow, value, substitutions, arguments, type):
print("begin_apply ")
print(when: nothrow, "[nothrow] ")
print(value)
print(whenEmpty: false, "<", substitutions, ", ", ">") { naked($0) }
print("(", arguments, ", ", ")") { print($0) }
print(" : ")
print(type)
case let .beginBorrow(operand):
print("begin_borrow ")
print(operand)
case let .builtin(name, operands, type):
print("builtin ")
literal(name)
print("(", operands, ", ", ")") { print($0) }
print(" : ")
print(type)
case let .condFail(operand, message):
print("cond_fail ")
print(operand)
print(", ")
literal(message)
case let .convertEscapeToNoescape(notGuaranteed, escaped, operand, type):
print("convert_escape_to_noescape ")
print(when: notGuaranteed, "[not_guaranteed] ")
print(when: escaped, "[escaped] ")
print(operand)
print(" to ")
print(type)
case let .convertFunction(operand, withoutActuallyEscaping, type):
print("convert_function ")
print(operand)
print(" to ")
print(when: withoutActuallyEscaping, "[without_actually_escaping] ")
print(type)
case let .copyAddr(take, value, initialization, operand):
print("copy_addr ")
print(when: take, "[take] ")
print(value)
print(" to ")
print(when: initialization, "[initialization] ")
print(operand)
case let .copyValue(operand):
print("copy_value ")
print(operand)
case let .deallocStack(operand):
print("dealloc_stack ")
print(operand)
case let .debugValue(operand, attributes):
print("debug_value ")
print(operand)
print(whenEmpty: false, ", ", attributes, ", ", "") { print($0) }
case let .debugValueAddr(operand, attributes):
print("debug_value_addr ")
print(operand)
print(whenEmpty: false, ", ", attributes, ", ", "") { print($0) }
case let .destroyValue(operand):
print("destroy_value ")
print(operand)
case let .destructureTuple(operand):
print("destructure_tuple ")
print(operand)
case let .endAccess(abort, operand):
print("end_access ")
print(when: abort, "[abort] ")
print(operand)
case let .endApply(value):
print("end_apply ")
print(value)
case let .endBorrow(value):
print("end_borrow ")
print(value)
case let .enum(type, declRef, maybeOperand):
print("enum ")
print(type)
print(", ")
print(declRef)
if let operand = maybeOperand {
print(", ")
print(operand)
}
case let .floatLiteral(type, value):
print("float_literal ")
print(type)
print(", 0x")
print(value)
case let .functionRef(name, type):
print("function_ref ")
print("@")
print(name)
print(" : ")
print(type)
case let .globalAddr(name, type):
print("global_addr ")
print("@")
print(name)
print(" : ")
print(type)
case let .indexAddr(addr, index):
print("index_addr ")
print(addr)
print(", ")
print(index)
case let .integerLiteral(type, value):
print("integer_literal ")
print(type)
print(", ")
literal(value)
case let .load(maybeOwnership, operand):
print("load ")
if let ownership = maybeOwnership {
print(ownership)
print(" ")
}
print(operand)
case let .markDependence(operand, on):
print("mark_dependence ")
print(operand)
print(" on ")
print(on)
case let .metatype(type):
print("metatype ")
print(type)
case let .partialApply(calleeGuaranteed, onStack, value, substitutions, arguments, type):
print("partial_apply ")
print(when: calleeGuaranteed, "[callee_guaranteed] ")
print(when: onStack, "[on_stack] ")
print(value)
print(whenEmpty: false, "<", substitutions, ", ", ">") { naked($0) }
print("(", arguments, ", ", ")") { print($0) }
print(" : ")
print(type)
case let .pointerToAddress(operand, strict, type):
print("pointer_to_address ")
print(operand)
print(" to ")
print(when: strict, "[strict] ")
print(type)
case let .releaseValue(operand):
print("release_value ")
print(operand)
case let .retainValue(operand):
print("retain_value ")
print(operand)
case let .selectEnum(operand, cases, type):
print("select_enum ")
print(operand)
print(whenEmpty: false, "", cases, "", "") { print($0) }
print(" : ")
print(type)
case let .store(value, maybeOwnership, operand):
print("store ")
print(value)
print(" to ")
if let ownership = maybeOwnership {
print(ownership)
print(" ")
}
print(operand)
case let .stringLiteral(encoding, value):
print("string_literal ")
print(encoding)
print(" ")
literal(value)
case let .strongRelease(operand):
print("strong_release ")
print(operand)
case let .strongRetain(operand):
print("strong_retain ")
print(operand)
case let .struct(type, operands):
print("struct ")
print(type)
print(" (", operands, ", ", ")") { print($0) }
case let .structElementAddr(operand, declRef):
print("struct_element_addr ")
print(operand)
print(", ")
print(declRef)
case let .structExtract(operand, declRef):
print("struct_extract ")
print(operand)
print(", ")
print(declRef)
case let .thinToThickFunction(operand, type):
print("thin_to_thick_function ")
print(operand)
print(" to ")
print(type)
case let .tuple(elements):
print("tuple ")
print(elements)
case let .tupleExtract(operand, declRef):
print("tuple_extract ")
print(operand)
print(", ")
literal(declRef)
case let .unknown(name):
print(name)
print(" <?>")
case let .witnessMethod(archeType, declRef, declType, type):
print("witness_method ")
print(archeType)
print(", ")
print(declRef)
print(" : ")
naked(declType)
print(" : ")
print(type)
}
}
func print(_ terminator: Terminator) {
switch terminator {
case let .br(label, operands):
print("br ")
print(label)
print(whenEmpty: false, "(", operands, ", ", ")") { print($0) }
case let .condBr(cond, trueLabel, trueOperands, falseLabel, falseOperands):
print("cond_br ")
print(cond)
print(", ")
print(trueLabel)
print(whenEmpty: false, "(", trueOperands, ", ", ")") { print($0) }
print(", ")
print(falseLabel)
print(whenEmpty: false, "(", falseOperands, ", ", ")") { print($0) }
case let .return(operand):
print("return ")
print(operand)
case let .switchEnum(operand, cases):
print("switch_enum ")
print(operand)
print(whenEmpty: false, "", cases, "", "") { print($0) }
case let .unknown(name):
print(name)
print(" <?>")
case .unreachable:
print("unreachable")
}
}
// MARK: Auxiliary data structures
func print(_ access: Access) {
switch access {
case .deinit:
print("deinit")
case .`init`:
print("init")
case .modify:
print("modify")
case .read:
print("read")
}
}
func print(_ argument: Argument) {
print(argument.valueName)
print(" : ")
print(argument.type)
}
func print(_ `case`: Case) {
print(", ")
switch `case` {
case let .case(declRef, result):
print("case ")
print(declRef)
print(": ")
print(result)
case let .default(result):
print("default ")
print(result)
}
}
func print(_ convention: Convention) {
print("(")
switch convention {
case .c:
print("c")
case .method:
print("method")
case .thin:
print("thin")
case let .witnessMethod(type):
print("witness_method: ")
naked(type)
}
print(")")
}
func print(_ attribute: DebugAttribute) {
switch attribute {
case let .argno(name):
print("argno ")
literal(name)
case let .name(name):
print("name ")
literal(name)
case .let:
print("let")
case .var:
print("var")
}
}
func print(_ declKind: DeclKind) {
switch declKind {
case .allocator:
print("allocator")
case .deallocator:
print("deallocator")
case .destroyer:
print("destroyer")
case .enumElement:
print("enumelt")
case .getter:
print("getter")
case .globalAccessor:
print("globalaccessor")
case .initializer:
print("initializer")
case .ivarDestroyer:
print("ivardestroyer")
case .ivarInitializer:
print("ivarinitializer")
case .setter:
print("setter")
}
}
func print(_ declRef: DeclRef) {
print("#")
print(declRef.name.joined(separator: "."))
if let kind = declRef.kind {
print("!")
print(kind)
}
if let level = declRef.level {
print(declRef.kind == nil ? "!" : ".")
literal(level)
}
}
func print(_ encoding: Encoding) {
switch encoding {
case .objcSelector:
print("objcSelector")
case .utf8:
print("utf8")
case .utf16:
print("utf16")
}
}
func print(_ enforcement: Enforcement) {
switch enforcement {
case .dynamic:
print("dynamic")
case .static:
print("static")
case .unknown:
print("unknown")
case .unsafe:
print("unsafe")
}
}
func print(_ attribute: FunctionAttribute) {
switch attribute {
case .alwaysInline:
print("[always_inline]")
case let .differentiable(spec):
print("[differentiable ")
print(spec)
print("]")
case .dynamicallyReplacable:
print("[dynamically_replacable]")
case .noInline:
print("[noinline]")
case .noncanonical(.ownershipSSA):
print("[ossa]")
case .readonly:
print("[readonly]")
case let .semantics(value):
print("[_semantics ")
literal(value)
print("]")
case .serialized:
print("[serialized]")
case .thunk:
print("[thunk]")
case .transparent:
print("[transparent]")
}
}
func print(_ linkage: Linkage) {
switch linkage {
case .hidden:
print("hidden ")
case .hiddenExternal:
print("hidden_external ")
case .private:
print("private ")
case .privateExternal:
print("private_external ")
case .public:
print("")
case .publicExternal:
print("public_external ")
case .publicNonABI:
print("non_abi ")
case .shared:
print("shared ")
case .sharedExternal:
print("shared_external ")
}
}
func print(_ loc: Loc) {
print("loc ")
literal(loc.path)
print(":")
literal(loc.line)
print(":")
literal(loc.column)
}
func print(_ operand: Operand) {
print(operand.value)
print(" : ")
print(operand.type)
}
func print(_ result: Result) {
if result.valueNames.count == 1 {
print(result.valueNames[0])
} else {
print("(", result.valueNames, ", ", ")") { print($0) }
}
}
func print(_ sourceInfo: SourceInfo) {
// NB: The SIL docs say that scope refs precede locations, but this is
// not true once you look at the compiler outputs or its source code.
print(", ", sourceInfo.loc) { print($0) }
print(", scope ", sourceInfo.scopeRef) { print($0) }
}
func print(_ elements: TupleElements) {
switch elements {
case let .labeled(type, values):
print(type)
print(" (", values, ", ", ")") { print($0) }
case let .unlabeled(operands):
print("(", operands, ", ", ")") { print($0) }
}
}
func print(_ type: Type) {
if case let .withOwnership(attr, subtype) = type {
print(attr)
print(" ")
print(subtype)
} else {
print("$")
naked(type)
}
}
func naked(_ type: Type) {
switch type {
case let .addressType(type):
print("*")
naked(type)
case let .attributedType(attrs, type):
print("", attrs, " ", " ") { print($0) }
naked(type)
case .coroutineTokenType:
print("!CoroutineTokenType!")
case let .functionType(params, result):
print("(", params, ", ", ")") { naked($0) }
print(" -> ")
naked(result)
case let .genericType(params, reqs, type):
print("<", params, ", ", "") { print($0) }
print(whenEmpty: false, " where ", reqs, ", ", "") { print($0) }
print(">")
// This is a weird corner case of -emit-sil, so we have to go the extra mile.
if case .genericType = type {
naked(type)
} else {
print(" ")
naked(type)
}
case let .namedType(name):
print(name)
case let .selectType(type, name):
naked(type)
print(".")
print(name)
case .selfType:
print("Self")
case let .specializedType(type, args):
naked(type)
print("<", args, ", ", ">") { naked($0) }
case let .tupleType(params):
print("(", params, ", ", ")") { naked($0) }
case .withOwnership(_, _):
fatalError("Types with ownership should be printed before naked type print!")
}
}
func print(_ attribute: TypeAttribute) {
switch attribute {
case .calleeGuaranteed:
print("@callee_guaranteed")
case let .convention(convention):
print("@convention")
print(convention)
case .guaranteed:
print("@guaranteed")
case .inGuaranteed:
print("@in_guaranteed")
case .in:
print("@in")
case .inout:
print("@inout")
case .noescape:
print("@noescape")
case .out:
print("@out")
case .owned:
print("@owned")
case .thick:
print("@thick")
case .thin:
print("@thin")
case .yieldOnce:
print("@yield_once")
case .yields:
print("@yields")
}
}
func print(_ requirement: TypeRequirement) {
switch requirement {
case let .conformance(lhs, rhs):
naked(lhs)
print(" : ")
naked(rhs)
case let .equality(lhs, rhs):
naked(lhs)
print(" == ")
naked(rhs)
}
}
func print(_ ownership: LoadOwnership) {
switch ownership {
case .copy: print("[copy]")
case .take: print("[take]")
case .trivial: print("[trivial]")
}
}
func print(_ ownership: StoreOwnership) {
switch ownership {
case .`init`: print("[init]")
case .trivial: print("[trivial]")
}
}
}
extension Module: CustomStringConvertible {
public var description: String {
let p = SILPrinter()
p.print(self)
return p.description
}
}
extension Function: CustomStringConvertible {
public var description: String {
let p = SILPrinter()
p.print(self)
return p.description
}
}
extension Block: CustomStringConvertible {
public var description: String {
let p = SILPrinter()
p.print(self)
return p.description
}
}
extension OperatorDef: CustomStringConvertible {
public var description: String {
let p = SILPrinter()
p.print(self)
return p.description
}
}
extension TerminatorDef: CustomStringConvertible {
public var description: String {
let p = SILPrinter()
p.print(self)
return p.description
}
}
extension InstructionDef: CustomStringConvertible {
public var description: String {
switch self {
case let .operator(def): return def.description
case let .terminator(def): return def.description
}
}
}
extension Operator: CustomStringConvertible {
public var description: String {
let p = SILPrinter()
p.print(self)
return p.description
}
}
extension Terminator: CustomStringConvertible {
public var description: String {
let p = SILPrinter()
p.print(self)
return p.description
}
}
extension Instruction: CustomStringConvertible {
public var description: String {
switch self {
case let .operator(def): return def.description
case let .terminator(def): return def.description
}
}
}
| apache-2.0 |
cnoon/swift-compiler-crashes | crashes-duplicates/13282-swift-sourcemanager-getmessage.swift | 11 | 222 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
enum A {
deinit {
init
{
let NSObject {
class
case ,
| mit |
kripple/bti-watson | ios-app/Carthage/Checkouts/AlamofireObjectMapper/Carthage/Checkouts/ObjectMapper/Carthage/Checkouts/Nimble/Nimble/Matchers/BeGreaterThan.swift | 189 | 1567 | import Foundation
/// A Nimble matcher that succeeds when the actual value is greater than the expected value.
public func beGreaterThan<T: Comparable>(expectedValue: T?) -> NonNilMatcherFunc<T> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be greater than <\(stringify(expectedValue))>"
return try actualExpression.evaluate() > expectedValue
}
}
/// A Nimble matcher that succeeds when the actual value is greater than the expected value.
public func beGreaterThan(expectedValue: NMBComparable?) -> NonNilMatcherFunc<NMBComparable> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be greater than <\(stringify(expectedValue))>"
let actualValue = try actualExpression.evaluate()
let matches = actualValue != nil && actualValue!.NMB_compare(expectedValue) == NSComparisonResult.OrderedDescending
return matches
}
}
public func ><T: Comparable>(lhs: Expectation<T>, rhs: T) {
lhs.to(beGreaterThan(rhs))
}
public func >(lhs: Expectation<NMBComparable>, rhs: NMBComparable?) {
lhs.to(beGreaterThan(rhs))
}
extension NMBObjCMatcher {
public class func beGreaterThanMatcher(expected: NMBComparable?) -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
let expr = actualExpression.cast { $0 as? NMBComparable }
return try! beGreaterThan(expected).matches(expr, failureMessage: failureMessage)
}
}
}
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/08837-swift-sourcemanager-getmessage.swift | 11 | 259 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
extension NSSet {
func d {
var b (
let {
protocol B {
{
}
class a
{
deinit {
class
case ,
| mit |
masters3d/xswift | exercises/word-count/Sources/WordCountExample.swift | 1 | 970 | struct WordCount {
func splitStringToArray(_ inString: String) -> [String] {
return inString.characters.split(whereSeparator: { splitAt($0) }).map { String($0) }
}
func splitAt(_ characterToCompare: Character, charToSplitAt: String = " !&$%^&,:") -> Bool {
for each in charToSplitAt.characters {
if each == characterToCompare {
return true
}
}
return false
}
let words: String
init(words: String) {
self.words = words
}
func count() -> [String: Int] {
var dict = [String: Int]()
let cleanArray = splitStringToArray(words)
cleanArray.forEach { string in
if !string.isEmpty {
if let count = dict[string.lowercased()] {
dict[string.lowercased()] = count + 1
} else { dict[string.lowercased()] = 1
}
}
}
return dict
}
}
| mit |
tlax/looper | looper/View/Main/Subclasses/VSpinner.swift | 1 | 1037 | import UIKit
class VSpinner:UIImageView
{
private let kAnimationDuration:TimeInterval = 1
init()
{
super.init(frame:CGRect.zero)
let images:[UIImage] = [
#imageLiteral(resourceName: "assetSpinner0"),
#imageLiteral(resourceName: "assetSpinner1"),
#imageLiteral(resourceName: "assetSpinner2"),
#imageLiteral(resourceName: "assetSpinner3"),
#imageLiteral(resourceName: "assetSpinner4"),
#imageLiteral(resourceName: "assetSpinner5"),
#imageLiteral(resourceName: "assetSpinner6"),
#imageLiteral(resourceName: "assetSpinner7")
]
isUserInteractionEnabled = false
translatesAutoresizingMaskIntoConstraints = false
clipsToBounds = true
animationDuration = kAnimationDuration
animationImages = images
contentMode = UIViewContentMode.center
startAnimating()
}
required init?(coder:NSCoder)
{
return nil
}
}
| mit |
mobilabsolutions/jenkins-ios | JenkinsiOS/Model/JenkinsAPI/Job/Job+DescribingColor.swift | 1 | 1271 | //
// Created by Robert on 27.06.17.
// Copyright (c) 2017 MobiLab Solutions. All rights reserved.
//
import UIKit
extension Job: DescribingColor {
func describingColor() -> UIColor {
guard let color = self.color
else { return .clear }
switch color {
case .aborted: fallthrough
case .abortedAnimated:
return UIColor(red: 159 / 255, green: 159 / 255, blue: 159 / 255, alpha: 1.0)
case .blue: fallthrough
case .blueAnimated:
return UIColor(red: 22 / 255, green: 91 / 255, blue: 244 / 255, alpha: 1.0)
case .red: fallthrough
case .redAnimated:
return UIColor(red: 238 / 255, green: 0, blue: 0, alpha: 1.0)
case .disabled: fallthrough
case .disabledAnimated:
return UIColor(red: 82 / 255, green: 81 / 255, blue: 82 / 255, alpha: 1.0)
case .folder:
return UIColor.blue.withAlphaComponent(0.5)
case .notBuilt: fallthrough
case .notBuiltAnimated:
return UIColor(red: 237 / 255, green: 160 / 255, blue: 0, alpha: 1.0)
case .yellow: fallthrough
case .yellowAnimated:
return UIColor(red: 255 / 255, green: 222 / 255, blue: 44 / 255, alpha: 1.0)
}
}
}
| mit |
tardieu/swift | test/Interpreter/complex.swift | 66 | 610 | // RUN: %target-typecheck-verify-swift
public struct Complex {
public var real = 0.0, imag = 0.0
public func magnitude() -> Double {
return real * real + imag * imag
}
public init() {}
public init(real: Double, imag: Double) {
self.real = real
self.imag = imag
}
}
public func * (lhs: Complex, rhs: Complex) -> Complex {
return Complex(real: lhs.real * rhs.real - lhs.imag * rhs.imag,
imag: lhs.real * rhs.imag + lhs.imag * rhs.real)
}
public func + (lhs: Complex, rhs: Complex) -> Complex {
return Complex(real: lhs.real + rhs.real, imag: lhs.imag + rhs.imag)
}
| apache-2.0 |
Solar1011/- | 我的微博/我的微博/Classes/Module/Home/StatusCell/StatusNormalCell.swift | 1 | 787 | //
// StatusNormalCell.swift
// 我的微博
//
// Created by teacher on 15/8/2.
// Copyright © 2015年 itheima. All rights reserved.
//
import UIKit
/// 原创微博
class StatusNormalCell: StatusCell {
override func setupUI() {
super.setupUI()
// 3> 配图视图
let cons = pictureView.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: contentLabel, size: CGSize(width: 290, height: 290), offset: CGPoint(x: 0, y: statusCellControlMargin))
pictureWidthCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Width)
pictureHeightCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)
pictureTopCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Top)
}
}
| mit |
obitow/hackerrank-swift | HackerRankTests/Warmup/DiagonalDifferenceTests.swift | 1 | 442 | /// Practice / Algorithms / Warmup / Diagonal Difference
/// https://www.hackerrank.com/challenges/diagonal-difference
import XCTest
import HackerRank
class DiagonalDifferenceTests: XCTestCase {
func test00() {
let result = diagonalDifference(arr: [[11, 2, 4],
[ 4, 5, 6],
[10, 8, -12]])
XCTAssertEqual(result, 15)
}
}
| mit |
xusader/firefox-ios | Client/Frontend/Reader/ReaderModeStyleViewController.swift | 3 | 14656 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
private struct ReaderModeStyleViewControllerUX {
static let RowHeight = 50
static let Width = 270
static let Height = 4 * RowHeight
static let FontTypeRowBackground = UIColor(rgb: 0xfbfbfb)
static let FontTypeTitleFontSansSerif = UIFont(name: "FiraSans", size: 16)
static let FontTypeTitleFontSerif = UIFont(name: "Charis SIL", size: 16)
static let FontTypeTitleSelectedColor = UIColor(rgb: 0x333333)
static let FontTypeTitleNormalColor = UIColor.lightGrayColor() // TODO THis needs to be 44% of 0x333333
static let FontSizeRowBackground = UIColor(rgb: 0xf4f4f4)
static let FontSizeLabelFontSansSerif = UIFont(name: "FiraSans-Book", size: 22)
static let FontSizeLabelFontSerif = UIFont(name: "Charis SIL", size: 22)
static let FontSizeLabelColor = UIColor(rgb: 0x333333)
static let FontSizeButtonTextColorEnabled = UIColor(rgb: 0x333333)
static let FontSizeButtonTextColorDisabled = UIColor.lightGrayColor() // TODO THis needs to be 44% of 0x333333
static let FontSizeButtonTextFont = UIFont(name: "FiraSans-Book", size: 22)
static let ThemeRowBackgroundColor = UIColor.whiteColor()
static let ThemeTitleFontSansSerif = UIFont(name: "FiraSans-Light", size: 15)
static let ThemeTitleFontSerif = UIFont(name: "Charis SIL", size: 15)
static let ThemeTitleColorLight = UIColor(rgb: 0x333333)
static let ThemeTitleColorDark = UIColor.whiteColor()
static let ThemeTitleColorSepia = UIColor(rgb: 0x333333)
static let ThemeBackgroundColorLight = UIColor.whiteColor()
static let ThemeBackgroundColorDark = UIColor.blackColor()
static let ThemeBackgroundColorSepia = UIColor(rgb: 0xf0ece7)
static let BrightnessRowBackground = UIColor(rgb: 0xf4f4f4)
static let BrightnessSliderTintColor = UIColor(rgb: 0xe66000)
static let BrightnessSliderWidth = 140
static let BrightnessIconOffset = 10
}
// MARK: -
protocol ReaderModeStyleViewControllerDelegate {
func readerModeStyleViewController(readerModeStyleViewController: ReaderModeStyleViewController, didConfigureStyle style: ReaderModeStyle)
}
// MARK: -
class ReaderModeStyleViewController: UIViewController {
var delegate: ReaderModeStyleViewControllerDelegate?
var readerModeStyle: ReaderModeStyle = DefaultReaderModeStyle
private var fontTypeButtons: [FontTypeButton]!
private var fontSizeLabel: FontSizeLabel!
private var fontSizeButtons: [FontSizeButton]!
private var themeButtons: [ThemeButton]!
override func viewDidLoad() {
// Our preferred content size has a fixed width and height based on the rows + padding
preferredContentSize = CGSize(width: ReaderModeStyleViewControllerUX.Width, height: ReaderModeStyleViewControllerUX.Height)
popoverPresentationController?.backgroundColor = ReaderModeStyleViewControllerUX.FontTypeRowBackground
// Font type row
let fontTypeRow = UIView()
view.addSubview(fontTypeRow)
fontTypeRow.backgroundColor = ReaderModeStyleViewControllerUX.FontTypeRowBackground
fontTypeRow.snp_makeConstraints { (make) -> () in
make.top.equalTo(self.view)
make.left.right.equalTo(self.view)
make.height.equalTo(ReaderModeStyleViewControllerUX.RowHeight)
}
fontTypeButtons = [
FontTypeButton(fontType: ReaderModeFontType.SansSerif),
FontTypeButton(fontType: ReaderModeFontType.Serif)
]
setupButtons(fontTypeButtons, inRow: fontTypeRow, action: "SELchangeFontType:")
// Font size row
let fontSizeRow = UIView()
view.addSubview(fontSizeRow)
fontSizeRow.backgroundColor = ReaderModeStyleViewControllerUX.FontSizeRowBackground
fontSizeRow.snp_makeConstraints { (make) -> () in
make.top.equalTo(fontTypeRow.snp_bottom)
make.left.right.equalTo(self.view)
make.height.equalTo(ReaderModeStyleViewControllerUX.RowHeight)
}
fontSizeLabel = FontSizeLabel()
fontSizeRow.addSubview(fontSizeLabel)
fontSizeLabel.snp_makeConstraints { (make) -> () in
make.center.equalTo(fontSizeRow)
return
}
fontSizeButtons = [
FontSizeButton(fontSizeAction: FontSizeAction.Smaller),
FontSizeButton(fontSizeAction: FontSizeAction.Bigger)
]
setupButtons(fontSizeButtons, inRow: fontSizeRow, action: "SELchangeFontSize:")
// Theme row
let themeRow = UIView()
view.addSubview(themeRow)
themeRow.snp_makeConstraints { (make) -> () in
make.top.equalTo(fontSizeRow.snp_bottom)
make.left.right.equalTo(self.view)
make.height.equalTo(ReaderModeStyleViewControllerUX.RowHeight)
}
themeButtons = [
ThemeButton(theme: ReaderModeTheme.Light),
ThemeButton(theme: ReaderModeTheme.Dark),
ThemeButton(theme: ReaderModeTheme.Sepia)
]
setupButtons(themeButtons, inRow: themeRow, action: "SELchangeTheme:")
// Brightness row
let brightnessRow = UIView()
view.addSubview(brightnessRow)
brightnessRow.backgroundColor = ReaderModeStyleViewControllerUX.BrightnessRowBackground
brightnessRow.snp_makeConstraints { (make) -> () in
make.top.equalTo(themeRow.snp_bottom)
make.left.right.equalTo(self.view)
make.height.equalTo(ReaderModeStyleViewControllerUX.RowHeight)
}
let slider = UISlider()
brightnessRow.addSubview(slider)
slider.tintColor = ReaderModeStyleViewControllerUX.BrightnessSliderTintColor
slider.addTarget(self, action: "SELchangeBrightness:", forControlEvents: UIControlEvents.ValueChanged)
slider.snp_makeConstraints { make in
make.center.equalTo(brightnessRow.center)
make.width.equalTo(ReaderModeStyleViewControllerUX.BrightnessSliderWidth)
}
let brightnessMinImageView = UIImageView(image: UIImage(named: "brightnessMin"))
brightnessRow.addSubview(brightnessMinImageView)
brightnessMinImageView.snp_makeConstraints { (make) -> () in
make.centerY.equalTo(slider)
make.right.equalTo(slider.snp_left).offset(-ReaderModeStyleViewControllerUX.BrightnessIconOffset)
}
let brightnessMaxImageView = UIImageView(image: UIImage(named: "brightnessMax"))
brightnessRow.addSubview(brightnessMaxImageView)
brightnessMaxImageView.snp_makeConstraints { (make) -> () in
make.centerY.equalTo(slider)
make.left.equalTo(slider.snp_right).offset(ReaderModeStyleViewControllerUX.BrightnessIconOffset)
}
selectFontType(readerModeStyle.fontType)
updateFontSizeButtons()
selectTheme(readerModeStyle.theme)
slider.value = Float(UIScreen.mainScreen().brightness)
}
/// Setup constraints for a row of buttons. Left to right. They are all given the same width.
private func setupButtons(buttons: [UIButton], inRow row: UIView, action: Selector) {
for (idx, button) in enumerate(buttons) {
row.addSubview(button)
button.addTarget(self, action: action, forControlEvents: UIControlEvents.TouchUpInside)
button.snp_makeConstraints { make in
make.top.equalTo(row.snp_top)
if idx == 0 {
make.left.equalTo(row.snp_left)
} else {
make.left.equalTo(buttons[idx - 1].snp_right)
}
make.bottom.equalTo(row.snp_bottom)
make.width.equalTo(self.preferredContentSize.width / CGFloat(buttons.count))
}
}
}
func SELchangeFontType(button: FontTypeButton) {
selectFontType(button.fontType)
delegate?.readerModeStyleViewController(self, didConfigureStyle: readerModeStyle)
}
private func selectFontType(fontType: ReaderModeFontType) {
readerModeStyle.fontType = fontType
for button in fontTypeButtons {
button.selected = (button.fontType == fontType)
}
for button in themeButtons {
button.fontType = fontType
}
fontSizeLabel.fontType = fontType
}
func SELchangeFontSize(button: FontSizeButton) {
switch button.fontSizeAction {
case .Smaller:
readerModeStyle.fontSize = readerModeStyle.fontSize.smaller()
case .Bigger:
readerModeStyle.fontSize = readerModeStyle.fontSize.bigger()
}
updateFontSizeButtons()
delegate?.readerModeStyleViewController(self, didConfigureStyle: readerModeStyle)
}
private func updateFontSizeButtons() {
for button in fontSizeButtons {
switch button.fontSizeAction {
case .Bigger:
button.enabled = !readerModeStyle.fontSize.isLargest()
break
case .Smaller:
button.enabled = !readerModeStyle.fontSize.isSmallest()
break
}
}
}
func SELchangeTheme(button: ThemeButton) {
selectTheme(button.theme)
delegate?.readerModeStyleViewController(self, didConfigureStyle: readerModeStyle)
}
private func selectTheme(theme: ReaderModeTheme) {
readerModeStyle.theme = theme
}
func SELchangeBrightness(slider: UISlider) {
UIScreen.mainScreen().brightness = CGFloat(slider.value)
}
}
// MARK: -
class FontTypeButton: UIButton {
var fontType: ReaderModeFontType = .SansSerif
convenience init(fontType: ReaderModeFontType) {
self.init(frame: CGRectZero)
self.fontType = fontType
setTitleColor(ReaderModeStyleViewControllerUX.FontTypeTitleSelectedColor, forState: UIControlState.Selected)
setTitleColor(ReaderModeStyleViewControllerUX.FontTypeTitleNormalColor, forState: UIControlState.Normal)
backgroundColor = ReaderModeStyleViewControllerUX.FontTypeRowBackground
switch fontType {
case .SansSerif:
setTitle(NSLocalizedString("Sans-serif", comment: "Font type setting in the reading view settings"), forState: UIControlState.Normal)
let f = ReaderModeStyleViewControllerUX.ThemeTitleFontSansSerif
titleLabel?.font = f
case .Serif:
setTitle(NSLocalizedString("Serif", comment: "Font type setting in the reading view settings"), forState: UIControlState.Normal)
let f = ReaderModeStyleViewControllerUX.ThemeTitleFontSerif
titleLabel?.font = f
}
}
}
// MARK: -
enum FontSizeAction {
case Smaller
case Bigger
}
class FontSizeButton: UIButton {
var fontSizeAction: FontSizeAction = .Bigger
convenience init(fontSizeAction: FontSizeAction) {
self.init(frame: CGRectZero)
self.fontSizeAction = fontSizeAction
setTitleColor(ReaderModeStyleViewControllerUX.FontSizeButtonTextColorEnabled, forState: UIControlState.Normal)
setTitleColor(ReaderModeStyleViewControllerUX.FontSizeButtonTextColorDisabled, forState: UIControlState.Disabled)
switch fontSizeAction {
case .Smaller:
let smallerFontLabel = NSLocalizedString("-", comment: "Button for smaller reader font size. Keep this extremely short! This is shown in the reader mode toolbar.")
setTitle(smallerFontLabel, forState: .Normal)
case .Bigger:
let largerFontLabel = NSLocalizedString("+", comment: "Button for larger reader font size. Keep this extremely short! This is shown in the reader mode toolbar.")
setTitle(largerFontLabel, forState: .Normal)
}
// TODO Does this need to change with the selected font type? Not sure if makes sense for just +/-
titleLabel?.font = ReaderModeStyleViewControllerUX.FontSizeButtonTextFont
}
}
// MARK: -
class FontSizeLabel: UILabel {
override init(frame: CGRect) {
super.init(frame: frame)
let fontSizeLabel = NSLocalizedString("Aa", comment: "Button for reader mode font size. Keep this extremely short! This is shown in the reader mode toolbar.")
text = fontSizeLabel
}
required init(coder aDecoder: NSCoder) {
// TODO
fatalError("init(coder:) has not been implemented")
}
var fontType: ReaderModeFontType = .SansSerif {
didSet {
switch fontType {
case .SansSerif:
font = ReaderModeStyleViewControllerUX.FontSizeLabelFontSansSerif
case .Serif:
font = ReaderModeStyleViewControllerUX.FontSizeLabelFontSerif
}
}
}
}
// MARK: -
class ThemeButton: UIButton {
var theme: ReaderModeTheme!
convenience init(theme: ReaderModeTheme) {
self.init(frame: CGRectZero)
self.theme = theme
setTitle(theme.rawValue, forState: UIControlState.Normal)
switch theme {
case .Light:
setTitle(NSLocalizedString("Light", comment: "Light theme setting in Reading View settings"), forState: .Normal)
setTitleColor(ReaderModeStyleViewControllerUX.ThemeTitleColorLight, forState: UIControlState.Normal)
backgroundColor = ReaderModeStyleViewControllerUX.ThemeBackgroundColorLight
case .Dark:
setTitle(NSLocalizedString("Dark", comment: "Dark theme setting in Reading View settings"), forState: .Normal)
setTitleColor(ReaderModeStyleViewControllerUX.ThemeTitleColorDark, forState: UIControlState.Normal)
backgroundColor = ReaderModeStyleViewControllerUX.ThemeBackgroundColorDark
case .Sepia:
setTitle(NSLocalizedString("Sepia", comment: "Sepia theme setting in Reading View settings"), forState: .Normal)
setTitleColor(ReaderModeStyleViewControllerUX.ThemeTitleColorSepia, forState: UIControlState.Normal)
backgroundColor = ReaderModeStyleViewControllerUX.ThemeBackgroundColorSepia
}
}
var fontType: ReaderModeFontType = .SansSerif {
didSet {
switch fontType {
case .SansSerif:
titleLabel?.font = ReaderModeStyleViewControllerUX.ThemeTitleFontSansSerif
case .Serif:
titleLabel?.font = ReaderModeStyleViewControllerUX.ThemeTitleFontSerif
}
}
}
} | mpl-2.0 |
OscarSwanros/swift | test/DebugInfo/test-foundation.swift | 4 | 3190 | // RUN: %target-swift-frontend -emit-ir -g %s -o %t.ll
// RUN: %FileCheck %s --check-prefix IMPORT-CHECK < %t.ll
// RUN: %FileCheck %s --check-prefix LOC-CHECK < %t.ll
// RUN: llc %t.ll -filetype=obj -o %t.o
// RUN: %llvm-dwarfdump %t.o | %FileCheck %s --check-prefix DWARF-CHECK
// DISABLED <rdar://problem/28232630>: %llvm-dwarfdump --verify %t.o
// REQUIRES: OS=macosx
import ObjectiveC
import Foundation
class MyObject : NSObject {
// Ensure we don't emit linetable entries for ObjC thunks.
// LOC-CHECK: define {{.*}} @_T04main8MyObjectC0B3ArrSo7NSArrayCvgTo
// LOC-CHECK: ret {{.*}}, !dbg ![[DBG:.*]]
// LOC-CHECK: ret
var MyArr = NSArray()
// IMPORT-CHECK: filename: "test-foundation.swift"
// IMPORT-CHECK-DAG: [[FOUNDATION:[0-9]+]] = !DIModule({{.*}} name: "Foundation",{{.*}} includePath:
// IMPORT-CHECK-DAG: !DICompositeType(tag: DW_TAG_structure_type, name: "NSArray", scope: ![[NSARRAY:[0-9]+]]
// IMPORT-CHECK-DAG: ![[NSARRAY]] = !DIModule(scope: ![[FOUNDATION:[0-9]+]], name: "NSArray"
// IMPORT-CHECK-DAG: !DIImportedEntity(tag: DW_TAG_imported_module, {{.*}}entity: ![[FOUNDATION]]
func foo(_ obj: MyObject) {
return obj.foo(obj)
}
}
// SANITY-DAG: !DISubprogram(name: "blah",{{.*}} line: [[@LINE+2]],{{.*}} isDefinition: true
extension MyObject {
func blah() {
var _ = MyObject()
}
}
// SANITY-DAG: ![[NSOBJECT:.*]] = !DICompositeType(tag: DW_TAG_structure_type, name: "NSObject",{{.*}} identifier: "_T0So8NSObjectC"
// SANITY-DAG: !DIGlobalVariable(name: "NsObj",{{.*}} line: [[@LINE+1]],{{.*}} type: ![[NSOBJECT]],{{.*}} isDefinition: true
var NsObj: NSObject
NsObj = MyObject()
var MyObj: MyObject
MyObj = NsObj as! MyObject
MyObj.blah()
public func err() {
// DWARF-CHECK: DW_AT_name ("NSError")
// DWARF-CHECK: DW_AT_linkage_name{{.*}}_T0So7NSErrorC
let _ = NSError(domain: "myDomain", code: 4,
userInfo: [AnyHashable("a"):1,
AnyHashable("b"):2,
AnyHashable("c"):3])
}
// LOC-CHECK: define {{.*}}4date
public func date() {
// LOC-CHECK: call {{.*}} @_T0S2SBp21_builtinStringLiteral_Bw17utf8CodeUnitCountBi1_7isASCIItcfC{{.*}}, !dbg ![[L1:.*]]
let d1 = DateFormatter()
d1.dateFormat = "dd. mm. yyyy" // LOC-CHECK: call{{.*}}objc_msgSend{{.*}}, !dbg ![[L2:.*]]
// LOC-CHECK: call {{.*}} @_T0S2SBp21_builtinStringLiteral_Bw17utf8CodeUnitCountBi1_7isASCIItcfC{{.*}}, !dbg ![[L3:.*]]
let d2 = DateFormatter()
d2.dateFormat = "mm dd yyyy" // LOC-CHECK: call{{.*}}objc_msgSend{{.*}}, !dbg ![[L4:.*]]
}
// Make sure we build some witness tables for enums.
func useOptions(_ opt: URL.BookmarkCreationOptions)
-> URL.BookmarkCreationOptions {
return [opt, opt]
}
// LOC-CHECK: ![[THUNK:.*]] = distinct !DISubprogram({{.*}}linkageName: "_T04main8MyObjectC0B3ArrSo7NSArrayCvgTo"
// LOC-CHECK-NOT: line:
// LOC-CHECK-SAME: isDefinition: true
// LOC-CHECK: ![[DBG]] = !DILocation(line: 0, scope: ![[THUNK]])
// These debug locations should all be in ordered by increasing line number.
// LOC-CHECK: ![[L1]] =
// LOC-CHECK: ![[L2]] =
// LOC-CHECK: ![[L3]] =
// LOC-CHECK: ![[L4]] =
| apache-2.0 |
openHPI/xikolo-ios | iOS/ViewControllers/Courses/CourseItemViewController.swift | 1 | 12436 | //
// Created for xikolo-ios under GPL-3.0 license.
// Copyright © HPI. All rights reserved.
//
import BrightFutures
import Common
import UIKit
import CoreData
class CourseItemViewController: UIPageViewController {
private lazy var progressLabel: UILabel = {
let label = UILabel()
label.font = UIFont.boldSystemFont(ofSize: UIFont.smallSystemFontSize)
return label
}()
private lazy var previousItemButton: UIButton = {
let button = UIButton(type: .custom)
button.setImage(R.image.chevronRight(), for: .normal)
button.addTarget(self, action: #selector(showPreviousItem), for: .touchUpInside)
button.imageView?.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
button.imageView?.contentMode = .scaleAspectFit
button.imageEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
button.contentVerticalAlignment = .fill
button.contentHorizontalAlignment = .fill
button.translatesAutoresizingMaskIntoConstraints = false
button.isHidden = true
return button
}()
private lazy var nextItemButton: UIButton = {
let button = UIButton(type: .custom)
button.setImage(R.image.chevronRight(), for: .normal)
button.addTarget(self, action: #selector(showNextItem), for: .touchUpInside)
button.imageView?.contentMode = .scaleAspectFit
button.imageEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
button.contentVerticalAlignment = .fill
button.contentHorizontalAlignment = .fill
button.translatesAutoresizingMaskIntoConstraints = false
button.isHidden = true
return button
}()
private var previousItem: CourseItem?
private var nextItem: CourseItem?
var currentItem: CourseItem? {
didSet {
self.trackItemVisit()
ErrorManager.shared.remember(self.currentItem?.id as Any, forKey: "item_id")
self.previousItem = self.currentItem?.previousItem
self.nextItem = self.currentItem?.nextItem
self.navigationItem.rightBarButtonItem = self.generateActionMenuButton()
guard self.view.window != nil else { return }
self.updateProgressLabel()
self.updatePreviousAndNextItemButtons()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
self.delegate = self
self.navigationItem.rightBarButtonItem = self.generateActionMenuButton()
self.view.backgroundColor = ColorCompatibility.systemBackground
self.navigationItem.titleView = self.progressLabel
guard let item = self.currentItem else { return }
guard let newViewController = self.viewController(for: item) else { return }
self.setViewControllers([newViewController], direction: .forward, animated: false)
self.view.addSubview(self.previousItemButton)
self.view.addSubview(self.nextItemButton)
NSLayoutConstraint.activate([
self.previousItemButton.leadingAnchor.constraint(equalTo: self.view.layoutMarginsGuide.leadingAnchor),
NSLayoutConstraint(item: self.previousItemButton,
attribute: .centerY,
relatedBy: .equal,
toItem: self.view.layoutMarginsGuide,
attribute: .centerY,
multiplier: 1.0,
constant: -32),
self.previousItemButton.widthAnchor.constraint(equalToConstant: 44),
self.previousItemButton.heightAnchor.constraint(equalToConstant: 44),
self.nextItemButton.trailingAnchor.constraint(equalTo: self.view.layoutMarginsGuide.trailingAnchor),
NSLayoutConstraint(item: self.nextItemButton,
attribute: .centerY,
relatedBy: .equal,
toItem: self.view.layoutMarginsGuide,
attribute: .centerY,
multiplier: 1.0,
constant: -32),
self.nextItemButton.widthAnchor.constraint(equalToConstant: 44),
self.nextItemButton.heightAnchor.constraint(equalToConstant: 44),
])
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.updatePreviousAndNextItemButtons()
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate { _ in
self.updatePreviousAndNextItemButtons()
}
}
func reload(animated: Bool) {
guard let item = self.currentItem else { return }
guard let newViewController = self.viewController(for: item) else { return }
self.setViewControllers([newViewController], direction: .forward, animated: animated)
}
private func viewController(for item: CourseItem) -> CourseItemContentViewController? {
guard !item.isProctoredInProctoredCourse else {
let viewController = R.storyboard.courseLearningsProctored.instantiateInitialViewController()
viewController?.configure(for: item)
return viewController
}
guard item.hasAvailableContent else {
let viewController = R.storyboard.courseLearningsUnavailable.instantiateInitialViewController()
viewController?.configure(for: item)
viewController?.delegate = self
return viewController
}
let viewController: CourseItemContentViewController? = {
switch item.contentType {
case "video":
return R.storyboard.courseLearningsVideo.instantiateInitialViewController()
case "rich_text":
return R.storyboard.courseLearningsRichtext.instantiateInitialViewController()
case "lti_exercise":
return R.storyboard.courseLearningsLTI.instantiateInitialViewController()
case "peer_assessment":
return R.storyboard.courseLearningsPeerAssessment.instantiateInitialViewController()
default:
return R.storyboard.courseLearningsWeb.instantiateInitialViewController()
}
}()
viewController?.configure(for: item)
return viewController
}
@objc private func showPreviousItem() {
guard let item = self.previousItem else { return }
guard let newViewController = self.viewController(for: item) else { return }
self.setViewControllers([newViewController], direction: .reverse, animated: true) { completed in
guard completed else { return }
self.currentItem = item
}
}
@objc private func showNextItem() {
guard let item = self.nextItem else { return }
guard let newViewController = self.viewController(for: item) else { return }
self.setViewControllers([newViewController], direction: .forward, animated: true) { completed in
guard completed else { return }
self.currentItem = item
}
}
private func trackItemVisit() {
guard let item = self.currentItem else { return }
guard !item.isProctoredInProctoredCourse else { return }
guard item.hasAvailableContent else { return }
CourseItemHelper.markAsVisited(item)
LastVisitHelper.recordVisit(for: item)
let context = [
"content_type": item.contentType,
"section_id": item.section?.id,
"course_id": item.section?.course?.id,
]
TrackingHelper.createEvent(.visitedItem, resourceType: .item, resourceId: item.id, on: self, context: context)
}
private func generateActionMenuButton() -> UIBarButtonItem {
var menuActions: [[Action]] = []
if let video = self.currentItem?.content as? Video {
menuActions += [video.actions]
}
menuActions.append([
self.currentItem?.shareAction { [weak self] in self?.shareCourseItem() },
self.currentItem?.openHelpdesk { [weak self] in self?.openHelpdesk() },
].compactMap { $0 })
let button = UIBarButtonItem.circularItem(
with: R.image.navigationBarIcons.dots(),
target: self,
menuActions: menuActions
)
button.isEnabled = true
button.accessibilityLabel = NSLocalizedString(
"accessibility-label.course-item.navigation-bar.item.actions",
comment: "Accessibility label for actions button in navigation bar of the course item view"
)
return button
}
private func updateProgressLabel() {
if let item = self.currentItem, let section = item.section {
let sortedCourseItems = section.items.sorted(by: \.position)
if let index = sortedCourseItems.firstIndex(of: item) {
self.progressLabel.text = "\(index + 1) / \(section.items.count)"
self.progressLabel.sizeToFit()
} else {
self.progressLabel.text = "- / \(section.items.count)"
self.progressLabel.sizeToFit()
}
} else {
self.progressLabel.text = nil
}
}
func updatePreviousAndNextItemButtons() {
let enoughSpaceForButtons: Bool = {
let insets = NSDirectionalEdgeInsets.readableContentInsets(for: self)
return insets.leading >= 84
}()
let childViewControllerIsFullScreen: Bool = {
guard let videoViewController = self.viewControllers?.first as? VideoViewController else { return false }
return videoViewController.videoIsShownInFullScreen
}()
self.previousItemButton.isHidden = !enoughSpaceForButtons || childViewControllerIsFullScreen || self.previousItem == nil
self.nextItemButton.isHidden = !enoughSpaceForButtons || childViewControllerIsFullScreen || self.nextItem == nil
}
private func shareCourseItem() {
guard let item = self.currentItem else { return }
let activityViewController = UIActivityViewController(activityItems: [item], applicationActivities: nil)
activityViewController.popoverPresentationController?.barButtonItem = self.navigationItem.rightBarButtonItem
self.present(activityViewController, animated: trueUnlessReduceMotionEnabled)
}
private func openHelpdesk() {
let helpdeskViewController = R.storyboard.tabAccount.helpdeskViewController().require()
helpdeskViewController.course = self.currentItem?.section?.course
let navigationController = CustomWidthNavigationController(rootViewController: helpdeskViewController)
self.present(navigationController, animated: trueUnlessReduceMotionEnabled)
}
}
extension CourseItemViewController: UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let item = self.previousItem else { return nil }
guard let newViewController = self.viewController(for: item) else { return nil }
return newViewController
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let item = self.nextItem else { return nil }
guard let newViewController = self.viewController(for: item) else { return nil }
return newViewController
}
}
extension CourseItemViewController: UIPageViewControllerDelegate {
func pageViewController(_ pageViewController: UIPageViewController,
didFinishAnimating finished: Bool,
previousViewControllers: [UIViewController],
transitionCompleted completed: Bool) {
guard finished && completed else {
return
}
guard let currentCourseItemContentViewController = self.viewControllers?.first as? CourseItemContentViewController else {
return
}
self.currentItem = currentCourseItemContentViewController.item
}
}
| gpl-3.0 |
LeoMobileDeveloper/PullToRefreshKit | Sources/PullToRefreshKit/Classes/Availability.swift | 1 | 8321 | //
// Availability.swift
// PullToRefreshKit
//
// Created by Leo on 2017/11/9.
// Copyright © 2017年 Leo Huang. All rights reserved.
//
import Foundation
import UIKit
public protocol SetUp {}
public extension SetUp where Self: AnyObject {
@discardableResult
@available(*, deprecated, message: "This method will be removed at V 1.0.0")
func SetUp(_ closure: (Self) -> Void) -> Self {
closure(self)
return self
}
}
extension NSObject: SetUp {}
//Header
public extension UIScrollView{
@discardableResult
@available(*, deprecated, message: "Use new API at PullToRefresh.Swift")
func setUpHeaderRefresh(_ action:@escaping ()->())->DefaultRefreshHeader{
let header = DefaultRefreshHeader(frame:CGRect(x: 0,
y: 0,
width: self.frame.width,
height: PullToRefreshKitConst.defaultHeaderHeight))
return setUpHeaderRefresh(header, action: action)
}
@discardableResult
@available(*, deprecated, message: "Use new API at PullToRefresh.Swift")
func setUpHeaderRefresh<T:UIView>(_ header:T,action:@escaping ()->())->T where T:RefreshableHeader{
let oldContain = self.viewWithTag(PullToRefreshKitConst.headerTag)
oldContain?.removeFromSuperview()
let containFrame = CGRect(x: 0, y: -self.frame.height, width: self.frame.width, height: self.frame.height)
let containComponent = RefreshHeaderContainer(frame: containFrame)
if let endDuration = header.durationOfHideAnimation?(){
containComponent.durationOfEndRefreshing = endDuration
}
containComponent.tag = PullToRefreshKitConst.headerTag
containComponent.refreshAction = action
self.addSubview(containComponent)
containComponent.delegate = header
header.autoresizingMask = [.flexibleWidth,.flexibleHeight]
let bounds = CGRect(x: 0,y: containFrame.height - header.frame.height,width: self.frame.width,height: header.frame.height)
header.frame = bounds
containComponent.addSubview(header)
return header
}
@available(*, deprecated, message: "Use new API at PullToRefresh.Swift")
func beginHeaderRefreshing(){
let header = self.viewWithTag(PullToRefreshKitConst.headerTag) as? RefreshHeaderContainer
header?.beginRefreshing()
}
@available(*, deprecated, message: "Use new API at PullToRefresh.Swift")
func endHeaderRefreshing(_ result:RefreshResult = .none,delay:Double = 0.0){
let header = self.viewWithTag(PullToRefreshKitConst.headerTag) as? RefreshHeaderContainer
header?.endRefreshing(result,delay: delay)
}
}
//Footer
public extension UIScrollView{
@discardableResult
@available(*, deprecated, message: "Use new API at PullToRefresh.Swift")
func setUpFooterRefresh(_ action:@escaping ()->())->DefaultRefreshFooter{
let footer = DefaultRefreshFooter(frame: CGRect(x: 0,
y: 0,
width: self.frame.width,
height: PullToRefreshKitConst.defaultFooterHeight))
return setUpFooterRefresh(footer, action: action)
}
@discardableResult
@available(*, deprecated, message: "Use new API at PullToRefresh.Swift")
func setUpFooterRefresh<T:UIView>(_ footer:T,action:@escaping ()->())->T where T:RefreshableFooter{
let oldContain = self.viewWithTag(PullToRefreshKitConst.footerTag)
oldContain?.removeFromSuperview()
let frame = CGRect(x: 0,y: 0,width: self.frame.width, height: PullToRefreshKitConst.defaultFooterHeight)
let containComponent = RefreshFooterContainer(frame: frame)
containComponent.tag = PullToRefreshKitConst.footerTag
containComponent.refreshAction = action
self.insertSubview(containComponent, at: 0)
containComponent.delegate = footer
footer.autoresizingMask = [.flexibleWidth,.flexibleHeight]
footer.frame = containComponent.bounds
containComponent.addSubview(footer)
return footer
}
@available(*, deprecated, message: "Use new API at PullToRefresh.Swift")
func beginFooterRefreshing(){
let footer = self.viewWithTag(PullToRefreshKitConst.footerTag) as? RefreshFooterContainer
if footer?.state == .idle {
footer?.beginRefreshing()
}
}
@available(*, deprecated, message: "Use new API at PullToRefresh.Swift")
func endFooterRefreshing(){
let footer = self.viewWithTag(PullToRefreshKitConst.footerTag) as? RefreshFooterContainer
footer?.endRefreshing()
}
@available(*, deprecated, message: "Use new API at PullToRefresh.Swift")
func setFooterNoMoreData(){
let footer = self.viewWithTag(PullToRefreshKitConst.footerTag) as? RefreshFooterContainer
footer?.endRefreshing()
}
@available(*, deprecated, message: "Use new API at PullToRefresh.Swift")
func resetFooterToDefault(){
let footer = self.viewWithTag(PullToRefreshKitConst.footerTag) as? RefreshFooterContainer
footer?.resetToDefault()
}
@available(*, deprecated, message: "Use new API at PullToRefresh.Swift")
func endFooterRefreshingWithNoMoreData(){
let footer = self.viewWithTag(PullToRefreshKitConst.footerTag) as? RefreshFooterContainer
footer?.endRefreshing()
footer?.updateToNoMoreData()
}
}
//Left
extension UIScrollView{
@discardableResult
@available(*, deprecated, message: "Use new API at PullToRefresh.Swift")
public func setUpLeftRefresh(_ action: @escaping ()->())->DefaultRefreshLeft{
let left = DefaultRefreshLeft(frame: CGRect(x: 0,y: 0,width: PullToRefreshKitConst.defaultLeftWidth, height: self.frame.height))
return setUpLeftRefresh(left, action: action)
}
@discardableResult
@available(*, deprecated, message: "Use new API at PullToRefresh.Swift")
public func setUpLeftRefresh<T:UIView>(_ left:T,action:@escaping ()->())->T where T:RefreshableLeftRight{
let oldContain = self.viewWithTag(PullToRefreshKitConst.leftTag)
oldContain?.removeFromSuperview()
let frame = CGRect(x: -1.0 * PullToRefreshKitConst.defaultLeftWidth,y: 0,width: PullToRefreshKitConst.defaultLeftWidth, height: self.frame.height)
let containComponent = RefreshLeftContainer(frame: frame)
containComponent.tag = PullToRefreshKitConst.leftTag
containComponent.refreshAction = action
self.insertSubview(containComponent, at: 0)
containComponent.delegate = left
left.autoresizingMask = [.flexibleWidth,.flexibleHeight]
left.frame = containComponent.bounds
containComponent.addSubview(left)
return left
}
}
//Right
extension UIScrollView{
@discardableResult
@available(*, deprecated, message: "Use new API at PullToRefresh.Swift")
public func setUpRightRefresh(_ action:@escaping ()->())->DefaultRefreshRight{
let right = DefaultRefreshRight(frame: CGRect(x: 0 ,y: 0 ,width: PullToRefreshKitConst.defaultLeftWidth ,height: self.frame.height ))
return setUpRightRefresh(right, action: action)
}
@discardableResult
@available(*, deprecated, message: "Use new API at PullToRefresh.Swift")
public func setUpRightRefresh<T:UIView>(_ right:T,action:@escaping ()->())->T where T:RefreshableLeftRight{
let oldContain = self.viewWithTag(PullToRefreshKitConst.rightTag)
oldContain?.removeFromSuperview()
let frame = CGRect(x: 0 ,y: 0 ,width: PullToRefreshKitConst.defaultLeftWidth ,height: self.frame.height )
let containComponent = RefreshRightContainer(frame: frame)
containComponent.tag = PullToRefreshKitConst.rightTag
containComponent.refreshAction = action
self.insertSubview(containComponent, at: 0)
containComponent.delegate = right
right.autoresizingMask = [.flexibleWidth,.flexibleHeight]
right.frame = containComponent.bounds
containComponent.addSubview(right)
return right
}
}
| mit |
xiabob/ZhiHuDaily | ZhiHuDaily/ZhiHuDaily/Frameworks/XBCycleView/XBImageDownloader.swift | 3 | 3546 | //
// XBImageDownloader.swift
// XBCycleView
//
// Created by xiabob on 16/6/13.
// Copyright © 2016年 xiabob. All rights reserved.
//
import UIKit
public typealias finishClosure = (_ image: UIImage?) -> ()
open class XBImageDownloader: NSObject {
fileprivate lazy var imageCache: NSCache<AnyObject, UIImage> = {
let cache = NSCache<AnyObject, UIImage>()
cache.countLimit = 10
return cache
}()
fileprivate lazy var imageCacheDir: String = {
var dirString = ""
if let dir = NSSearchPathForDirectoriesInDomains(.cachesDirectory,
.userDomainMask,
true).last {
dirString = dir + "/XBImageDownloaderCache"
}
return dirString
}()
override init() {
super.init()
commonInit()
}
fileprivate func commonInit() {
let isCacheDirExist = FileManager.default.fileExists(atPath: imageCacheDir)
if !isCacheDirExist {
do {
try FileManager.default.createDirectory(atPath: imageCacheDir, withIntermediateDirectories: true, attributes: nil)
} catch {
print("XBImageDownloaderCache dir create error")
}
}
}
fileprivate func getImageFromLocal(_ url: String) -> UIImage? {
let path = imageCacheDir + "/" + url.xb_MD5
if let data = try? Data(contentsOf: URL(fileURLWithPath: path)) {
return UIImage(data: data)
} else {
return nil
}
}
open func getImageWithUrl(urlString url: String, completeClosure closure: @escaping finishClosure) {
//first get image from memory
if let image = imageCache.object(forKey: url as AnyObject) {
closure(image)
return
}
//second get image from local
if let image = getImageFromLocal(url) {
//save to memory
imageCache.setObject(image, forKey: url as AnyObject)
closure(image)
return
}
//last get image from network
let queue = DispatchQueue(label: "com.xiabob.XBCycleView", attributes: DispatchQueue.Attributes.concurrent)
queue.async { [unowned self] in
if let imageUrl = URL(string: url) {
if let imageData = try? Data(contentsOf: imageUrl) {
//save to disk
try? imageData.write(to: URL(fileURLWithPath: self.imageCacheDir + "/" + url.xb_MD5), options: [.atomic])
let image = UIImage(data: imageData)
if image != nil {
//save to memory
self.imageCache.setObject(image!, forKey: url as AnyObject)
}
DispatchQueue.main.async(execute: {
closure(image)
})
return
}
}
}
}
open func clearCachedImages() {
do {
let paths = try FileManager.default.contentsOfDirectory(atPath: imageCacheDir)
for path in paths {
try FileManager.default.removeItem(atPath: imageCacheDir + "/" + path)
}
} catch {
print("XBImageDownloaderCache dir remove error")
}
}
}
| mit |
matsoftware/SDevBootstrapButton | SDevBootstrapButton/SDevBootstrapButton/String+FontAwesome.swift | 1 | 24718 | //
// NSString+FontAwesome.swift
// SDevBootstrapButton
//
// Created by Sedat Ciftci on 22/02/15.
// Copyright (c) 2015 Sedat Ciftci. All rights reserved.
//
import UIKit
public extension UIFont {
public class func fontAwesomeOfSize(fontSize: CGFloat) -> UIFont {
return UIFont(name: "FontAwesome", size: fontSize)!
}
}
public extension String {
public static func fontAwesomeIconWithName(name: String) -> String {
var icons: [String: String]?
var token: dispatch_once_t = 0
dispatch_once(&token) {
icons = [
"adjust":"\u{f042}",
"adn":"\u{f170}",
"align-center":"\u{f037}",
"align-justify":"\u{f039}",
"align-left":"\u{f036}",
"align-right":"\u{f038}",
"ambulance":"\u{f0f9}",
"anchor":"\u{f13d}",
"android":"\u{f17b}",
"angellist":"\u{f209}",
"angle-double-down":"\u{f103}",
"angle-double-left":"\u{f100}",
"angle-double-right":"\u{f101}",
"angle-double-up":"\u{f102}",
"angle-down":"\u{f107}",
"angle-left":"\u{f104}",
"angle-right":"\u{f105}",
"angle-up":"\u{f106}",
"apple":"\u{f179}",
"archive":"\u{f187}",
"area-chart":"\u{f1fe}",
"arrow-circle-down":"\u{f0ab}",
"arrow-circle-left":"\u{f0a8}",
"arrow-circle-o-down":"\u{f01a}",
"arrow-circle-o-left":"\u{f190}",
"arrow-circle-o-right":"\u{f18e}",
"arrow-circle-o-up":"\u{f01b}",
"arrow-circle-right":"\u{f0a9}",
"arrow-circle-up":"\u{f0aa}",
"arrow-down":"\u{f063}",
"arrow-left":"\u{f060}",
"arrow-right":"\u{f061}",
"arrow-up":"\u{f062}",
"arrows":"\u{f047}",
"arrows-alt":"\u{f0b2}",
"arrows-h":"\u{f07e}",
"arrows-v":"\u{f07d}",
"asterisk":"\u{f069}",
"at":"\u{f1fa}",
"automobile (alias)":"\u{f1b9}",
"backward":"\u{f04a}",
"ban":"\u{f05e}",
"bank (alias)":"\u{f19c}",
"bar-chart":"\u{f080}",
"bar-chart-o (alias)":"\u{f080}",
"barcode":"\u{f02a}",
"bars":"\u{f0c9}",
"bed":"\u{f236}",
"beer":"\u{f0fc}",
"behance":"\u{f1b4}",
"behance-square":"\u{f1b5}",
"bell":"\u{f0f3}",
"bell-o":"\u{f0a2}",
"bell-slash":"\u{f1f6}",
"bell-slash-o":"\u{f1f7}",
"bicycle":"\u{f206}",
"binoculars":"\u{f1e5}",
"birthday-cake":"\u{f1fd}",
"bitbucket":"\u{f171}",
"bitbucket-square":"\u{f172}",
"bitcoin (alias)":"\u{f15a}",
"bold":"\u{f032}",
"bolt":"\u{f0e7}",
"bomb":"\u{f1e2}",
"book":"\u{f02d}",
"bookmark":"\u{f02e}",
"bookmark-o":"\u{f097}",
"briefcase":"\u{f0b1}",
"btc":"\u{f15a}",
"bug":"\u{f188}",
"building":"\u{f1ad}",
"building-o":"\u{f0f7}",
"bullhorn":"\u{f0a1}",
"bullseye":"\u{f140}",
"bus":"\u{f207}",
"buysellads":"\u{f20d}",
"cab (alias)":"\u{f1ba}",
"calculator":"\u{f1ec}",
"calendar":"\u{f073}",
"calendar-o":"\u{f133}",
"camera":"\u{f030}",
"camera-retro":"\u{f083}",
"car":"\u{f1b9}",
"caret-down":"\u{f0d7}",
"caret-left":"\u{f0d9}",
"caret-right":"\u{f0da}",
"caret-square-o-down":"\u{f150}",
"caret-square-o-left":"\u{f191}",
"caret-square-o-right":"\u{f152}",
"caret-square-o-up":"\u{f151}",
"caret-up":"\u{f0d8}",
"cart-arrow-down":"\u{f218}",
"cart-plus":"\u{f217}",
"cc":"\u{f20a}",
"cc-amex":"\u{f1f3}",
"cc-discover":"\u{f1f2}",
"cc-mastercard":"\u{f1f1}",
"cc-paypal":"\u{f1f4}",
"cc-stripe":"\u{f1f5}",
"cc-visa":"\u{f1f0}",
"certificate":"\u{f0a3}",
"chain (alias)":"\u{f0c1}",
"chain-broken":"\u{f127}",
"check":"\u{f00c}",
"check-circle":"\u{f058}",
"check-circle-o":"\u{f05d}",
"check-square":"\u{f14a}",
"check-square-o":"\u{f046}",
"chevron-circle-down":"\u{f13a}",
"chevron-circle-left":"\u{f137}",
"chevron-circle-right":"\u{f138}",
"chevron-circle-up":"\u{f139}",
"chevron-down":"\u{f078}",
"chevron-left":"\u{f053}",
"chevron-right":"\u{f054}",
"chevron-up":"\u{f077}",
"child":"\u{f1ae}",
"circle":"\u{f111}",
"circle-o":"\u{f10c}",
"circle-o-notch":"\u{f1ce}",
"circle-thin":"\u{f1db}",
"clipboard":"\u{f0ea}",
"clock-o":"\u{f017}",
"close (alias)":"\u{f00d}",
"cloud":"\u{f0c2}",
"cloud-download":"\u{f0ed}",
"cloud-upload":"\u{f0ee}",
"cny (alias)":"\u{f157}",
"code":"\u{f121}",
"code-fork":"\u{f126}",
"codepen":"\u{f1cb}",
"coffee":"\u{f0f4}",
"cog":"\u{f013}",
"cogs":"\u{f085}",
"columns":"\u{f0db}",
"comment":"\u{f075}",
"comment-o":"\u{f0e5}",
"comments":"\u{f086}",
"comments-o":"\u{f0e6}",
"compass":"\u{f14e}",
"compress":"\u{f066}",
"connectdevelop":"\u{f20e}",
"copy (alias)":"\u{f0c5}",
"copyright":"\u{f1f9}",
"credit-card":"\u{f09d}",
"crop":"\u{f125}",
"crosshairs":"\u{f05b}",
"css3":"\u{f13c}",
"cube":"\u{f1b2}",
"cubes":"\u{f1b3}",
"cut (alias)":"\u{f0c4}",
"cutlery":"\u{f0f5}",
"dashboard (alias)":"\u{f0e4}",
"dashcube":"\u{f210}",
"database":"\u{f1c0}",
"dedent (alias)":"\u{f03b}",
"delicious":"\u{f1a5}",
"desktop":"\u{f108}",
"deviantart":"\u{f1bd}",
"diamond":"\u{f219}",
"digg":"\u{f1a6}",
"dollar (alias)":"\u{f155}",
"dot-circle-o":"\u{f192}",
"download":"\u{f019}",
"dribbble":"\u{f17d}",
"dropbox":"\u{f16b}",
"drupal":"\u{f1a9}",
"edit (alias)":"\u{f044}",
"eject":"\u{f052}",
"ellipsis-h":"\u{f141}",
"ellipsis-v":"\u{f142}",
"empire":"\u{f1d1}",
"envelope":"\u{f0e0}",
"envelope-o":"\u{f003}",
"envelope-square":"\u{f199}",
"eraser":"\u{f12d}",
"eur":"\u{f153}",
"euro (alias)":"\u{f153}",
"exchange":"\u{f0ec}",
"exclamation":"\u{f12a}",
"exclamation-circle":"\u{f06a}",
"exclamation-triangle":"\u{f071}",
"expand":"\u{f065}",
"external-link":"\u{f08e}",
"external-link-square":"\u{f14c}",
"eye":"\u{f06e}",
"eye-slash":"\u{f070}",
"eyedropper":"\u{f1fb}",
"facebook":"\u{f09a}",
"facebook-f (alias)":"\u{f09a}",
"facebook-official":"\u{f230}",
"facebook-square":"\u{f082}",
"fast-backward":"\u{f049}",
"fast-forward":"\u{f050}",
"fax":"\u{f1ac}",
"female":"\u{f182}",
"fighter-jet":"\u{f0fb}",
"file":"\u{f15b}",
"file-archive-o":"\u{f1c6}",
"file-audio-o":"\u{f1c7}",
"file-code-o":"\u{f1c9}",
"file-excel-o":"\u{f1c3}",
"file-image-o":"\u{f1c5}",
"file-movie-o (alias)":"\u{f1c8}",
"file-o":"\u{f016}",
"file-pdf-o":"\u{f1c1}",
"file-photo-o (alias)":"\u{f1c5}",
"file-picture-o (alias)":"\u{f1c5}",
"file-powerpoint-o":"\u{f1c4}",
"file-sound-o (alias)":"\u{f1c7}",
"file-text":"\u{f15c}",
"file-text-o":"\u{f0f6}",
"file-video-o":"\u{f1c8}",
"file-word-o":"\u{f1c2}",
"file-zip-o (alias)":"\u{f1c6}",
"files-o":"\u{f0c5}",
"film":"\u{f008}",
"filter":"\u{f0b0}",
"fire":"\u{f06d}",
"fire-extinguisher":"\u{f134}",
"flag":"\u{f024}",
"flag-checkered":"\u{f11e}",
"flag-o":"\u{f11d}",
"flash (alias)":"\u{f0e7}",
"flask":"\u{f0c3}",
"flickr":"\u{f16e}",
"floppy-o":"\u{f0c7}",
"folder":"\u{f07b}",
"folder-o":"\u{f114}",
"folder-open":"\u{f07c}",
"folder-open-o":"\u{f115}",
"font":"\u{f031}",
"forumbee":"\u{f211}",
"forward":"\u{f04e}",
"foursquare":"\u{f180}",
"frown-o":"\u{f119}",
"futbol-o":"\u{f1e3}",
"gamepad":"\u{f11b}",
"gavel":"\u{f0e3}",
"gbp":"\u{f154}",
"ge (alias)":"\u{f1d1}",
"gear (alias)":"\u{f013}",
"gears (alias)":"\u{f085}",
"genderless (alias)":"\u{f1db}",
"gift":"\u{f06b}",
"git":"\u{f1d3}",
"git-square":"\u{f1d2}",
"github":"\u{f09b}",
"github-alt":"\u{f113}",
"github-square":"\u{f092}",
"gittip (alias)":"\u{f184}",
"glass":"\u{f000}",
"globe":"\u{f0ac}",
"google":"\u{f1a0}",
"google-plus":"\u{f0d5}",
"google-plus-square":"\u{f0d4}",
"google-wallet":"\u{f1ee}",
"graduation-cap":"\u{f19d}",
"gratipay":"\u{f184}",
"group (alias)":"\u{f0c0}",
"h-square":"\u{f0fd}",
"hacker-news":"\u{f1d4}",
"hand-o-down":"\u{f0a7}",
"hand-o-left":"\u{f0a5}",
"hand-o-right":"\u{f0a4}",
"hand-o-up":"\u{f0a6}",
"hdd-o":"\u{f0a0}",
"header":"\u{f1dc}",
"headphones":"\u{f025}",
"heart":"\u{f004}",
"heart-o":"\u{f08a}",
"heartbeat":"\u{f21e}",
"history":"\u{f1da}",
"home":"\u{f015}",
"hospital-o":"\u{f0f8}",
"hotel (alias)":"\u{f236}",
"html5":"\u{f13b}",
"ils":"\u{f20b}",
"image (alias)":"\u{f03e}",
"inbox":"\u{f01c}",
"indent":"\u{f03c}",
"info":"\u{f129}",
"info-circle":"\u{f05a}",
"inr":"\u{f156}",
"instagram":"\u{f16d}",
"institution (alias)":"\u{f19c}",
"ioxhost":"\u{f208}",
"italic":"\u{f033}",
"joomla":"\u{f1aa}",
"jpy":"\u{f157}",
"jsfiddle":"\u{f1cc}",
"key":"\u{f084}",
"keyboard-o":"\u{f11c}",
"krw":"\u{f159}",
"language":"\u{f1ab}",
"laptop":"\u{f109}",
"lastfm":"\u{f202}",
"lastfm-square":"\u{f203}",
"leaf":"\u{f06c}",
"leanpub":"\u{f212}",
"legal (alias)":"\u{f0e3}",
"lemon-o":"\u{f094}",
"level-down":"\u{f149}",
"level-up":"\u{f148}",
"life-bouy (alias)":"\u{f1cd}",
"life-buoy (alias)":"\u{f1cd}",
"life-ring":"\u{f1cd}",
"life-saver (alias)":"\u{f1cd}",
"lightbulb-o":"\u{f0eb}",
"line-chart":"\u{f201}",
"link":"\u{f0c1}",
"linkedin":"\u{f0e1}",
"linkedin-square":"\u{f08c}",
"linux":"\u{f17c}",
"list":"\u{f03a}",
"list-alt":"\u{f022}",
"list-ol":"\u{f0cb}",
"list-ul":"\u{f0ca}",
"location-arrow":"\u{f124}",
"lock":"\u{f023}",
"long-arrow-down":"\u{f175}",
"long-arrow-left":"\u{f177}",
"long-arrow-right":"\u{f178}",
"long-arrow-up":"\u{f176}",
"magic":"\u{f0d0}",
"magnet":"\u{f076}",
"mail-forward (alias)":"\u{f064}",
"mail-reply (alias)":"\u{f112}",
"mail-reply-all (alias)":"\u{f122}",
"male":"\u{f183}",
"map-marker":"\u{f041}",
"mars":"\u{f222}",
"mars-double":"\u{f227}",
"mars-stroke":"\u{f229}",
"mars-stroke-h":"\u{f22b}",
"mars-stroke-v":"\u{f22a}",
"maxcdn":"\u{f136}",
"meanpath":"\u{f20c}",
"medium":"\u{f23a}",
"medkit":"\u{f0fa}",
"meh-o":"\u{f11a}",
"mercury":"\u{f223}",
"microphone":"\u{f130}",
"microphone-slash":"\u{f131}",
"minus":"\u{f068}",
"minus-circle":"\u{f056}",
"minus-square":"\u{f146}",
"minus-square-o":"\u{f147}",
"mobile":"\u{f10b}",
"mobile-phone (alias)":"\u{f10b}",
"money":"\u{f0d6}",
"moon-o":"\u{f186}",
"mortar-board (alias)":"\u{f19d}",
"motorcycle":"\u{f21c}",
"music":"\u{f001}",
"navicon (alias)":"\u{f0c9}",
"neuter":"\u{f22c}",
"newspaper-o":"\u{f1ea}",
"openid":"\u{f19b}",
"outdent":"\u{f03b}",
"pagelines":"\u{f18c}",
"paint-brush":"\u{f1fc}",
"paper-plane":"\u{f1d8}",
"paper-plane-o":"\u{f1d9}",
"paperclip":"\u{f0c6}",
"paragraph":"\u{f1dd}",
"paste (alias)":"\u{f0ea}",
"pause":"\u{f04c}",
"paw":"\u{f1b0}",
"paypal":"\u{f1ed}",
"pencil":"\u{f040}",
"pencil-square":"\u{f14b}",
"pencil-square-o":"\u{f044}",
"phone":"\u{f095}",
"phone-square":"\u{f098}",
"photo (alias)":"\u{f03e}",
"picture-o":"\u{f03e}",
"pie-chart":"\u{f200}",
"pied-piper":"\u{f1a7}",
"pied-piper-alt":"\u{f1a8}",
"pinterest":"\u{f0d2}",
"pinterest-p":"\u{f231}",
"pinterest-square":"\u{f0d3}",
"plane":"\u{f072}",
"play":"\u{f04b}",
"play-circle":"\u{f144}",
"play-circle-o":"\u{f01d}",
"plug":"\u{f1e6}",
"plus":"\u{f067}",
"plus-circle":"\u{f055}",
"plus-square":"\u{f0fe}",
"plus-square-o":"\u{f196}",
"power-off":"\u{f011}",
"print":"\u{f02f}",
"puzzle-piece":"\u{f12e}",
"qq":"\u{f1d6}",
"qrcode":"\u{f029}",
"question":"\u{f128}",
"question-circle":"\u{f059}",
"quote-left":"\u{f10d}",
"quote-right":"\u{f10e}",
"ra (alias)":"\u{f1d0}",
"random":"\u{f074}",
"rebel":"\u{f1d0}",
"recycle":"\u{f1b8}",
"reddit":"\u{f1a1}",
"reddit-square":"\u{f1a2}",
"refresh":"\u{f021}",
"remove (alias)":"\u{f00d}",
"renren":"\u{f18b}",
"reorder (alias)":"\u{f0c9}",
"repeat":"\u{f01e}",
"reply":"\u{f112}",
"reply-all":"\u{f122}",
"retweet":"\u{f079}",
"rmb (alias)":"\u{f157}",
"road":"\u{f018}",
"rocket":"\u{f135}",
"rotate-left (alias)":"\u{f0e2}",
"rotate-right (alias)":"\u{f01e}",
"rouble (alias)":"\u{f158}",
"rss":"\u{f09e}",
"rss-square":"\u{f143}",
"rub":"\u{f158}",
"ruble (alias)":"\u{f158}",
"rupee (alias)":"\u{f156}",
"save (alias)":"\u{f0c7}",
"scissors":"\u{f0c4}",
"search":"\u{f002}",
"search-minus":"\u{f010}",
"search-plus":"\u{f00e}",
"sellsy":"\u{f213}",
"send (alias)":"\u{f1d8}",
"send-o (alias)":"\u{f1d9}",
"server":"\u{f233}",
"share":"\u{f064}",
"share-alt":"\u{f1e0}",
"share-alt-square":"\u{f1e1}",
"share-square":"\u{f14d}",
"share-square-o":"\u{f045}",
"shekel (alias)":"\u{f20b}",
"sheqel (alias)":"\u{f20b}",
"shield":"\u{f132}",
"ship":"\u{f21a}",
"shirtsinbulk":"\u{f214}",
"shopping-cart":"\u{f07a}",
"sign-in":"\u{f090}",
"sign-out":"\u{f08b}",
"signal":"\u{f012}",
"simplybuilt":"\u{f215}",
"sitemap":"\u{f0e8}",
"skyatlas":"\u{f216}",
"skype":"\u{f17e}",
"slack":"\u{f198}",
"sliders":"\u{f1de}",
"slideshare":"\u{f1e7}",
"smile-o":"\u{f118}",
"soccer-ball-o (alias)":"\u{f1e3}",
"sort":"\u{f0dc}",
"sort-alpha-asc":"\u{f15d}",
"sort-alpha-desc":"\u{f15e}",
"sort-amount-asc":"\u{f160}",
"sort-amount-desc":"\u{f161}",
"sort-asc":"\u{f0de}",
"sort-desc":"\u{f0dd}",
"sort-down (alias)":"\u{f0dd}",
"sort-numeric-asc":"\u{f162}",
"sort-numeric-desc":"\u{f163}",
"sort-up (alias)":"\u{f0de}",
"soundcloud":"\u{f1be}",
"space-shuttle":"\u{f197}",
"spinner":"\u{f110}",
"spoon":"\u{f1b1}",
"spotify":"\u{f1bc}",
"square":"\u{f0c8}",
"square-o":"\u{f096}",
"stack-exchange":"\u{f18d}",
"stack-overflow":"\u{f16c}",
"star":"\u{f005}",
"star-half":"\u{f089}",
"star-half-empty (alias)":"\u{f123}",
"star-half-full (alias)":"\u{f123}",
"star-half-o":"\u{f123}",
"star-o":"\u{f006}",
"steam":"\u{f1b6}",
"steam-square":"\u{f1b7}",
"step-backward":"\u{f048}",
"step-forward":"\u{f051}",
"stethoscope":"\u{f0f1}",
"stop":"\u{f04d}",
"street-view":"\u{f21d}",
"strikethrough":"\u{f0cc}",
"stumbleupon":"\u{f1a4}",
"stumbleupon-circle":"\u{f1a3}",
"subscript":"\u{f12c}",
"subway":"\u{f239}",
"suitcase":"\u{f0f2}",
"sun-o":"\u{f185}",
"superscript":"\u{f12b}",
"support (alias)":"\u{f1cd}",
"table":"\u{f0ce}",
"tablet":"\u{f10a}",
"tachometer":"\u{f0e4}",
"tag":"\u{f02b}",
"tags":"\u{f02c}",
"tasks":"\u{f0ae}",
"taxi":"\u{f1ba}",
"tencent-weibo":"\u{f1d5}",
"terminal":"\u{f120}",
"text-height":"\u{f034}",
"text-width":"\u{f035}",
"th":"\u{f00a}",
"th-large":"\u{f009}",
"th-list":"\u{f00b}",
"thumb-tack":"\u{f08d}",
"thumbs-down":"\u{f165}",
"thumbs-o-down":"\u{f088}",
"thumbs-o-up":"\u{f087}",
"thumbs-up":"\u{f164}",
"ticket":"\u{f145}",
"times":"\u{f00d}",
"times-circle":"\u{f057}",
"times-circle-o":"\u{f05c}",
"tint":"\u{f043}",
"toggle-down (alias)":"\u{f150}",
"toggle-left (alias)":"\u{f191}",
"toggle-off":"\u{f204}",
"toggle-on":"\u{f205}",
"toggle-right (alias)":"\u{f152}",
"toggle-up (alias)":"\u{f151}",
"train":"\u{f238}",
"transgender":"\u{f224}",
"transgender-alt":"\u{f225}",
"trash":"\u{f1f8}",
"trash-o":"\u{f014}",
"tree":"\u{f1bb}",
"trello":"\u{f181}",
"trophy":"\u{f091}",
"truck":"\u{f0d1}",
"try":"\u{f195}",
"tty":"\u{f1e4}",
"tumblr":"\u{f173}",
"tumblr-square":"\u{f174}",
"turkish-lira (alias)":"\u{f195}",
"twitch":"\u{f1e8}",
"twitter":"\u{f099}",
"twitter-square":"\u{f081}",
"umbrella":"\u{f0e9}",
"underline":"\u{f0cd}",
"undo":"\u{f0e2}",
"university":"\u{f19c}",
"unlink (alias)":"\u{f127}",
"unlock":"\u{f09c}",
"unlock-alt":"\u{f13e}",
"unsorted (alias)":"\u{f0dc}",
"upload":"\u{f093}",
"usd":"\u{f155}",
"user":"\u{f007}",
"user-md":"\u{f0f0}",
"user-plus":"\u{f234}",
"user-secret":"\u{f21b}",
"user-times":"\u{f235}",
"users":"\u{f0c0}",
"venus":"\u{f221}",
"venus-double":"\u{f226}",
"venus-mars":"\u{f228}",
"viacoin":"\u{f237}",
"video-camera":"\u{f03d}",
"vimeo-square":"\u{f194}",
"vine":"\u{f1ca}",
"vk":"\u{f189}",
"volume-down":"\u{f027}",
"volume-off":"\u{f026}",
"volume-up":"\u{f028}",
"warning (alias)":"\u{f071}",
"wechat (alias)":"\u{f1d7}",
"weibo":"\u{f18a}",
"weixin":"\u{f1d7}",
"whatsapp":"\u{f232}",
"wheelchair":"\u{f193}",
"wifi":"\u{f1eb}",
"windows":"\u{f17a}",
"won (alias)":"\u{f159}",
"wordpress":"\u{f19a}",
"wrench":"\u{f0ad}",
"xing":"\u{f168}",
"xing-square":"\u{f169}",
"yahoo":"\u{f19e}",
"yelp":"\u{f1e9}",
"yen (alias)":"\u{f157}",
"youtube":"\u{f167}",
"youtube-play":"\u{f16a}"
]
}
return icons![name]!
}
} | mit |
07cs07/Design-Patterns-In-Swift | Design-Patterns.playground/section-62.swift | 4 | 105 | var tuple = PointConverter.convert(x:1.1, y:2.2, z:3.3, base:2.0, negative:true)
tuple.x
tuple.y
tuple.z | gpl-3.0 |
PureSwift/JSONC | Sources/JSONC/JSONExtensions.swift | 1 | 491 | //
// JSONExtensions.swift
// JSONC
//
// Created by Alsey Coleman Miller on 12/19/15.
// Copyright © 2015 PureSwift. All rights reserved.
//
import SwiftFoundation
public extension JSON.Value {
/// Deserializes JSON from a string.
///
/// - Note: Uses the [JSON-C](https://github.com/json-c/json-c) library.
init?(string: Swift.String) {
guard let value = JSONC.parse(string)
else { return nil }
self = value
}
} | mit |
SomnusLee1988/Azure | Azure/UIColorExtension.swift | 1 | 583 | //
// UIColorExtension.swift
// Mokacam
//
// Created by Somnus on 16/3/19.
// Copyright © 2016年 Somnus. All rights reserved.
//
import UIKit
public extension UIColor {
static func RGBA (r:CGFloat, _ g:CGFloat, _ b:CGFloat, _ a:CGFloat) -> UIColor {
return UIColor (red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a)
}
static func RGB (r:CGFloat, _ g:CGFloat, _ b:CGFloat) -> UIColor {
return RGBA(r, g, b, 1);
}
static func grayColorForValue(value:CGFloat) -> UIColor{
return self.RGB(value, value, value);
}
}
| mit |
watson-developer-cloud/ios-sdk | Sources/DiscoveryV1/Models/AggregationResult.swift | 1 | 1811 | /**
* (C) Copyright IBM Corp. 2018, 2020.
*
* 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
/**
Aggregation results for the specified query.
*/
public struct AggregationResult: Codable, Equatable {
/**
Key that matched the aggregation type.
*/
public var key: String?
/**
Number of matching results.
*/
public var matchingResults: Int?
/**
Aggregations returned in the case of chained aggregations.
*/
public var aggregations: [QueryAggregation]?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case key = "key"
case matchingResults = "matching_results"
case aggregations = "aggregations"
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let keyAsString = try? container.decode(String.self, forKey: .key) { key = keyAsString }
if let keyAsInt = try? container.decode(Int.self, forKey: .key) { key = "\(keyAsInt)" }
matchingResults = try container.decodeIfPresent(Int.self, forKey: .matchingResults)
aggregations = try container.decodeIfPresent([QueryAggregation].self, forKey: .aggregations)
}
}
| apache-2.0 |
dreamsxin/swift | test/SILGen/implicitly_unwrapped_optional.swift | 2 | 2404 | // RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s
func foo(f f: (() -> ())!) {
var f: (() -> ())! = f
f?()
}
// CHECK: sil hidden @{{.*}}foo{{.*}} : $@convention(thin) (@owned ImplicitlyUnwrappedOptional<() -> ()>) -> () {
// CHECK: bb0([[T0:%.*]] : $ImplicitlyUnwrappedOptional<() -> ()>):
// CHECK: [[F:%.*]] = alloc_box $ImplicitlyUnwrappedOptional<() -> ()>
// CHECK-NEXT: [[PF:%.*]] = project_box [[F]]
// CHECK: store [[T0]] to [[PF]]
// CHECK: [[T1:%.*]] = select_enum_addr [[PF]]
// CHECK-NEXT: cond_br [[T1]], bb1, bb3
// If it does, project and load the value out of the implicitly unwrapped
// optional...
// CHECK: bb1:
// CHECK-NEXT: [[FN0_ADDR:%.*]] = unchecked_take_enum_data_addr [[PF]]
// CHECK-NEXT: [[FN0:%.*]] = load [[FN0_ADDR]]
// ...unnecessarily reabstract back to () -> ()...
// CHECK: [[T0:%.*]] = function_ref @_TTRXFo_iT__iT__XFo___ : $@convention(thin) (@owned @callee_owned (@in ()) -> @out ()) -> ()
// CHECK-NEXT: [[FN1:%.*]] = partial_apply [[T0]]([[FN0]])
// .... then call it
// CHECK-NEXT: apply [[FN1]]()
// CHECK: br bb2
// (first nothing block)
// CHECK: bb3:
// CHECK-NEXT: enum $Optional<()>, #Optional.none!enumelt
// CHECK-NEXT: br bb2
// The rest of this is tested in optional.swift
func wrap<T>(x x: T) -> T! { return x }
// CHECK-LABEL: sil hidden @_TF29implicitly_unwrapped_optional16wrap_then_unwrap
func wrap_then_unwrap<T>(x x: T) -> T {
// CHECK: [[FORCE:%.*]] = function_ref @_TFs45_stdlib_ImplicitlyUnwrappedOptional_unwrappedurFGSQx_x
// CHECK: apply [[FORCE]]<{{.*}}>(%0, {{%.*}})
return wrap(x: x)!
}
// CHECK-LABEL: sil hidden @_TF29implicitly_unwrapped_optional10tuple_bindFT1xGSQTSiSS___GSqSS_ : $@convention(thin) (@owned ImplicitlyUnwrappedOptional<(Int, String)>) -> @owned Optional<String> {
func tuple_bind(x x: (Int, String)!) -> String? {
return x?.1
// CHECK: cond_br {{%.*}}, [[NONNULL:bb[0-9]+]], [[NULL:bb[0-9]+]]
// CHECK: [[NONNULL]]:
// CHECK: [[STRING:%.*]] = tuple_extract {{%.*}} : $(Int, String), 1
// CHECK-NOT: release_value [[STRING]]
}
// CHECK-LABEL: sil hidden @_TF29implicitly_unwrapped_optional31tuple_bind_implicitly_unwrappedFT1xGSQTSiSS___SS
func tuple_bind_implicitly_unwrapped(x x: (Int, String)!) -> String {
return x.1
}
func return_any() -> AnyObject! { return nil }
func bind_any() {
let object : AnyObject? = return_any()
}
| apache-2.0 |
flodolo/firefox-ios | Tests/ClientTests/ReaderModeStyleTests.swift | 1 | 3979 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import XCTest
@testable import Client
class ReaderModeStyleTests: XCTestCase {
override func tearDown() {
super.tearDown()
LegacyThemeManager.instance.current = LegacyNormalTheme()
}
func test_initWithProperties_succeeds() {
let readerModeStyle = ReaderModeStyle(theme: .dark,
fontType: .sansSerif,
fontSize: .size1)
XCTAssertEqual(readerModeStyle.theme, ReaderModeTheme.dark)
XCTAssertEqual(readerModeStyle.fontType, ReaderModeFontType.sansSerif)
XCTAssertEqual(readerModeStyle.fontSize, ReaderModeFontSize.size1)
}
func test_encodingAsDictionary_succeeds() {
let readerModeStyle = ReaderModeStyle(theme: .dark,
fontType: .sansSerif,
fontSize: .size1)
let encodingResult: [String: Any] = readerModeStyle.encodeAsDictionary()
let themeResult = encodingResult["theme"] as? String
let fontTypeResult = encodingResult["fontType"] as? String
let fontSizeResult = encodingResult["fontSize"] as? Int
XCTAssertEqual(themeResult, ReaderModeTheme.dark.rawValue, "Encoding as dictionary theme result doesn't reflect style")
XCTAssertEqual(fontTypeResult, ReaderModeFontType.sansSerif.rawValue, "Encoding as dictionary fontType result doesn't reflect style")
XCTAssertEqual(fontSizeResult, ReaderModeFontSize.size1.rawValue, "Encoding as dictionary fontSize result doesn't reflect style")
}
func test_initWithDictionnary_succeeds() {
let readerModeStyle = ReaderModeStyle(dict: ["theme": ReaderModeTheme.dark.rawValue,
"fontType": ReaderModeFontType.sansSerif.rawValue,
"fontSize": ReaderModeFontSize.size1.rawValue])
XCTAssertEqual(readerModeStyle?.theme, ReaderModeTheme.dark)
XCTAssertEqual(readerModeStyle?.fontType, ReaderModeFontType.sansSerif)
XCTAssertEqual(readerModeStyle?.fontSize, ReaderModeFontSize.size1)
}
func test_initWithWrongDictionnary_fails() {
let readerModeStyle = ReaderModeStyle(dict: ["wrong": 1,
"fontType": ReaderModeFontType.sansSerif,
"fontSize": ReaderModeFontSize.size1])
XCTAssertNil(readerModeStyle)
}
func test_initWithEmptyDictionnary_fails() {
let readerModeStyle = ReaderModeStyle(dict: [:])
XCTAssertNil(readerModeStyle)
}
// MARK: - ReaderModeTheme
func test_defaultReaderModeTheme() {
let defaultTheme = ReaderModeTheme.preferredTheme(for: nil)
XCTAssertEqual(defaultTheme, .light)
}
func test_appWideThemeDark_returnsDark() {
LegacyThemeManager.instance.current = LegacyDarkTheme()
let theme = ReaderModeTheme.preferredTheme(for: ReaderModeTheme.light)
XCTAssertEqual(theme, .dark)
}
func test_readerThemeSepia_returnsSepia() {
let theme = ReaderModeTheme.preferredTheme(for: ReaderModeTheme.sepia)
XCTAssertEqual(theme, .sepia)
}
func test_preferredColorTheme_changesFromLightToDark() {
LegacyThemeManager.instance.current = LegacyDarkTheme()
var readerModeStyle = ReaderModeStyle(theme: .light,
fontType: .sansSerif,
fontSize: .size1)
XCTAssertEqual(readerModeStyle.theme, .light)
readerModeStyle.ensurePreferredColorThemeIfNeeded()
XCTAssertEqual(readerModeStyle.theme, .dark)
}
}
| mpl-2.0 |
Hamuko/Nullpo | Nullpo/PreferenceController.swift | 1 | 2347 | import Cocoa
class PreferenceController: NSWindowController {
@IBOutlet weak var backgroundLinkCheckbox: NSButton!
@IBOutlet weak var uploaderList: NSPopUpButton!
@IBOutlet weak var concurrentStepper: NSStepper!
dynamic var concurrentUploadCount = 4
convenience init() {
self.init(windowNibName: "PreferenceController")
}
override func windowDidLoad() {
super.windowDidLoad()
populateUploaderList()
loadUserPreferences()
}
/// Opening links in background was changed via the checkbox.
@IBAction func changedBackgroundLinks(sender: AnyObject) {
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
let openLinksInBackground: Bool = Bool(backgroundLinkCheckbox.state)
defaults.setBool(openLinksInBackground, forKey: "OpenLinksInBackground")
}
@IBAction func changedConcurrentUploadCount(sender: AnyObject) {
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(sender.integerValue, forKey: "ConcurrentUploadJobs")
}
/// Uploader was changed using the pop-up button.
@IBAction func changedUploader(sender: AnyObject) {
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
let selectedUploader: String = uploaderList.selectedItem!.title
defaults.setObject(selectedUploader, forKey: "Uploader")
}
/// Populate the settings window with NSUserDefaults values.
func loadUserPreferences() {
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
var concurrentUploads: Int = defaults.integerForKey("ConcurrentUploadJobs")
let openLinksInBackground: Bool = defaults.boolForKey("OpenLinksInBackground")
let uploaderName: String = defaults.objectForKey("Uploader") as? String ?? "Uguu"
if concurrentUploads <= 0 || concurrentUploads > 64 {
concurrentUploads = 1
}
backgroundLinkCheckbox.state = Int(openLinksInBackground)
concurrentUploadCount = concurrentUploads
uploaderList.selectItem(uploaderList.itemWithTitle(uploaderName))
}
/// Add keys from Uploaders.plist to the pop-up button.
func populateUploaderList() {
uploaderList.addItemsWithTitles(Array(UploadGroup.uploaders.keys))
}
}
| apache-2.0 |
couchbase/couchbase-lite-ios | Swift/CollectionConfiguration.swift | 1 | 3555 | //
// CollectionConfiguration.swift
// CouchbaseLite
//
// Copyright (c) 2017 Couchbase, Inc 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 collection configuration that can be configured specifically for the replication.
public struct CollectionConfiguration {
/// The custom conflict resolver function. If this value is nil, the default conflict resolver will be used..
public var conflictResolver: ConflictResolverProtocol?
/// Filter function for validating whether the documents can be pushed to the remote endpoint.
/// Only documents of which the function returns true are replicated.
public var pushFilter: ReplicationFilter?
/// Filter function for validating whether the documents can be pulled from the remote endpoint.
/// Only documents of which the function returns true are replicated.
public var pullFilter: ReplicationFilter?
/// Channels filter for specifying the channels for the pull the replicator will pull from. For any
/// collections that do not have the channels filter specified, all accessible channels will be pulled. Push
/// replicator will ignore this filter.
public var channels: Array<String>?
/// Document IDs filter to limit the documents in the collection to be replicated with the remote endpoint.
/// If not specified, all docs in the collection will be replicated.
public var documentIDs: Array<String>?
public init() {
self.init(config: nil)
}
// MARK: internal
init(config: CollectionConfiguration?) {
if let config = config {
self.conflictResolver = config.conflictResolver
self.pushFilter = config.pushFilter
self.pullFilter = config.pullFilter
self.channels = config.channels
self.documentIDs = config.documentIDs
}
}
func toImpl(_ collection: Collection) -> CBLCollectionConfiguration {
let c = CBLCollectionConfiguration()
c.channels = self.channels
c.documentIDs = self.documentIDs
if let pushFilter = self.filter(push: true, collection: collection) {
c.pushFilter = pushFilter
}
if let pullFilter = self.filter(push: false, collection: collection) {
c.pullFilter = pullFilter
}
if let resolver = self.conflictResolver {
c.setConflictResolverUsing { (conflict) -> CBLDocument? in
return resolver.resolve(conflict: Conflict(impl: conflict, collection: collection))?.impl
}
}
return c
}
func filter(push: Bool, collection: Collection) -> ((CBLDocument, CBLDocumentFlags) -> Bool)? {
guard let f = push ? self.pushFilter : self.pullFilter else {
return nil
}
return { (doc, flags) in
return f(Document(doc, collection: collection), DocumentFlags(rawValue: Int(flags.rawValue)))
}
}
}
| apache-2.0 |
ArnavChawla/InteliChat | Carthage/Checkouts/swift-sdk/Source/DiscoveryV1/Models/IndexCapacity.swift | 1 | 1462 | /**
* Copyright IBM Corporation 2018
*
* 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
/** Details about the resource usage and capacity of the environment. */
public struct IndexCapacity: Decodable {
/// Summary of the document usage statistics for the environment.
public var documents: EnvironmentDocuments?
/// Summary of the disk usage of the environment.
public var diskUsage: DiskUsage?
/// Summary of the collection usage in the environment.
public var collections: CollectionUsage?
/// **Deprecated**: Summary of the memory usage of the environment.
public var memoryUsage: MemoryUsage?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case documents = "documents"
case diskUsage = "disk_usage"
case collections = "collections"
case memoryUsage = "memory_usage"
}
}
| mit |
passt0r/MaliDeck | MaliDeck/TenThunders.swift | 1 | 363 | //
// TenThunders.swift
// MaliDeck
//
// Created by Dmytro Pasinchuk on 07.02.17.
// Copyright © 2017 Dmytro Pasinchuk. All rights reserved.
//
import Foundation
import UIKit
func prepareTenThunders() -> [Stats] {
var thunderMembers = [Stats]()
thunderMembers = prepareDownload(fraction: "Ten Thunders")
return thunderMembers
}
| gpl-3.0 |
Peekazoo/Peekazoo-iOS | Peekazoo/Peekazoo/AppDelegate.swift | 1 | 2335 | //
// AppDelegate.swift
// Peekazoo
//
// Created by Thomas Sherwood on 11/05/2017.
// Copyright © 2017 Peekazoo. All rights reserved.
//
import UIKit
@UIApplicationMain
public class AppDelegate: UIResponder, UIApplicationDelegate {
public var window: UIWindow? = UIWindow()
public var appFactory: AppFactory = PhoneAppFactory()
public var app: App?
public func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
app = appFactory.makeApplication(window: window!)
app?.launch()
return true
}
public 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.
}
public 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.
}
public 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.
}
public 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.
}
public func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| apache-2.0 |
adrfer/swift | validation-test/compiler_crashers_fixed/27732-swift-valuedecl-getinterfacetype.swift | 13 | 363 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let a{{
class B{
struct g{}struct g{
{
{}}func b{class A{{
}
struct Q{{}
{}func b{{p{}{
{
{}}typealias{{"
{
class A{enum B{
struct D{
var:{
for h={
| apache-2.0 |
bumpersfm/handy | Handy/UINavigationController.swift | 1 | 369 | //
// Created by Dani Postigo on 11/18/16.
//
import Foundation
import UIKit
extension UINavigationController {
public convenience init(rootViewController: UIViewController, navigationBarClass: AnyClass?) {
self.init(navigationBarClass: navigationBarClass, toolbarClass: nil)
self.setViewControllers([rootViewController], animated: false)
}
}
| mit |
jdkelley/Udacity-VirtualTourist | VirtualTourist/VirtualTourist/FlickrClient.swift | 1 | 7256 | //
// FlickrClient.swift
// VirtualTourist
//
// Created by Joshua Kelley on 10/19/16.
// Copyright © 2016 Joshua Kelley. All rights reserved.
//
import Foundation
import UIKit
class FlickrClient {
// MARK: - Singleton
/// A shared and threadsafe instance of FlickrClient
static let sharedInstance = FlickrClient()
private init() {}
// MARK: Search By Location
func imageSearchByLocation() {
// get lat and long
let lat = 36.2
let lon = 81.7
// get urls
taskForGet(latitude: lat, longitude: lon) { (data, error) in
if let error = error {
if error is ImageDownloadError {
} else if error is GetRequestError {
} else if error is URLRequestParseToJSONError {
}
} else {
guard let result = data as? [String: Any] else {
let notDictionary = FlickrDeserializationError(kind: .resultNotDictionary, message: "Results could not be cast as the expected JSON object.", data: data)
return
}
guard let photosObject = result[ResponseKeys.photos] as? [String: Any] else {
let noPhotosResult = FlickrDeserializationError(kind: .photosResultObjectNotResolvable, message: "Photos Object Does Not Exist.", data: result)
return
}
guard let photoArray = photosObject[ResponseKeys.photo] as? [[String: Any]] else {
let photoObjectArrayDNE = FlickrDeserializationError(kind: .photoDictionaryDoesNotExist, message: "Dictionary of photo objects does not exist.", data: photosObject)
return
}
let array: [String] = photoArray.flatMap {
guard let urlString = $0[FlickrClient.ResponseKeys.url_m] as? String else {
return nil
}
return urlString
}
// Do something with the array of urls
}
}
}
// MARK: Task For GET
func taskForGet(latitude: Double, longitude: Double, completionHandlerForGet: @escaping CompletionHandlerForGet) -> URLSessionDataTask {
let url = flickrUrl(latitude: latitude, longitude: longitude)
let request = URLRequest(url: url)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
guard error == nil else {
let getError = GetRequestError(kind: .errorInResponse, message: "There was an error with your request.", url: url.absoluteString, errorMessage: "\(error!)")
completionHandlerForGet(nil, getError)
return
}
guard let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode >= 200 && statusCode < 300 else {
let getError = GetRequestError(kind: .non200Response, message: "Request returned something other than a 2xx response.", url: url.absoluteString, errorMessage: "")
completionHandlerForGet(nil, getError)
return
}
guard let unwrappedData = data else {
let getError = GetRequestError(kind: .noData, message: "No Data was returned from your request!", url: url.absoluteString, errorMessage: "")
completionHandlerForGet(nil, getError)
return
}
self.convert(data: unwrappedData, with: completionHandlerForGet)
}
task.resume()
return task
}
func convert(data: Data, with: CompletionHandlerForGet) {
var parsedResult: Any!
do {
parsedResult = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
} catch {
let deserializeError = URLRequestParseToJSONError(kind: .unparsableToJSON, message: "Could not parse the data as JSON.", data: data)
with(nil, deserializeError)
return
}
with(parsedResult, nil)
}
func fetchImageFor(url: URL, completion: @escaping DownloadedImageHandler) {
}
}
// MARK: - Convenience
extension FlickrClient {
/// Builds a URL to request a latitude/longitude search from Flickr.
///
/// - parameter latitude: The latitude to search at.
/// - parameter longitude: The longitude to search at.
///
/// - returns: A valid URL.
fileprivate func flickrUrl(latitude: Double, longitude: Double) -> URL {
let parameters: [String: Any] = [
ParameterKeys.method : ParameterValues.searchMethod,
ParameterKeys.apiKey : AppConstants.FlickrAPIKey,
ParameterKeys.safeSearch : ParameterValues.safeSearch,
ParameterKeys.extras : ParameterValues.extras,
ParameterKeys.format : ParameterValues.format,
ParameterKeys.nojsoncallback : ParameterValues.nojsoncallback,
ParameterKeys.bbox : bboxString(latitude: latitude, longitude: longitude),
ParameterKeys.lat : latitude,
ParameterKeys.lon : longitude
]
return flickrUrlFrom(parameters: parameters)
}
/// Builds a valid `URL` instance from query parameters and url components.
///
/// - parameter parameters: This is a `[String: Any]` dictionary that holds the key-value pairs that will be `URLQueryItems`.
///
/// - returns: A valid URL.
fileprivate func flickrUrlFrom(parameters: [String: Any]) -> URL {
var components = URLComponents()
components.scheme = Constants.apiScheme
components.host = Constants.apiHost
components.path = Constants.apiPath
components.queryItems = [URLQueryItem]()
for (key, value) in parameters {
let queryItem = URLQueryItem(name: key, value: "\(value)")
components.queryItems!.append(queryItem)
}
return components.url!
}
/// `bboxString` creates a url-safe bounding box parameter.
///
/// - parameter latitude: The center coordinate's latitude of the bounding box
/// - parameter longitude: The center coordinate's longitude of the bounding box
///
/// - returns: A string describing the bounding box ready to be passed as a url parameter.
fileprivate func bboxString(latitude: Double, longitude: Double) -> String {
let minLon = max(longitude - Constants.searchBBoxHalfWidth, Constants.searchLonRange.0)
let minLat = max(latitude - Constants.searchBBoxHalfHeight,Constants.searchLatRange.0)
let maxLon = min(longitude + Constants.searchBBoxHalfWidth,Constants.searchLonRange.1)
let maxLat = min(latitude + Constants.searchBBoxHalfHeight, Constants.searchLatRange.1)
return "\(minLon),\(minLat),\(maxLon),\(maxLat)"
}
}
| mit |
slavapestov/swift | test/SILGen/writeback_conflict_diagnostics.swift | 7 | 4944 | // RUN: %target-swift-frontend %s -o /dev/null -emit-silgen -verify
struct MutatorStruct {
mutating func f(inout x : MutatorStruct) {}
}
var global_property : MutatorStruct { get {} set {} }
var global_int_property : Int {
get { return 42 }
set {}
}
struct StructWithProperty {
var computed_int : Int {
get { return 42 }
set {}
}
var stored_int = 0
var computed_struct : MutatorStruct { get {} set {} }
}
var global_struct_property : StructWithProperty
var c_global_struct_property : StructWithProperty { get {} set {} }
func testInOutAlias() {
var x = 42
swap(&x, // expected-note {{previous aliasing argument}}
&x) // expected-error {{inout arguments are not allowed to alias each other}}
swap(&global_struct_property, // expected-note {{previous aliasing argument}}
&global_struct_property) // expected-error {{inout arguments are not allowed to alias each other}}
}
func testWriteback() {
var a = StructWithProperty()
a.computed_struct . // expected-note {{concurrent writeback occurred here}}
f(&a.computed_struct) // expected-error {{inout writeback to computed property 'computed_struct' occurs in multiple arguments to call, introducing invalid aliasing}}
swap(&global_struct_property.stored_int,
&global_struct_property.stored_int) // ok
swap(&global_struct_property.computed_int, // expected-note {{concurrent writeback occurred here}}
&global_struct_property.computed_int) // expected-error {{inout writeback to computed property 'computed_int' occurs in multiple arguments to call, introducing invalid aliasing}}
swap(&a.computed_int, // expected-note {{concurrent writeback occurred here}}
&a.computed_int) // expected-error {{inout writeback to computed property 'computed_int' occurs in multiple arguments to call, introducing invalid aliasing}}
global_property.f(&global_property) // expected-error {{inout writeback to computed property 'global_property' occurs in multiple arguments to call, introducing invalid aliasing}} expected-note {{concurrent writeback occurred here}}
a.computed_struct.f(&a.computed_struct) // expected-error {{inout writeback to computed property 'computed_struct' occurs in multiple arguments to call, introducing invalid aliasing}} expected-note {{concurrent writeback occurred here}}
}
func testComputedStructWithProperty() {
swap(&c_global_struct_property.stored_int, &c_global_struct_property.stored_int) // expected-error {{inout writeback to computed property 'c_global_struct_property' occurs in multiple arguments to call, introducing invalid aliasing}} expected-note {{concurrent writeback occurred here}}
var c_local_struct_property : StructWithProperty { get {} set {} }
swap(&c_local_struct_property.stored_int, &c_local_struct_property.stored_int) // expected-error {{inout writeback to computed property 'c_local_struct_property' occurs in multiple arguments to call, introducing invalid aliasing}} expected-note {{concurrent writeback occurred here}}
swap(&c_local_struct_property.stored_int, &c_global_struct_property.stored_int) // ok
}
var global_array : [[Int]]
func testMultiArray(i : Int, j : Int, array : [[Int]]) {
var array = array
swap(&array[i][j],
&array[i][i])
swap(&array[0][j],
&array[0][i])
swap(&global_array[0][j],
&global_array[0][i])
// TODO: This is obviously the same writeback problem, but isn't detectable
// with the current level of sophistication in SILGen.
swap(&array[1+0][j], &array[1+0][i])
swap(&global_array[0][j], &array[j][i]) // ok
}
struct ArrayWithoutAddressors<T> {
subscript(i: Int) -> T {
get { return value }
set {}
}
var value: T
}
var global_array_without_addressors: ArrayWithoutAddressors<ArrayWithoutAddressors<Int>>
func testMultiArrayWithoutAddressors(
i: Int, j: Int, array: ArrayWithoutAddressors<ArrayWithoutAddressors<Int>>
) {
var array = array
swap(&array[i][j], // expected-note {{concurrent writeback occurred here}}
&array[i][i]) // expected-error {{inout writeback through subscript occurs in multiple arguments to call, introducing invalid aliasing}}
swap(&array[0][j], // expected-note {{concurrent writeback occurred here}}
&array[0][i]) // expected-error {{inout writeback through subscript occurs in multiple arguments to call, introducing invalid aliasing}}
swap(&global_array_without_addressors[0][j], // expected-note {{concurrent writeback occurred here}}
&global_array_without_addressors[0][i]) // expected-error {{inout writeback through subscript occurs in multiple arguments to call, introducing invalid aliasing}}
// TODO: This is obviously the same writeback problem, but isn't detectable
// with the current level of sophistication in SILGen.
swap(&array[1+0][j], &array[1+0][i])
swap(&global_array_without_addressors[0][j], &array[j][i]) // ok
}
| apache-2.0 |
ioscreator/ioscreator | IOS10FacebookTutorial/IOS10FacebookTutorial/ViewController.swift | 1 | 1221 | //
// ViewController.swift
// IOS10FacebookTutorial
//
// Created by Arthur Knopper on 25/04/2017.
// Copyright © 2017 Arthur Knopper. All rights reserved.
//
import UIKit
import Social
class ViewController: UIViewController {
@IBAction func postToFacebook(_ sender: Any) {
// 1
//if SLComposeViewController.isAvailableForServiceType(SLServiceTypeFacebook) {
if SLComposeViewController.isAvailable(forServiceType: SLServiceTypeFacebook) {
// 2
if let controller = SLComposeViewController(forServiceType: SLServiceTypeFacebook) {
// 3
controller.setInitialText("Testing Posting to Facebook")
// 4
self.present(controller, animated:true, completion:nil)
}
}
else {
// 3
print("no Facebook account found on device")
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
hayleyqinn/windWeather | 风生/WechatKit-master/WechatKit/Result.swift | 1 | 3507 | // Result.swift
//
// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
//
// 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
/**
Used to represent whether a request was successful or encountered an error.
- Success: The request and all post processing operations were successful resulting in the serialization of the
provided associated value.
- Failure: The request encountered an error resulting in a failure. The associated values are the original data
provided by the server as well as the error that caused the failure.
*/
public enum Result<Value, Error> {
case success(Value)
case failure(Error)
/// Returns `true` if the result is a success, `false` otherwise.
public var isSuccess: Bool {
switch self {
case .success:
return true
case .failure:
return false
}
}
/// Returns `true` if the result is a failure, `false` otherwise.
public var isFailure: Bool {
return !isSuccess
}
/// Returns the associated value if the result is a success, `nil` otherwise.
public var value: Value? {
switch self {
case .success(let value):
return value
case .failure:
return nil
}
}
/// Returns the associated error value if the result is a failure, `nil` otherwise.
public var error: Error? {
switch self {
case .success:
return nil
case .failure(let error):
return error
}
}
}
// MARK: - CustomStringConvertible
extension Result: CustomStringConvertible {
/// The textual representation used when written to an output stream, which includes whether the result was a
/// success or failure.
public var description: String {
switch self {
case .success:
return "SUCCESS"
case .failure:
return "FAILURE"
}
}
}
// MARK: - CustomDebugStringConvertible
extension Result: CustomDebugStringConvertible {
/// The debug textual representation used when written to an output stream, which includes whether the result was a
/// success or failure in addition to the value or error.
public var debugDescription: String {
switch self {
case .success(let value):
return "SUCCESS: \(value)"
case .failure(let error):
return "FAILURE: \(error)"
}
}
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.