repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
chris-al-brown/alchemy-csa | Demo.playground/Contents.swift | 1 | 3491 | // -----------------------------------------------------------------------------
// Copyright (c) 2016, Christopher A. Brown (chris-al-brown)
//
// 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.
//
// AlchemyCSA
// Demo.playground
// 06/29/2016
// -----------------------------------------------------------------------------
import Foundation
import AlchemyCSA
/// print a fasta record
func fastaPrint<T: Alphabet where T: CustomStringConvertible>(record: (String, [T?])?) -> String {
guard let record = record else {
return "..."
}
let header = record.0
let sequence = record.1.map {return $0?.description ?? "•"}
return ">\(header): \(sequence)"
}
/// stream an alignment as simple protein sequences
if let path = Bundle.main().pathForResource("small.aln", ofType:nil) {
var stream = try FastaStream<Protein>(open:path)
fastaPrint(record:stream.read())
fastaPrint(record:stream.read())
fastaPrint(record:stream.read())
fastaPrint(record:stream.read())
fastaPrint(record:stream.read())
fastaPrint(record:stream.read())
stream.reset()
fastaPrint(record:stream.read())
fastaPrint(record:stream.read())
fastaPrint(record:stream.read())
}
/// stream an alignment as aligned protein sequences
if let path = Bundle.main().pathForResource("small.aln", ofType:nil) {
var stream = try FastaStream<Gapped<Protein>>(open:path)
fastaPrint(record:stream.read())
fastaPrint(record:stream.read())
fastaPrint(record:stream.read())
fastaPrint(record:stream.read())
fastaPrint(record:stream.read())
fastaPrint(record:stream.read())
stream.reset()
fastaPrint(record:stream.read())
fastaPrint(record:stream.read())
fastaPrint(record:stream.read())
}
/// stream an alignment as aligned protein sequences
if let path = Bundle.main().pathForResource("small.aln", ofType:nil) {
var alignment = try Alignment<Protein>(open:path)
let rowBased = alignment
alignment.memoryLayout = .column
let colBased = alignment
rowBased[0, 1]
colBased[0, 1]
rowBased[0, 1] == colBased[0, 1]
rowBased.memoryLayout == colBased.memoryLayout
rowBased["sequence1"]
colBased["sequence1"]
rowBased["sequence1"]! == colBased["sequence1"]!
rowBased.row(at:1)
colBased.row(at:1)
rowBased.row(at:1) == colBased.row(at:1)
rowBased.column(at:1)
colBased.column(at:1)
rowBased.column(at:1) == colBased.column(at:1)
}
| mit | ac6872b51d958f7ad2dba3e51db1758c | 35.726316 | 98 | 0.674692 | 3.929054 | false | false | false | false |
steve-holmes/music-app-2 | MusicApp/Modules/Player/PlayerModule.swift | 1 | 4454 | //
// PlayerModule.swift
// MusicApp
//
// Created by Hưng Đỗ on 6/9/17.
// Copyright © 2017 HungDo. All rights reserved.
//
import Swinject
class PlayerModule: Module {
override func register() {
// MARK: Controllers
container.register(PlayerViewController.self) { resolver in
let controller = UIStoryboard.player.controller(of: PlayerViewController.self)
controller.store = resolver.resolve(PlayerStore.self)!
controller.action = resolver.resolve(PlayerAction.self)!
controller.controllers = [
resolver.resolve(ListPlayerViewController.self)!,
resolver.resolve(InformationPlayerViewController.self)!,
resolver.resolve(LyricPlayerViewController.self)!
]
controller.timer = resolver.resolve(PlayerTimer.self)!
return controller
}
container.register(ListPlayerViewController.self) { resolver in
let controller = UIStoryboard.player.controller(of: ListPlayerViewController.self)
controller.store = resolver.resolve(PlayerStore.self)!
controller.action = resolver.resolve(PlayerAction.self)!
return controller
}
container.register(InformationPlayerViewController.self) { resolver in
let controller = UIStoryboard.player.controller(of: InformationPlayerViewController.self)
controller.store = resolver.resolve(PlayerStore.self)!
controller.action = resolver.resolve(PlayerAction.self)!
return controller
}
container.register(LyricPlayerViewController.self) { resolver in
let controller = UIStoryboard.player.controller(of: LyricPlayerViewController.self)
controller.store = resolver.resolve(PlayerStore.self)!
controller.action = resolver.resolve(PlayerAction.self)!
controller.lyricStore = resolver.resolve(LyricStore.self)!
controller.lyricAction = resolver.resolve(LyricAction.self)!
return controller
}
container.register(PlayerStore.self) { resolver in
return MAPlayerStore()
}
container.register(PlayerAction.self) { resolver in
return MAPlayerAction(
store: resolver.resolve(PlayerStore.self)!,
service: resolver.resolve(PlayerService.self)!
)
}
container.register(LyricStore.self) { resolver in
return MALyricStore()
}
container.register(LyricAction.self) { resolver in
return MALyricAction(
store: resolver.resolve(LyricStore.self)!,
service: resolver.resolve(LyricService.self)!
)
}
// MARK: Domain Models
container.register(PlayerService.self) { resolver in
return MAPlayerService(
notification: resolver.resolve(PlayerNotification.self)!,
timerCoordinator: resolver.resolve(PlayerTimerCoordinator.self)!
)
}
container.register(LyricService.self) { resolver in
return MALyricService(
repository: resolver.resolve(LyricRepository.self)!
)
}
container.register(PlayerNotification.self) { resolver in
return MAPlayerNotification()
}
container.register(PlayerTimerCoordinator.self) { resolver in
return MAPlayerTimerCoordinator()
}
container.register(PlayerTimer.self) { resolver in
return MAPlayerTimer()
}.initCompleted { resolver, timer in
let timer = timer as! MAPlayerTimer
timer.action = resolver.resolve(PlayerAction.self)!
timer.controller = resolver.resolve(PlayerViewController.self)!
}
container.register(LyricRepository.self) { resolver in
return MALyricRepository(
loader: resolver.resolve(LyricLoader.self)!
)
}
container.register(LyricLoader.self) { resolver in
return MALyricLoader()
}
}
}
| mit | 8c10ede0a2f2c8578e36769ea4b764fa | 33.757813 | 101 | 0.589346 | 5.56821 | false | false | false | false |
queueit/QueueIT.iOS.Sdk | QueueItSDK/QueueITEngine.swift | 1 | 8364 | import Foundation
public class QueueITEngine {
let MAX_RETRY_SEC = 10
let INITIAL_WAIT_RETRY_SEC = 1
var customerId: String
var eventId: String
var configId: String
var layoutName: String
var language: String
var widgets = [WidgetRequest]()
var deltaSec: Int
var onQueueItemAssigned: (QueueItemDetails) -> Void
var onQueuePassed: () -> Void
var onPostQueue: () -> Void
var onIdleQueue: () -> Void
var onWidgetChanged: (WidgetDetails) -> Void
var onQueueIdRejected: (String) -> Void
var onQueueItError: (String) -> Void
public init(customerId: String, eventId: String, configId: String, widgets:WidgetRequest ..., layoutName: String, language: String,
onQueueItemAssigned: @escaping (_ queueItemDetails: QueueItemDetails) -> Void,
onQueuePassed: @escaping () -> Void,
onPostQueue: @escaping () -> Void,
onIdleQueue: @escaping () -> Void,
onWidgetChanged: @escaping(WidgetDetails) -> Void,
onQueueIdRejected: @escaping(String) -> Void,
onQueueItError: @escaping(String) -> Void) {
self.deltaSec = self.INITIAL_WAIT_RETRY_SEC
self.customerId = customerId
self.eventId = eventId
self.configId = configId
self.layoutName = layoutName
self.language = language
self.onQueueItemAssigned = onQueueItemAssigned
self.onQueuePassed = onQueuePassed
self.onPostQueue = onPostQueue
self.onIdleQueue = onIdleQueue
self.onWidgetChanged = onWidgetChanged
self.onQueueIdRejected = onQueueIdRejected
self.onQueueItError = onQueueItError
for w in widgets {
self.widgets.append(w)
}
QueueCache.sharedInstance.initialize(customerId, eventId)
}
public func run() {
if isInSession(tryExtendSession: true) {
onQueuePassed()
} else if isWithinQueueIdSession() {
if ensureConnected() {
checkStatus()
}
} else if ensureConnected() {
enqueue()
}
}
func ensureConnected() -> Bool {
var count = 0;
while count < 5
{
if !iOSUtils.isInternetAvailable()
{
sleep(1)
count += 1
}
else
{
return true
}
}
self.onQueueItError("No internet connection!")
return false
}
func isWithinQueueIdSession() -> Bool {
let cache = QueueCache.sharedInstance
if cache.getQueueIdTtl() != nil {
let currentTime = Date()
let queueIdTtl = Date(timeIntervalSince1970: Double(cache.getQueueIdTtl()!))
if currentTime < queueIdTtl {
return true
}
}
return false
}
func isInSession(tryExtendSession: Bool) -> Bool {
let cache = QueueCache.sharedInstance
if cache.getRedirectId() != nil {
let currentDate = Date()
let sessionDate = Date(timeIntervalSince1970: Double(cache.getSessionTtl()!))
if currentDate < sessionDate {
if tryExtendSession {
let isExtendSession = cache.getExtendSession()
if isExtendSession != nil {
cache.setSessionTtl(currentTimeUnixUtil() + cache.getSessionTtlDelta()!)
}
}
return true
}
}
return false
}
func enqueue() {
QueueService.sharedInstance.enqueue(self.customerId, self.eventId, self.configId, layoutName: nil, language: nil,
success: { (enqueueDto) -> Void in
self.onEnqueueSuccess(enqueueDto)
},
failure: { (errorMessage, errorStatusCode) -> Void in
self.onEnqueueFailed(errorMessage, errorStatusCode)
})
}
func onEnqueueSuccess(_ enqueueDto: EnqueueDTO) {
self.resetDeltaSec()
let redirectInfo = enqueueDto.redirectDto
if redirectInfo != nil {
self.handleQueuePassed(redirectInfo!)
} else {
let eventState = enqueueDto.eventDetails.state
if eventState == .queue || eventState == .prequeue {
self.handleQueueIdAssigned(enqueueDto.queueIdDto!, enqueueDto.eventDetails)
self.checkStatus()
} else if eventState == .postqueue {
self.onPostQueue()
} else if eventState == .idle {
self.onIdleQueue()
}
}
}
func handleQueueIdAssigned(_ queueIdInfo: QueueIdDTO, _ eventDetails: EventDTO) {
let cache = QueueCache.sharedInstance
cache.setQueueId(queueIdInfo.queueId)
cache.setQueueIdTtl(queueIdInfo.ttl + currentTimeUnixUtil())
self.onQueueItemAssigned(QueueItemDetails(queueIdInfo.queueId, eventDetails))
}
func checkStatus() {
let queueId = QueueCache.sharedInstance.getQueueId()!
QueueService.sharedInstance.getStatus(self.customerId, self.eventId, queueId, self.configId, self.widgets, onGetStatus: (onGetStatusSuccess), onFailed: (onGetStatusFailed))
}
func onGetStatusSuccess(statusDto: StatusDTO) {
self.resetDeltaSec()
if statusDto.widgets != nil {
self.handleWidgets(statusDto.widgets!)
}
if statusDto.rejectDto != nil {
self.handleQueueIdRejected((statusDto.rejectDto?.reason)!)
}
else if statusDto.redirectDto != nil {
self.handleQueuePassed(statusDto.redirectDto!)
}
else if statusDto.eventDetails?.state == .postqueue {
self.onPostQueue()
}
else {
let delaySec = statusDto.nextCallMSec / 1000
self.executeWithDelay(delaySec, self.checkStatus)
}
}
func onGetStatusFailed(errorMessage: String) {
if ensureConnected() {
self.retryMonitor(self.checkStatus, errorMessage)
}
}
func handleWidgets(_ widgets: [WidgetDTO]) {
let cache = QueueCache.sharedInstance
for widget in widgets {
if cache.widgetExist(widget.name) {
let checksumFromCache = cache.getWidgets()?[widget.name]
if checksumFromCache != widget.checksum {
cache.addOrUpdateWidget(widget)
self.onWidgetChanged(WidgetDetails(widget.name, widget.data))
}
} else {
cache.addOrUpdateWidget(widget)
self.onWidgetChanged(WidgetDetails(widget.name, widget.data))
}
}
}
func handleQueueIdRejected(_ reason: String) {
self.onQueueIdRejected(reason)
QueueCache.sharedInstance.clear()
}
func handleQueuePassed(_ redirectInfo: RedirectDTO) {
let cache = QueueCache.sharedInstance
cache.clear()
cache.setRedirectId(redirectInfo.redirectId)
cache.setSessionTtlDelta(redirectInfo.ttl)
cache.setSessionTtl(redirectInfo.ttl + currentTimeUnixUtil())
cache.setExtendSession(redirectInfo.extendTtl)
self.onQueuePassed()
}
func currentTimeUnixUtil() -> Int64 {
let val = Int64(NSDate().timeIntervalSince1970)
return val
}
func executeWithDelay(_ delaySec: Int, _ action: @escaping () -> ()) {
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(delaySec), execute: {
action()
})
}
func resetDeltaSec() {
self.deltaSec = self.INITIAL_WAIT_RETRY_SEC
}
func retryMonitor(_ action: @escaping () -> Void, _ errorMessage: String) {
if self.deltaSec < MAX_RETRY_SEC
{
executeWithDelay(self.deltaSec, action)
self.deltaSec = self.deltaSec * 2;
} else {
self.onQueueItError(errorMessage)
}
}
func onEnqueueFailed(_ message: String, _ errorStatusCode: Int) {
if errorStatusCode >= 400 && errorStatusCode < 500
{
self.onQueueItError(message)
} else if errorStatusCode >= 500 {
self.retryMonitor(self.enqueue, message)
}
}
}
| lgpl-3.0 | a4fd0a6bf989a1b1e7201f9a3610170e | 33.705394 | 180 | 0.587398 | 4.613348 | false | false | false | false |
Syerram/asphalos | asphalos/DataManager.swift | 1 | 4065 | //
// DataManager.swift
// asphalos
//
// Created by Saikiran Yerram on 12/28/14.
// Copyright (c) 2014 Blackhorn. All rights reserved.
//
import Foundation
import UIKit
import CoreData
extension NSManagedObject {
///Save all of the changes
class func save() {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.saveContext()
}
class func managedObjectContext() -> NSManagedObjectContext? {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
if let managedObjContext = appDelegate.managedObjectContext {
return managedObjContext
} else {
return nil
}
}
///Calling this method will delete the object and commit changes.
///@warning: If you have any other changes in the context, those will be committed as well
class func deleteNow(managedObject:NSManagedObject) {
NSManagedObject.managedObjectContext()?.deleteObject(managedObject)
NSManagedObject.save()
}
///Remove all of the records for the given entities
class func purge(entityNames: [String]) {
var isDirty = false
for entityName in entityNames {
let fetchRequest = NSFetchRequest(entityName: entityName)
fetchRequest.includesPropertyValues = false
fetchRequest.includesSubentities = false
if let results = NSManagedObject.managedObjectContext()!.executeFetchRequest(fetchRequest, error: nil) as? [NSManagedObject] {
for result in results {
NSManagedObject.managedObjectContext()?.deleteObject(result)
isDirty = true
}
}
}
if isDirty {
NSManagedObject.save()
NSManagedObject.managedObjectContext()?.reset()
}
}
///New entity
class func newEntity<T>(entityName:String) -> T {
return NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: self.managedObjectContext()!) as! T
}
///Prepare sort descriptors for list of tuples with key, ascending order
class func prepareSortDescriptors(sortKeys:[(String, Bool)]) -> [NSSortDescriptor]{
var sortDescriptors:[NSSortDescriptor] = []
for (key, ascending) in sortKeys {
sortDescriptors.append(NSSortDescriptor(key: key, ascending: ascending))
}
return sortDescriptors
}
///Return all objects of the given entity
class func fetchAll(entityName:String, sortKeys:[(String, Bool)]? = nil) -> [NSManagedObject] {
let fetchRequest = NSFetchRequest(entityName: entityName)
if let _sortKeys = sortKeys {
fetchRequest.sortDescriptors = self.prepareSortDescriptors(_sortKeys)
}
if let fetchResults = NSManagedObject.managedObjectContext()!.executeFetchRequest(fetchRequest, error: nil) as? [NSManagedObject] {
return fetchResults
} else {
return []
}
}
///Return specific objects for the given predicate
class func fetch(entityName:String, sortKeys:[(String, Bool)]? = nil, predicates:() -> NSPredicate) -> [NSManagedObject] {
let fetchRequest = NSFetchRequest(entityName: entityName)
fetchRequest.predicate = predicates()
if let _sortKeys = sortKeys {
fetchRequest.sortDescriptors = self.prepareSortDescriptors(_sortKeys)
}
if let fetchResults = NSManagedObject.managedObjectContext()!.executeFetchRequest(fetchRequest, error: nil) as? [NSManagedObject] {
return fetchResults
} else {
return []
}
}
///Provide count of objects for the given predicate
class func count(entityName:String, predicates:() -> NSPredicate) -> Int {
let fetchRequest = NSFetchRequest(entityName: entityName)
fetchRequest.predicate = predicates()
return NSManagedObject.managedObjectContext()!.countForFetchRequest(fetchRequest, error: nil)
}
} | mit | 12a84f71c7013160302481e9495b3979 | 37.358491 | 139 | 0.662485 | 5.553279 | false | false | false | false |
lyimin/EyepetizerApp | EyepetizerApp/EyepetizerApp/Constant/EYEConstant.swift | 1 | 1229 | //
// EYEConstant.swift
// EyepetizerApp
//
// Created by 梁亦明 on 16/3/11.
// Copyright © 2016年 xiaoming. All rights reserved.
//
import UIKit
struct UIConstant {
// 屏幕宽高
static let IPHONE6_WIDTH : CGFloat = 375
static let IPHONE6_HEIGHT : CGFloat = 667
static let IPHONE5_WIDTH : CGFloat = 320
static let IPHONE5_HEIGHT : CGFloat = 568
static let SCREEN_WIDTH : CGFloat = UIScreen.mainScreen().bounds.width
static let SCREEN_HEIGHT : CGFloat = UIScreen.mainScreen().bounds.height
// 导航栏高度
static let UI_NAV_HEIGHT : CGFloat = 64
// tab高度
static let UI_TAB_HEIGHT : CGFloat = 49
// 周排行-月排行-总排行高度
static let UI_CHARTS_HEIGHT : CGFloat = 50
// 字体
static let UI_FONT_12 : CGFloat = 12
static let UI_FONT_13 : CGFloat = 13
static let UI_FONT_14 : CGFloat = 14
static let UI_FONT_16 : CGFloat = 16
static let UI_FONT_20 : CGFloat = 20
// 间距
static let UI_MARGIN_5 : CGFloat = 5
static let UI_MARGIN_10 : CGFloat = 10
static let UI_MARGIN_15 : CGFloat = 15
static let UI_MARGIN_20 : CGFloat = 20
}
struct KeysConstant {
static let launchImgKey = "launchImgKey"
}
| mit | 825c8bf06b4a12bb267ce80637901844 | 27.487805 | 76 | 0.65411 | 3.518072 | false | false | false | false |
pennlabs/penn-mobile-ios | PennMobile/GSR-Booking/Model/GSRGroupUser.swift | 1 | 984 | //
// GSRGroupUser.swift
// PennMobile
//
// Created by Daniel Salib on 11/8/19.
// Copyright © 2019 PennLabs. All rights reserved.
//
import Foundation
struct GSRGroupUser: Decodable {
let pennkey: String!
let groups: [GSRGroup]?
enum CodingKeys: String, CodingKey {
case pennkey = "username"
case groups = "booking_groups"
}
}
struct GSRInviteSearchResult: Codable, Equatable, Comparable {
let first: String?
let last: String?
let email: String?
let pennkey: String
static func == (lhs: GSRInviteSearchResult, rhs: GSRInviteSearchResult) -> Bool {
return lhs.pennkey == rhs.pennkey
}
static func == (lhs: GSRInviteSearchResult, rhs: GSRGroupMember) -> Bool {
return lhs.pennkey == rhs.pennKey
}
static func < (lhs: GSRInviteSearchResult, rhs: GSRInviteSearchResult) -> Bool {
return lhs.pennkey < rhs.pennkey
}
}
typealias GSRInviteSearchResults = [GSRInviteSearchResult]
| mit | 1fe32458993471b0f91acff2e459d443 | 22.97561 | 85 | 0.669379 | 3.766284 | false | false | false | false |
lucasmpaim/LPaimiOSUtils | Pod/Classes/LPaimUtilsImages.swift | 1 | 2894 | //
// Images.swift
// LPaimUtils
//
// Created by LPaimUtils on 21/03/15.
// Copyright (c) 2015 LPaimUtils. All rights reserved.
//
import Foundation
enum SuportedImages{
case PNG, JPEG
}
class LPaimUtilsImages{
/**
Generate UIImage with a BezierPath
Obs: Don't call .setStroke or .stroke methods
*/
class func GenerateImageWithBezierPath(draws : [UIBezierPath : UIColor]) -> UIImage?{
func calculateSize() -> CGSize{
var size = CGSize(width: 0, height: 0)
for draw in draws{
size.height += draw.0.bounds.height
size.width += draw.0.bounds.width
}
return size
}
var size = calculateSize()
UIGraphicsBeginImageContext(size)
let context = UIGraphicsGetCurrentContext()
for draw in draws{
draw.1.setStroke()
draw.0.stroke()
}
var colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return colorImage
}
/**
Save the image in the app path
:param: image The UIImage to save in app path
:param: name The name of file - Don't include the extension
:type: The type of image
*/
class func SaveImage(var #image: UIImage, var name:String ,var type: SuportedImages){
var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as! NSString
if(type == SuportedImages.PNG){
var data = UIImagePNGRepresentation(image)
var filePath = paths.stringByAppendingPathComponent("\(name).wai")
NSFileManager.defaultManager().createFileAtPath(filePath, contents: data, attributes: nil)
}else{
var data = UIImageJPEGRepresentation(image, 1.0)
var filePath = paths.stringByAppendingPathComponent("\(name).wai")
NSFileManager.defaultManager().createFileAtPath(filePath, contents: data, attributes: nil)
}
}
/**
Load one image saved in app path
:param: name the name of file - Don't include the extension
:returns: the image
*/
class func LoadImage(var #name:String) -> UIImage?{
var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as! NSString
var imagem: UIImage?
var filePath: String = paths.stringByAppendingPathComponent("\(name).wai")
var data = NSData(contentsOfFile: filePath)
if(data != nil && data?.length > 0){
imagem = UIImage(data: data!)!
}
return imagem
}
} | mit | ab7c808586c95b80980eac933cbee877 | 28.242424 | 157 | 0.599171 | 5.167857 | false | false | false | false |
IBM-Swift/Kitura | Sources/Kitura/CodableRouter+TypeSafeMiddleware.swift | 1 | 115917 | /*
* 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
import LoggerAPI
import KituraNet
import KituraContracts
// Type-safe middleware Codable router
extension Router {
// MARK: Codable Routing with TypeSafeMiddleware
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User`, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.get("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3,
respondWith: (User?, RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware instance and returns a single Codable object or a RequestError.
*/
public func get<T: TypeSafeMiddleware, O: Codable>(
_ route: String,
handler: @escaping (T, @escaping CodableResultClosure<O>) -> Void
) {
registerGetRoute(route: route, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET(Single) typed middleware request")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
handler(typeSafeMiddleware, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User`, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, middle2: Middle2, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives two TypeSafeMiddleware instances and returns a single Codable object or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, @escaping CodableResultClosure<O>) -> Void
) {
registerGetRoute(route: route, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET(Single) typed middleware request")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User`, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives three TypeSafeMiddleware instances and returns a single Codable object or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, T3, @escaping CodableResultClosure<O>) -> Void
) {
registerGetRoute(route: route, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET(Single) typed middleware request")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`
and a handler which responds with an array of Codable objects or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User` array, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, respondWith: ([User]?, RequestError?) -> Void) in
guard let user: [User] = session.user else {
return respondWith(nil, .notFound)
}
respondWith([user], nil)
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.get("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3,
respondWith: ([User]?, RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware instance and returns an array of Codable objects or a RequestError.
*/
public func get<T: TypeSafeMiddleware, O: Codable>(
_ route: String,
handler: @escaping (T, @escaping CodableArrayResultClosure<O>) -> Void
) {
registerGetRoute(route: route, outputType: O.self, outputIsArray: true)
get(route) { request, response, next in
Log.verbose("Received GET(Array) typed middleware request")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
handler(typeSafeMiddleware, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`
and a handler which responds with an array of Codable objects or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User` array, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, middle2: Middle2, respondWith: ([User]?, RequestError?) -> Void) in
guard let user: [User] = session.user else {
return respondWith(nil, .notFound)
}
respondWith([user], nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives two TypeSafeMiddleware instances and returns an array of Codable objects or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, @escaping CodableArrayResultClosure<O>) -> Void
) {
registerGetRoute(route: route, outputType: O.self, outputIsArray: true)
get(route) { request, response, next in
Log.verbose("Received GET(Array) typed middleware request")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`
and a handler which responds with an array of Codable objects or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User` array, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, respondWith: ([User]?, RequestError?) -> Void) in
guard let user: [User] = session.user else {
return respondWith(nil, .notFound)
}
respondWith([user], nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives three TypeSafeMiddleware instances and returns an array of Codable objects or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, T3, @escaping CodableArrayResultClosure<O>) -> Void
) {
registerGetRoute(route: route, outputType: O.self, outputIsArray: true)
get(route) { request, response, next in
Log.verbose("Received GET(Array) typed middleware request")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`, an `Identifier`
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, id: Int, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user[id] else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.get("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3, id: Int,
respondWith: (User?, RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware instance and an Identifier, and returns a single of Codable object or a RequestError.
*/
public func get<T: TypeSafeMiddleware, Id: Identifier, O: Codable>(
_ route: String,
handler: @escaping (T, Id, @escaping CodableResultClosure<O>) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerGetRoute(route: route, id: Id.self, outputType: O.self)
get(appendId(path: route)) { request, response, next in
Log.verbose("Received GET (singular with identifier and middleware) type-safe request")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response) else {
return next()
}
handler(typeSafeMiddleware, identifier, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`, an identifier
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, middle2: Middle2, id: Int, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user[id] else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives two TypeSafeMiddleware instances and an Identifier, and returns a single of Codable object or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, Id: Identifier, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, Id, @escaping CodableResultClosure<O>) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerGetRoute(route: route, id: Id.self, outputType: O.self)
get(appendId(path: route)) { request, response, next in
Log.verbose("Received GET (singular with identifier and middleware) type-safe request")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response) else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, identifier, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`, an identifier
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, rid: Int, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user[id] else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives three TypeSafeMiddleware instances and an Identifier, and returns a single of Codable object or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, Id: Identifier, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, T3, Id, @escaping CodableResultClosure<O>) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerGetRoute(route: route, id: Id.self, outputType: O.self)
get(appendId(path: route)) { request, response, next in
Log.verbose("Received GET (singular with identifier and middleware) type-safe request")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response) else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, identifier, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`
and a handler which responds with an array of (`Identifier`, Codable) tuples or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [(Int, User)] dictionary, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, respondWith: ([(Int, User)]?, RequestError?) -> Void) in
guard let users: [(Int, User)] = session.users else {
return respondWith(nil, .notFound)
}
respondWith(users, nil)
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.get("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3, id: Int,
respondWith: ([(Int, User)]?, RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware instance, and returns an array of (Identifier, Codable) tuples or a RequestError.
*/
public func get<T: TypeSafeMiddleware, Id: Identifier, O: Codable>(
_ route: String,
handler: @escaping (T, @escaping IdentifierCodableArrayResultClosure<Id, O>) -> Void
) {
registerGetRoute(route: route, id: Id.self, outputType: O.self, outputIsArray: true)
get(route) { request, response, next in
Log.verbose("Received GET(Array) with identifier typed middleware request")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
handler(typeSafeMiddleware, CodableHelpers.constructTupleArrayOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`
and a handler which responds with an array of (`Identifier`, Codable) tuples or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [(Int, User)] dictionary, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, middle2: Middle2, respondWith: ([(Int, User)]?, RequestError?) -> Void) in
guard let users: [(Int, User)] = session.users else {
return respondWith(nil, .notFound)
}
respondWith(users, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives two TypeSafeMiddleware instances, and returns an array of (Identifier, Codable) tuples or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, Id: Identifier, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, @escaping IdentifierCodableArrayResultClosure<Id, O>) -> Void
) {
registerGetRoute(route: route, id: Id.self, outputType: O.self, outputIsArray: true)
get(route) { request, response, next in
Log.verbose("Received GET(Array) with identifier typed middleware request")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, CodableHelpers.constructTupleArrayOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`
and a handler which responds with an array of (`Identifier`, Codable) tuples or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [(Int, User)] dictionary, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, respondWith: ([(Int, User)]?, RequestError?) -> Void) in
guard let users: [(Int, User)] = session.users else {
return respondWith(nil, .notFound)
}
respondWith(users, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives three TypeSafeMiddleware instances, and returns an array of (Identifier, Codable) tuples or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, Id: Identifier, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, T3, @escaping IdentifierCodableArrayResultClosure<Id, O>) -> Void
) {
registerGetRoute(route: route, id: Id.self, outputType: O.self, outputIsArray: true)
get(route) { request, response, next in
Log.verbose("Received GET(Array) with identifier typed middleware request")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, CodableHelpers.constructTupleArrayOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
struct Query: QueryParams {
let id: Int
}
router.get("/user") { (session: MySession, query: Query, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user[query.id] else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.get("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3, query: Query,
respondWith: (User?, RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware instance and a QueryParams instance, and returns a single of Codable object or a RequestError.
*/
public func get<T: TypeSafeMiddleware, Q: QueryParams, O: Codable>(
_ route: String,
handler: @escaping (T, Q, @escaping CodableResultClosure<O>) -> Void
) {
registerGetRoute(route: route, queryParams: Q.self, optionalQParam: false, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET (singular) type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
// Define result handler
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
do {
let query: Q = try QueryDecoder(dictionary: request.queryParameters).decode(Q.self)
handler(typeSafeMiddleware, query, CodableHelpers.constructOutResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
struct Query: QueryParams {
let id: Int
}
router.get("/user") { (session: MySession, middle2: Middle2, query: Query, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user[query.id] else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives two TypeSafeMiddleware instances and a QueryParams instance, and returns a single of Codable object or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, Q: QueryParams, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, Q, @escaping CodableResultClosure<O>) -> Void
) {
registerGetRoute(route: route, queryParams: Q.self, optionalQParam: false, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET (singular) type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
// Define result handler
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
do {
let query: Q = try QueryDecoder(dictionary: request.queryParameters).decode(Q.self)
handler(typeSafeMiddleware1, typeSafeMiddleware2, query, CodableHelpers.constructOutResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
struct Query: QueryParams {
let id: Int
}
router.get("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, rquery: Query, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user[query.id] else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives three TypeSafeMiddleware instances and a QueryParams instance, and returns a single of Codable object or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, Q: QueryParams, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, T3, Q, @escaping CodableResultClosure<O>) -> Void
) {
registerGetRoute(route: route, queryParams: Q.self, optionalQParam: false, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET (singular) type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
// Define result handler
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
do {
let query: Q = try QueryDecoder(dictionary: request.queryParameters).decode(Q.self)
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, query, CodableHelpers.constructOutResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with an array of Codable objects or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: [User]] dictionary, where `User` conforms to Codable.
```swift
struct Query: QueryParams {
let id: Int
}
router.get("/user") { (session: MySession, query: Query, respondWith: ([User]?, RequestError?) -> Void) in
guard let user: [User] = session.user[query.id] else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.get("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3, query: Query,
respondWith: ([User]?, RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware instance and a QueryParams instance, and returns an array of Codable objects or a RequestError.
*/
public func get<T: TypeSafeMiddleware, Q: QueryParams, O: Codable>(
_ route: String,
handler: @escaping (T, Q, @escaping CodableArrayResultClosure<O>) -> Void
) {
registerGetRoute(route: route, queryParams: Q.self, optionalQParam: false, outputType: O.self, outputIsArray: true)
get(route) { request, response, next in
Log.verbose("Received GET (plural) type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
do {
let query: Q = try QueryDecoder(dictionary: request.queryParameters).decode(Q.self)
handler(typeSafeMiddleware, query, CodableHelpers.constructOutResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with an array of Codable objects or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MyHTTPAuth` is a struct that conforms to the `TypeSafeHTTPBasic` protocol from `Kitura-CredentialsHTTP` to provide basic HTTP authentication.
```swift
struct Query: QueryParams {
let id: Int
}
router.get("/user") { (auth: MyHTTPAuth, query: Query?, respondWith: ([User]?, RequestError?) -> Void) in
if let query = query {
let matchedUsers = userArray.filter { $0.id <= query.id }
return respondWith(matchedUsers, nil)
} else {
respondWith(userArray, nil)
}
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.get("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3, query: Query,
respondWith: ([User]?, RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware instance and a QueryParams instance, and returns an array of Codable objects or a RequestError.
*/
public func get<T: TypeSafeMiddleware, Q: QueryParams, O: Codable>(
_ route: String,
handler: @escaping (T, Q?, @escaping CodableArrayResultClosure<O>) -> Void
) {
registerGetRoute(route: route, queryParams: Q.self, optionalQParam: true, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET (plural) type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
do {
var query: Q? = nil
let queryParameters = request.queryParameters
if queryParameters.count > 0 {
query = try QueryDecoder(dictionary: queryParameters).decode(Q.self)
}
handler(typeSafeMiddleware, query, CodableHelpers.constructOutResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with an array of Codable objects or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: [User]] dictionary, where `User` conforms to Codable.
```swift
struct Query: QueryParams {
let id: Int
}
router.get("/user") { (session: MySession, middle2: Middle2, query: Query, respondWith: ([User]?, RequestError?) -> Void) in
guard let user: [User] = session.user[query.id] else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives two TypeSafeMiddleware instances and a QueryParams instance, and returns an array of Codable objects or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, Q: QueryParams, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, Q, @escaping CodableArrayResultClosure<O>) -> Void
) {
registerGetRoute(route: route, queryParams: Q.self, optionalQParam: false, outputType: O.self, outputIsArray: true)
get(route) { request, response, next in
Log.verbose("Received GET (plural) type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
do {
let query: Q = try QueryDecoder(dictionary: request.queryParameters).decode(Q.self)
handler(typeSafeMiddleware1, typeSafeMiddleware2, query, CodableHelpers.constructOutResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with an array of Codable objects or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MyHTTPAuth` is a struct that conforms to the `TypeSafeHTTPBasic` protocol from `Kitura-CredentialsHTTP` to provide basic HTTP authentication.
```swift
struct Query: QueryParams {
let id: Int
}
router.get("/user") { (auth: MyHTTPAuth, middle2: Middle2, query: Query?, respondWith: ([User]?, RequestError?) -> Void) in
if let query = query {
let matchedUsers = userArray.filter { $0.id <= query.id }
return respondWith(matchedUsers, nil)
} else {
return respondWith(userArray, nil)
}
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives two TypeSafeMiddleware instances and a QueryParams instance, and returns an array of Codable objects or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, Q: QueryParams, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, Q?, @escaping CodableArrayResultClosure<O>) -> Void
) {
registerGetRoute(route: route, queryParams: Q.self, optionalQParam: true, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET (plural) type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
do {
var query: Q? = nil
let queryParameters = request.queryParameters
if queryParameters.count > 0 {
query = try QueryDecoder(dictionary: queryParameters).decode(Q.self)
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, query, CodableHelpers.constructOutResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with an array of Codable objects or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: [User]] dictionary, where `User` conforms to Codable.
```swift
struct Query: QueryParams {
let id: Int
}
router.get("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, query: Query, respondWith: ([User]?, RequestError?) -> Void) in
guard let user: [User] = session.user[query.id] else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives three TypeSafeMiddleware instances and a QueryParams instance, and returns an array of Codable objects or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, Q: QueryParams, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, T3, Q, @escaping CodableArrayResultClosure<O>) -> Void
) {
registerGetRoute(route: route, queryParams: Q.self, optionalQParam: false, outputType: O.self, outputIsArray: true)
get(route) { request, response, next in
Log.verbose("Received GET (plural) type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
do {
let query: Q = try QueryDecoder(dictionary: request.queryParameters).decode(Q.self)
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, query, CodableHelpers.constructOutResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with an array of Codable objects or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MyHTTPAuth` is a struct that conforms to the `TypeSafeHTTPBasic` protocol from `Kitura-CredentialsHTTP` to provide basic HTTP authentication.
```swift
struct Query: QueryParams {
let id: Int
}
router.get("/user") { (auth: MyHTTPAuth, middle2: Middle2, middle3: Middle3, query: Query?, respondWith: ([User]?, RequestError?) -> Void) in
if let query = query {
let matchedUsers = userArray.filter { $0.id <= query.id }
return respondWith(matchedUsers, nil)
} else {
return respondWith(userArray, nil)
}
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives three TypeSafeMiddleware instances and a QueryParams instance, and returns an array of Codable objects or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, Q: QueryParams, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, T3, Q?, @escaping CodableArrayResultClosure<O>) -> Void
) {
registerGetRoute(route: route, queryParams: Q.self, optionalQParam: true, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET (plural) type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
do {
var query: Q? = nil
let queryParameters = request.queryParameters
if queryParameters.count > 0 {
query = try QueryDecoder(dictionary: queryParameters).decode(Q.self)
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, query, CodableHelpers.constructOutResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User`, where `User` conforms to Codable.
```swift
router.delete("/user") { (session: MySession, respondWith: (RequestError?) -> Void) in
session.user: User? = nil
respondWith(nil)
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.delete("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3,
respondWith: (RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and returns a RequestError or nil on success.
*/
public func delete<T: TypeSafeMiddleware>(
_ route: String,
handler: @escaping (T, @escaping ResultClosure) -> Void
) {
registerDeleteRoute(route: route)
delete(route) { request, response, next in
Log.verbose("Received DELETE (plural with middleware) type-safe request")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
handler(typeSafeMiddleware, CodableHelpers.constructResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User`, where `User` conforms to Codable.
```swift
router.delete("/user") { (session: MySession, middle2: Middle2, respondWith: (RequestError?) -> Void) in
session.user: User? = nil
respondWith(nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and returns a RequestError or nil on success.
:nodoc:
*/
public func delete<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware>(
_ route: String,
handler: @escaping (T1, T2, @escaping ResultClosure) -> Void
) {
registerDeleteRoute(route: route)
delete(route) { request, response, next in
Log.verbose("Received DELETE (plural with middleware) type-safe request")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, CodableHelpers.constructResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User`, where `User` conforms to Codable.
```swift
router.delete("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, respondWith: (RequestError?) -> Void) in
session.user: User? = nil
respondWith(nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and returns a RequestError or nil on success.
:nodoc:
*/
public func delete<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware>(
_ route: String,
handler: @escaping (T1, T2, T3, @escaping ResultClosure) -> Void
) {
registerDeleteRoute(route: route)
delete(route) { request, response, next in
Log.verbose("Received DELETE (plural with middleware) type-safe request")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, CodableHelpers.constructResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`, an `Identifier`
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.delete("/user") { (session: MySession, id: Int, respondWith: (RequestError?) -> Void) in
session.user[id] = nil
respondWith(nil)
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.delete("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3, id: Int,
respondWith: (RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and Identifier, and returns nil on success, or a `RequestError`.
*/
public func delete<T: TypeSafeMiddleware, Id: Identifier>(
_ route: String,
handler: @escaping (T, Id, @escaping ResultClosure) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerDeleteRoute(route: route, id: Id.self)
delete(appendId(path: route)) { request, response, next in
Log.verbose("Received DELETE (singular with middleware) type-safe request")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response) else {
return next()
}
handler(typeSafeMiddleware, identifier, CodableHelpers.constructResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`, an `Identifier`
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.delete("/user") { (session: MySession, middle2: Middle2, id: Int, respondWith: (RequestError?) -> Void) in
session.user[id] = nil
respondWith(nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and Identifier, and returns nil on success, or a `RequestError`.
:nodoc:
*/
public func delete<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, Id: Identifier>(
_ route: String,
handler: @escaping (T1, T2, Id, @escaping ResultClosure) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerDeleteRoute(route: route, id: Id.self)
delete(appendId(path: route)) { request, response, next in
Log.verbose("Received DELETE (singular with middleware) type-safe request")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response) else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, identifier, CodableHelpers.constructResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`, an `Identifier`
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.delete("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, rid: Int, respondWith: (RequestError?) -> Void) in
session.user[id] = nil
respondWith(nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and Identifier, and returns nil on success, or a `RequestError`.
:nodoc:
*/
public func delete<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, Id: Identifier>(
_ route: String,
handler: @escaping (T1, T2, T3, Id, @escaping ResultClosure) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerDeleteRoute(route: route, id: Id.self)
delete(appendId(path: route)) { request, response, next in
Log.verbose("Received DELETE (singular with middleware) type-safe request")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response) else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, identifier, CodableHelpers.constructResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
struct Query: QueryParams {
let id: Int
}
router.delete("/user") { (session: MySession, query: Query, respondWith: (RequestError?) -> Void) in
session.user[query.id] = nil
respondWith(nil)
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.delete("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3, query: Query,
respondWith: (RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and Identifier, and returns nil on success, or a `RequestError`.
*/
public func delete<T: TypeSafeMiddleware, Q: QueryParams>(
_ route: String,
handler: @escaping (T, Q, @escaping ResultClosure) -> Void
) {
registerDeleteRoute(route: route, queryParams: Q.self, optionalQParam: false)
delete(route) { request, response, next in
Log.verbose("Received DELETE type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
do {
let query: Q = try QueryDecoder(dictionary: request.queryParameters).decode(Q.self)
handler(typeSafeMiddleware, query, CodableHelpers.constructResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MyHTTPAuth` is a struct that conforms to the `TypeSafeHTTPBasic` protocol from `Kitura-CredentialsHTTP` to provide basic HTTP authentication.
```swift
struct Query: QueryParams {
let id: Int
}
router.delete("/user") { (auth: MyHTTPAuth, query: Query?, respondWith: (RequestError?) -> Void) in
if let query = query {
userArray = userArray.filter { $0.id != query.id }
return respondWith(nil)
} else {
userArray = []
return respondWith(nil)
}
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.delete("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3, query: Query?,
respondWith: (RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and Identifier, and returns nil on success, or a `RequestError`.
*/
public func delete<T: TypeSafeMiddleware, Q: QueryParams>(
_ route: String,
handler: @escaping (T, Q?, @escaping ResultClosure) -> Void
) {
registerDeleteRoute(route: route, queryParams: Q.self, optionalQParam: true)
delete(route) { request, response, next in
Log.verbose("Received DELETE type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
do {
var query: Q? = nil
let queryParameters = request.queryParameters
if queryParameters.count > 0 {
query = try QueryDecoder(dictionary: queryParameters).decode(Q.self)
}
handler(typeSafeMiddleware, query, CodableHelpers.constructResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
struct Query: QueryParams {
let id: Int
}
router.delete("/user") { (session: MySession, middle2: Middle2, query: Query, respondWith: (RequestError?) -> Void) in
session.user[query.id] = nil
respondWith(nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and Identifier, and returns nil on success, or a `RequestError`.
:nodoc:
*/
public func delete<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, Q: QueryParams>(
_ route: String,
handler: @escaping (T1, T2, Q, @escaping ResultClosure) -> Void
) {
registerDeleteRoute(route: route, queryParams: Q.self, optionalQParam: false)
delete(route) { request, response, next in
Log.verbose("Received DELETE type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
do {
let query: Q = try QueryDecoder(dictionary: request.queryParameters).decode(Q.self)
handler(typeSafeMiddleware1, typeSafeMiddleware2, query, CodableHelpers.constructResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MyHTTPAuth` is a struct that conforms to the `TypeSafeHTTPBasic` protocol from `Kitura-CredentialsHTTP` to provide basic HTTP authentication.
```swift
struct Query: QueryParams {
let id: Int
}
router.delete("/user") { (auth: MyHTTPAuth, middle2, Middle2, query: Query?, respondWith: (RequestError?) -> Void) in
if let query = query {
userArray = userArray.filter { $0.id != query.id }
return respondWith(nil)
} else {
userArray = []
return respondWith(nil)
}
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and Identifier, and returns nil on success, or a `RequestError`.
:nodoc:
*/
public func delete<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, Q: QueryParams>(
_ route: String,
handler: @escaping (T1, T2, Q?, @escaping ResultClosure) -> Void
) {
registerDeleteRoute(route: route, queryParams: Q.self, optionalQParam: true)
delete(route) { request, response, next in
Log.verbose("Received DELETE type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
do {
var query: Q? = nil
let queryParameters = request.queryParameters
if queryParameters.count > 0 {
query = try QueryDecoder(dictionary: queryParameters).decode(Q.self)
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, query, CodableHelpers.constructResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
struct Query: QueryParams {
let id: Int
}
router.delete("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, rquery: Query, respondWith: (RequestError?) -> Void) in
session.user[query.id] = nil
respondWith(nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and Identifier, and returns nil on success, or a `RequestError`.
:nodoc:
*/
public func delete<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, Q: QueryParams>(
_ route: String,
handler: @escaping (T1, T2, T3, Q, @escaping ResultClosure) -> Void
) {
registerDeleteRoute(route: route, queryParams: Q.self, optionalQParam: false)
delete(route) { request, response, next in
Log.verbose("Received DELETE type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
do {
let query: Q = try QueryDecoder(dictionary: request.queryParameters).decode(Q.self)
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, query, CodableHelpers.constructResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MyHTTPAuth` is a struct that conforms to the `TypeSafeHTTPBasic` protocol from `Kitura-CredentialsHTTP` to provide basic HTTP authentication.
```swift
struct Query: QueryParams {
let id: Int
}
router.delete("/user") { (auth: MyHTTPAuth, middle2, Middle2, middle3, Middle3, query: Query?, respondWith: (RequestError?) -> Void) in
if let query = query {
userArray = userArray.filter { $0.id != query.id }
return respondWith(nil)
} else {
userArray = []
return respondWith(nil)
}
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and Identifier, and returns nil on success, or a `RequestError`.
:nodoc:
*/
public func delete<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, Q: QueryParams>(
_ route: String,
handler: @escaping (T1, T2, T3, Q?, @escaping ResultClosure) -> Void
) {
registerDeleteRoute(route: route, queryParams: Q.self, optionalQParam: true)
delete(route) { request, response, next in
Log.verbose("Received DELETE type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
do {
var query: Q? = nil
let queryParameters = request.queryParameters
if queryParameters.count > 0 {
query = try QueryDecoder(dictionary: queryParameters).decode(Q.self)
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, query, CodableHelpers.constructResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a POST request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`, a Codable object
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User`, where `User` conforms to Codable.
```swift
router.post("/user") { (session: MySession, user: User, respondWith: (User?, RequestError?) -> Void) in
if session.user == nil {
return respondWith(nil, .badRequest)
} else {
session.user = user
respondWith(user, nil)
}
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.post("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3, user: User,
respondWith: (User?, RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware instance and a Codable object, and returns a Codable object or a RequestError.
*/
public func post<T: TypeSafeMiddleware, I: Codable, O: Codable>(
_ route: String,
handler: @escaping (T, I, @escaping CodableResultClosure<O>) -> Void
) {
registerPostRoute(route: route, inputType: I.self, outputType: O.self)
post(route) { request, response, next in
Log.verbose("Received POST type-safe request")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
guard let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response) else {
next()
return
}
handler(typeSafeMiddleware, codableInput, CodableHelpers.constructOutResultHandler(successStatus: .created, response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a POST request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`, a Codable object
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User`, where `User` conforms to Codable.
```swift
router.post("/user") { (session: MySession, middle2: Middle2, user: User, respondWith: (User?, RequestError?) -> Void) in
if session.user == nil {
return respondWith(nil, .badRequest)
} else {
session.user = user
respondWith(user, nil)
}
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives two TypeSafeMiddleware instances and a Codable object, and returns a Codable object or a RequestError.
:nodoc:
*/
public func post<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, I: Codable, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, I, @escaping CodableResultClosure<O>) -> Void
) {
registerPostRoute(route: route, inputType: I.self, outputType: O.self)
post(route) { request, response, next in
Log.verbose("Received POST type-safe request")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
guard let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response) else {
next()
return
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, codableInput, CodableHelpers.constructOutResultHandler(successStatus: .created, response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a POST request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`, a Codable object
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User`, where `User` conforms to Codable.
```swift
router.post("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, ruser: User, respondWith: (User?, RequestError?) -> Void) in
if session.user == nil {
return respondWith(nil, .badRequest)
} else {
session.user = user
respondWith(user, nil)
}
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives three TypeSafeMiddleware instances and a Codable object, and returns a Codable object or a RequestError.
:nodoc:
*/
public func post<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, I: Codable, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, T3, I, @escaping CodableResultClosure<O>) -> Void
) {
registerPostRoute(route: route, inputType: I.self, outputType: O.self)
post(route) { request, response, next in
Log.verbose("Received POST type-safe request")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
guard let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response) else {
next()
return
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, codableInput, CodableHelpers.constructOutResultHandler(successStatus: .created, response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a POST request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`, a Codable object
and a handler which responds with an `Identifier` and a Codable object, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.post("/user") { (session: MySession, user: User, respondWith: (Int?, User?, RequestError?) -> Void) in
let newId = session.users.count + 1
session.user[newId] = user
respondWith(newId, user, nil)
}
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.post("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3, user: User, respondWith: (Int?, User?, RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware instance and a Codable object, and returns an Identifier and a Codable object or a RequestError.
*/
public func post<T: TypeSafeMiddleware, I: Codable, Id: Identifier, O: Codable>(
_ route: String,
handler: @escaping (T, I, @escaping IdentifierCodableResultClosure<Id, O>) -> Void
) {
registerPostRoute(route: route, id: Id.self, inputType: I.self, outputType: O.self)
post(route) { request, response, next in
Log.verbose("Received POST type-safe request")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
guard let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response) else {
return next()
}
handler(typeSafeMiddleware, codableInput, CodableHelpers.constructIdentOutResultHandler(successStatus: .created, response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a POST request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`, a Codable object
and a handler which responds with an `Identifier` and a Codable object, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.post("/user") { (session: MySession, middle2: Middle2, user: User, respondWith: (Int?, User?, RequestError?) -> Void) in
let newId = session.users.count + 1
session.user[newId] = user
respondWith(newId, user, nil)
}
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives two TypeSafeMiddleware instances and a Codable object, and returns an Identifier and a Codable object or a RequestError.
:nodoc:
*/
public func post<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, I: Codable, Id: Identifier, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, I, @escaping IdentifierCodableResultClosure<Id, O>) -> Void
) {
registerPostRoute(route: route, id: Id.self, inputType: I.self, outputType: O.self)
post(route) { request, response, next in
Log.verbose("Received POST type-safe request")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
guard let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response) else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, codableInput, CodableHelpers.constructIdentOutResultHandler(successStatus: .created, response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a POST request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`, a Codable object
and a handler which responds with an `Identifier` and a Codable object, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.post("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, ruser: User, respondWith: (Int?, User?, RequestError?) -> Void) in
let newId = session.users.count + 1
session.user[newId] = user
respondWith(newId, user, nil)
}
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives three TypeSafeMiddleware instances and a Codable object, and returns an Identifier and a Codable object or a RequestError.
:nodoc:
*/
public func post<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, I: Codable, Id: Identifier, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, T3, I, @escaping IdentifierCodableResultClosure<Id, O>) -> Void
) {
registerPostRoute(route: route, id: Id.self, inputType: I.self, outputType: O.self)
post(route) { request, response, next in
Log.verbose("Received POST type-safe request")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
guard let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response) else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, codableInput, CodableHelpers.constructIdentOutResultHandler(successStatus: .created, response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a PUT request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`, an `Identifier`, a Codable object
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.post("/user") { (session: MySession, id: Int, user: User, respondWith: (User?, RequestError?) -> Void) in
session.user[id] = user
respondWith(user, nil)
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.put("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3,
id: Int, user: User, respondWith: (User?, RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware instance, an Identifier and a Codable object, and returns a Codable object or a RequestError.
*/
public func put<T: TypeSafeMiddleware, Id: Identifier, I: Codable, O: Codable>(
_ route: String,
handler: @escaping (T, Id, I, @escaping CodableResultClosure<O>) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerPutRoute(route: route, id: Id.self, inputType: I.self, outputType: O.self)
put(appendId(path: route)) { request, response, next in
Log.verbose("Received PUT type-safe request")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response),
let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response)
else {
return next()
}
handler(typeSafeMiddleware, identifier, codableInput, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a PUT request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`, an `Identifier`, a Codable object
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.post("/user") { (session: MySession, middle2: Middle2, id: Int, user: User, respondWith: (User?, RequestError?) -> Void) in
session.user[id] = user
respondWith(user, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives two TypeSafeMiddleware instances, an Identifier and a Codable object, and returns a Codable object or a RequestError.
:nodoc:
*/
public func put<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, Id: Identifier, I: Codable, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, Id, I, @escaping CodableResultClosure<O>) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerPutRoute(route: route, id: Id.self, inputType: I.self, outputType: O.self)
put(appendId(path: route)) { request, response, next in
Log.verbose("Received PUT type-safe request")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response),
let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response)
else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, identifier, codableInput, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a PUT request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`, an `Identifier`, a Codable object
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.post("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, r id: Int, user: User, respondWith: (User?, RequestError?) -> Void) in
session.user[id] = user
respondWith(user, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives three TypeSafeMiddleware instances, an Identifier and a Codable object, and returns a Codable object or a RequestError.
:nodoc:
*/
public func put<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, Id: Identifier, I: Codable, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, T3, Id, I, @escaping CodableResultClosure<O>) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerPutRoute(route: route, id: Id.self, inputType: I.self, outputType: O.self)
put(appendId(path: route)) { request, response, next in
Log.verbose("Received PUT type-safe request")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response),
let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response)
else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, identifier, codableInput, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a PATCH request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`, an `Identifier`, a Codable object
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.patch("/user") { (session: MySession, id: Int, inputUser: User, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user[id] else {
return respondWith(nil, .notFound)
}
user.id = inputUser.id ?? user.id
user.name = inputUser.name ?? user.name
respondWith(user, nil)
}
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.patch("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3,
id: Int, user: User, respondWith: (User?, RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware instance, an Identifier and a Codable object, and returns a Codable object or a RequestError.
*/
public func patch<T: TypeSafeMiddleware, Id: Identifier, I: Codable, O: Codable>(
_ route: String,
handler: @escaping (T, Id, I, @escaping CodableResultClosure<O>) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerPatchRoute(route: route, id: Id.self, inputType: I.self, outputType: O.self)
patch(appendId(path: route)) { request, response, next in
Log.verbose("Received PATCH type-safe request")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response),
let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response)
else {
return next()
}
handler(typeSafeMiddleware, identifier, codableInput, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a PATCH request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`, an `Identifier`, a Codable object
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.patch("/user") { (session: MySession, middle2: Middle2, id: Int, inputUser: User, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user[id] else {
return respondWith(nil, .notFound)
}
user.id = inputUser.id ?? user.id
user.name = inputUser.name ?? user.name
respondWith(user, nil)
}
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives two TypeSafeMiddleware instances, an Identifier and a Codable object, and returns a Codable object or a RequestError.
:nodoc:
*/
public func patch<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, Id: Identifier, I: Codable, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, Id, I, @escaping CodableResultClosure<O>) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerPatchRoute(route: route, id: Id.self, inputType: I.self, outputType: O.self)
patch(appendId(path: route)) { request, response, next in
Log.verbose("Received PATCH type-safe request")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response),
let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response)
else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, identifier, codableInput, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a PATCH request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`, an `Identifier`, a Codable object
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.patch("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, rid: Int, inputUser: User, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user[id] else {
return respondWith(nil, .notFound)
}
user.id = inputUser.id ?? user.id
user.name = inputUser.name ?? user.name
respondWith(user, nil)
}
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives three TypeSafeMiddleware instances, an Identifier and a Codable object, and returns a Codable object or a RequestError.
:nodoc:
*/
public func patch<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, Id: Identifier, I: Codable, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, T3, Id, I, @escaping CodableResultClosure<O>) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerPatchRoute(route: route, id: Id.self, inputType: I.self, outputType: O.self)
patch(appendId(path: route)) { request, response, next in
Log.verbose("Received PATCH type-safe request")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response),
let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response)
else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, identifier, codableInput, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
// Function to call the static handle function of a TypeSafeMiddleware and on success return
// an instance of the middleware or on failing set the response error and return nil.
private func handleMiddleware<T: TypeSafeMiddleware>(
_ middlewareType: T.Type,
request: RouterRequest,
response: RouterResponse,
completion: @escaping (T?) -> Void
) {
T.handle(request: request, response: response) { (typeSafeMiddleware: T?, error: RequestError?) in
guard let typeSafeMiddleware = typeSafeMiddleware else {
response.status(CodableHelpers.httpStatusCode(from: error ?? .internalServerError))
return completion(nil)
}
completion(typeSafeMiddleware)
}
}
// Function to call the static handle function of two TypeSafeMiddleware in sequence and on success return
// both instances of the middlewares or on failing set the response error and return at least one nil.
private func handleMiddleware<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware>(
_ middlewareOneType: T1.Type,
_ middlewareTwoType: T2.Type,
request: RouterRequest,
response: RouterResponse,
completion: @escaping (T1?, T2?) -> Void
) {
T1.handle(request: request, response: response) { (typeSafeMiddleware1: T1?, error: RequestError?) in
guard let typeSafeMiddleware1 = typeSafeMiddleware1 else {
response.status(CodableHelpers.httpStatusCode(from: error ?? .internalServerError))
return completion(nil, nil)
}
T2.handle(request: request, response: response) { (typeSafeMiddleware2: T2?, error: RequestError?) in
guard let typeSafeMiddleware2 = typeSafeMiddleware2 else {
response.status(CodableHelpers.httpStatusCode(from: error ?? .internalServerError))
return completion(typeSafeMiddleware1, nil)
}
completion(typeSafeMiddleware1, typeSafeMiddleware2)
}
}
}
// Function to call the static handle function of three TypeSafeMiddleware in sequence and on success return
// all instances of the middlewares or on failing set the response error and return at least one nil.
private func handleMiddleware<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware>(
_ middlewareOneType: T1.Type,
_ middlewareTwoType: T2.Type,
_ middlewareThreeType: T3.Type,
request: RouterRequest,
response: RouterResponse,
completion: @escaping (T1?, T2?, T3?) -> Void
) {
T1.handle(request: request, response: response) { (typeSafeMiddleware1: T1?, error: RequestError?) in
guard let typeSafeMiddleware1 = typeSafeMiddleware1 else {
response.status(CodableHelpers.httpStatusCode(from: error ?? .internalServerError))
return completion(nil, nil, nil)
}
T2.handle(request: request, response: response) { (typeSafeMiddleware2: T2?, error: RequestError?) in
guard let typeSafeMiddleware2 = typeSafeMiddleware2 else {
response.status(CodableHelpers.httpStatusCode(from: error ?? .internalServerError))
return completion(typeSafeMiddleware1, nil, nil)
}
T3.handle(request: request, response: response) { (typeSafeMiddleware3: T3?, error: RequestError?) in
guard let typeSafeMiddleware3 = typeSafeMiddleware3 else {
response.status(CodableHelpers.httpStatusCode(from: error ?? .internalServerError))
return completion(typeSafeMiddleware1, typeSafeMiddleware2, nil)
}
completion(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3)
}
}
}
}
}
| apache-2.0 | a04ffaccf355dd54c34c35b25bb6d866 | 55.379864 | 210 | 0.654494 | 4.644855 | false | false | false | false |
Ethenyl/JAMFKit | JamfKit/Sources/Models/Policy/PolicyGeneral.swift | 1 | 6449 | //
// Copyright © 2017-present JamfKit. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
@objc(JMFKPolicyGeneral)
public final class PolicyGeneral: BaseObject {
// MARK: - Constants
static let EnabledKey = "enabled"
static let TriggerKey = "trigger"
static let TriggerCheckinKey = "trigger_checkin"
static let TriggerEnrollmentCompleteKey = "trigger_enrollment_complete"
static let TriggerLoginKey = "trigger_login"
static let TriggerLogoutKey = "trigger_logout"
static let TriggerNetworkStateChangedKey = "trigger_network_state_changed"
static let TriggerStartupKey = "trigger_startup"
static let TriggerOtherKey = "trigger_other"
static let FrequencyKey = "frequency"
static let LocationUserOnlyKey = "location_user_only"
static let TargetDriveKey = "target_drive"
static let OfflineKey = "offline"
static let CategoryKey = "category"
static let DateTimeLimitationsKey = "date_time_limitations"
static let NetworkLimitationsKey = "network_limitations"
static let OverrideDefaultSettingsKey = "override_default_settings"
static let NetworkRequirementsKey = "network_requirements"
static let SiteKey = "site"
// MARK: - Properties
@objc
public var isEnabled = false
@objc
public var trigger = ""
@objc
public var triggerCheckin = false
@objc
public var triggerEnrollmentComplete = false
@objc
public var triggerLogin = false
@objc
public var triggerLogout = false
@objc
public var triggerNetworkStateChanged = false
@objc
public var triggerStartup = false
@objc
public var triggerOther = ""
@objc
public var frequency = ""
@objc
public var locationUserOnly = false
@objc
public var targetDrive = ""
@objc
public var offline = false
@objc
public var category: Category?
@objc
public var dateTimeLimitations: PolicyDateTimeLimitations?
@objc
public var networkLimitations: PolicyNetworkLimitations?
@objc
public var overrideDefaultSettings: PolicyOverrideDefaultSettings?
@objc
public var networkRequirements = ""
@objc
public var site: Site?
// MARK: - Initialization
public required init?(json: [String: Any], node: String = "") {
isEnabled = json[PolicyGeneral.EnabledKey] as? Bool ?? false
trigger = json[PolicyGeneral.TriggerKey] as? String ?? ""
triggerCheckin = json[PolicyGeneral.TriggerCheckinKey] as? Bool ?? false
triggerEnrollmentComplete = json[PolicyGeneral.TriggerEnrollmentCompleteKey] as? Bool ?? false
triggerLogin = json[PolicyGeneral.TriggerLoginKey] as? Bool ?? false
triggerLogout = json[PolicyGeneral.TriggerLogoutKey] as? Bool ?? false
triggerNetworkStateChanged = json[PolicyGeneral.TriggerNetworkStateChangedKey] as? Bool ?? false
triggerStartup = json[PolicyGeneral.TriggerStartupKey] as? Bool ?? false
triggerOther = json[PolicyGeneral.TriggerOtherKey] as? String ?? ""
frequency = json[PolicyGeneral.FrequencyKey] as? String ?? ""
locationUserOnly = json[PolicyGeneral.LocationUserOnlyKey] as? Bool ?? false
targetDrive = json[PolicyGeneral.TargetDriveKey] as? String ?? ""
offline = json[PolicyGeneral.OfflineKey] as? Bool ?? false
if let categoryNode = json[PolicyGeneral.CategoryKey] as? [String: Any] {
category = Category(json: categoryNode)
}
if let dataLimitationsNode = json[PolicyGeneral.DateTimeLimitationsKey] as? [String: Any] {
dateTimeLimitations = PolicyDateTimeLimitations(json: dataLimitationsNode)
}
if let networkLimitationsNode = json[PolicyGeneral.NetworkLimitationsKey] as? [String: Any] {
networkLimitations = PolicyNetworkLimitations(json: networkLimitationsNode)
}
if let overrideDefaultSettingsNode = json[PolicyGeneral.OverrideDefaultSettingsKey] as? [String: Any] {
overrideDefaultSettings = PolicyOverrideDefaultSettings(json: overrideDefaultSettingsNode)
}
networkRequirements = json[PolicyGeneral.NetworkRequirementsKey] as? String ?? ""
if let siteNode = json[PolicyGeneral.SiteKey] as? [String: Any] {
site = Site(json: siteNode)
}
super.init(json: json)
}
public override init?(identifier: UInt, name: String) {
dateTimeLimitations = PolicyDateTimeLimitations()
networkLimitations = PolicyNetworkLimitations()
overrideDefaultSettings = PolicyOverrideDefaultSettings()
super.init(identifier: identifier, name: name)
}
// MARK: - Functions
public override func toJSON() -> [String: Any] {
var json = super.toJSON()
json[PolicyGeneral.EnabledKey] = isEnabled
json[PolicyGeneral.TriggerKey] = trigger
json[PolicyGeneral.TriggerCheckinKey] = triggerCheckin
json[PolicyGeneral.TriggerEnrollmentCompleteKey] = triggerEnrollmentComplete
json[PolicyGeneral.TriggerLoginKey] = triggerLogin
json[PolicyGeneral.TriggerLogoutKey] = triggerLogout
json[PolicyGeneral.TriggerNetworkStateChangedKey] = triggerNetworkStateChanged
json[PolicyGeneral.TriggerStartupKey] = triggerStartup
json[PolicyGeneral.TriggerOtherKey] = triggerOther
json[PolicyGeneral.FrequencyKey] = frequency
json[PolicyGeneral.LocationUserOnlyKey] = locationUserOnly
json[PolicyGeneral.TargetDriveKey] = targetDrive
json[PolicyGeneral.OfflineKey] = offline
if let category = category {
json[PolicyGeneral.CategoryKey] = category.toJSON()
}
if let dateTimeLimitations = dateTimeLimitations {
json[PolicyGeneral.DateTimeLimitationsKey] = dateTimeLimitations.toJSON()
}
if let networkLimitations = networkLimitations {
json[PolicyGeneral.NetworkLimitationsKey] = networkLimitations.toJSON()
}
if let overrideDefaultSettings = overrideDefaultSettings {
json[PolicyGeneral.OverrideDefaultSettingsKey] = overrideDefaultSettings.toJSON()
}
json[PolicyGeneral.NetworkRequirementsKey] = networkRequirements
if let site = site {
json[PolicyGeneral.SiteKey] = site.toJSON()
}
return json
}
}
| mit | dd6bc54c01083dd8c246a7ee685c6701 | 34.234973 | 111 | 0.698976 | 4.622222 | false | false | false | false |
jekahy/Adoreavatars | Adoravatars/DownloadsVC.swift | 1 | 1266 | //
// DownloadsVC.swift
// Adoravatars
//
// Created by Eugene on 21.06.17.
// Copyright © 2017 Eugene. All rights reserved.
//
import Foundation
import UIKit
import RxSwift
import RxCocoa
import Then
class DownloadsVC: UIViewController {
let cellIdentifier = "downloadCell"
@IBOutlet weak var tableView: UITableView!
private let disposeBag = DisposeBag()
private var viewModel:DownloadsVMType!
private var navigator:Navigator!
override func viewDidLoad()
{
super.viewDidLoad()
automaticallyAdjustsScrollViewInsets = false
viewModel.downloadTasks.drive(tableView.rx.items(cellIdentifier: cellIdentifier, cellType: DownloadCell.self))
{ (index, downloadTask: DownloadTaskType, cell) in
let downloadVM = DownloadVM(downloadTask)
cell.configureWith(downloadVM)
}.addDisposableTo(disposeBag)
}
static func createWith(navigator: Navigator, storyboard: UIStoryboard, viewModel: DownloadsVMType) -> DownloadsVC {
return storyboard.instantiateViewController(ofType: DownloadsVC.self).then { vc in
vc.navigator = navigator
vc.viewModel = viewModel
}
}
}
| mit | 6ae9bf57d6a0412e6634adc7c9698834 | 23.803922 | 119 | 0.666403 | 5.100806 | false | false | false | false |
Antondomashnev/Sourcery | SourceryTests/Stub/Performance-Code/Kiosk/Bid Fulfillment/KeypadContainerView.swift | 2 | 1392 | import UIKit
import Foundation
import RxSwift
import Action
import FLKAutoLayout
//@IBDesignable
class KeypadContainerView: UIView {
fileprivate var keypad: KeypadView!
fileprivate let viewModel = KeypadViewModel()
var stringValue: Observable<String>!
var intValue: Observable<Int>!
var deleteAction: CocoaAction!
var resetAction: CocoaAction!
override func prepareForInterfaceBuilder() {
for subview in subviews { subview.removeFromSuperview() }
let bundle = Bundle(for: type(of: self))
let image = UIImage(named: "KeypadViewPreviewIB", in: bundle, compatibleWith: self.traitCollection)
let imageView = UIImageView(frame: self.bounds)
imageView.image = image
self.addSubview(imageView)
}
override func awakeFromNib() {
super.awakeFromNib()
keypad = Bundle(for: type(of: self)).loadNibNamed("KeypadView", owner: self, options: nil)?.first as? KeypadView
keypad.leftAction = viewModel.deleteAction
keypad.rightAction = viewModel.clearAction
keypad.keyAction = viewModel.addDigitAction
intValue = viewModel.intValue.asObservable()
stringValue = viewModel.stringValue.asObservable()
deleteAction = viewModel.deleteAction
resetAction = viewModel.clearAction
self.addSubview(keypad)
keypad.align(to: self)
}
}
| mit | cbfc16ca65ab9bac44f191b44cc2b04c | 29.933333 | 120 | 0.700431 | 4.93617 | false | false | false | false |
rcwchew/swiftScan | swiftScan/ScanResultController.swift | 1 | 2340 | //
// ScanResultController.swift
// swiftScan
//
// Created by xialibing on 15/12/11.
// Copyright © 2015年 xialibing. All rights reserved.
//
import UIKit
class ScanResultController: UIViewController {
@IBOutlet weak var codeImg: UIImageView!
@IBOutlet weak var codeTypeLabel: UILabel!
@IBOutlet weak var codeStringLabel: UILabel!
@IBOutlet weak var concreteCodeImg: UIImageView!
var codeResult:LBXScanResult?
override func viewDidLoad() {
super.viewDidLoad()
self.edgesForExtendedLayout = UIRectEdge(rawValue: 0)
codeTypeLabel.text = ""
codeStringLabel.text = ""
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool)
{
super.viewDidAppear(animated)
codeImg.image = codeResult?.imgScanned
codeTypeLabel.text = "码的类型:" + (codeResult?.strBarCodeType)!
codeStringLabel.text = "码的内容:" + (codeResult?.strScanned)!
if codeImg.image != nil
{
var rect = LBXScanWrapper.getConcreteCodeRectFromImage(srcCodeImage: codeImg.image!, codeResult: codeResult!)
if !rect.isEmpty
{
zoomRect(rect: &rect, srcImg: codeImg.image!)
let img2 = LBXScanWrapper.getConcreteCodeImage(srcCodeImage: codeImg.image!, rect: rect)
if (img2 != nil)
{
concreteCodeImg.image = img2
}
}
}
}
func zoomRect( rect:inout CGRect,srcImg:UIImage)
{
rect.origin.x -= 10
rect.origin.y -= 10
rect.size.width += 20
rect.size.height += 20
if rect.origin.x < 0
{
rect.origin.x = 0
}
if (rect.origin.y < 0)
{
rect.origin.y = 0
}
if (rect.origin.x + rect.size.width) > srcImg.size.width
{
rect.size.width = srcImg.size.width - rect.origin.x - 1
}
if (rect.origin.y + rect.size.height) > srcImg.size.height
{
rect.size.height = srcImg.size.height - rect.origin.y - 1
}
}
}
| mit | ddae0f21e8a8c77f922a648541aeb09e | 23.956989 | 121 | 0.535976 | 4.330224 | false | false | false | false |
shyn/cs193p | Psychologist/Psychologist/TextViewController.swift | 1 | 866 | //
// TextViewController.swift
// Psychologist
//
// Created by deepwind on 5/1/17.
// Copyright © 2017 deepwind. All rights reserved.
//
import UIKit
class TextViewController: UIViewController {
@IBOutlet weak var textView: UITextView! {
didSet {
textView.text = text
}
}
// add ? to avoid crash when prepare segue
var text: String = "" {
didSet {
textView?.text = text
}
}
override var preferredContentSize: CGSize {
get {
if textView != nil && presentingViewController != nil {
return textView.sizeThatFits(presentingViewController!.view.bounds.size)
}else {
return super.preferredContentSize
}
}
set {
super.preferredContentSize = newValue
}
}
}
| mit | a91a5396cda56df756693a49ae1374b5 | 21.179487 | 88 | 0.557225 | 5.05848 | false | false | false | false |
February12/YLPhotoBrowser | Pods/Kingfisher/Sources/ImageDownloader.swift | 8 | 26245 | //
// ImageDownloader.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2017 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(macOS)
import AppKit
#else
import UIKit
#endif
/// Progress update block of downloader.
public typealias ImageDownloaderProgressBlock = DownloadProgressBlock
/// Completion block of downloader.
public typealias ImageDownloaderCompletionHandler = ((_ image: Image?, _ error: NSError?, _ url: URL?, _ originalData: Data?) -> ())
/// Download task.
public struct RetrieveImageDownloadTask {
let internalTask: URLSessionDataTask
/// Downloader by which this task is intialized.
public private(set) weak var ownerDownloader: ImageDownloader?
/**
Cancel this download task. It will trigger the completion handler with an NSURLErrorCancelled error.
*/
public func cancel() {
ownerDownloader?.cancelDownloadingTask(self)
}
/// The original request URL of this download task.
public var url: URL? {
return internalTask.originalRequest?.url
}
/// The relative priority of this download task.
/// It represents the `priority` property of the internal `NSURLSessionTask` of this download task.
/// The value for it is between 0.0~1.0. Default priority is value of 0.5.
/// See documentation on `priority` of `NSURLSessionTask` for more about it.
public var priority: Float {
get {
return internalTask.priority
}
set {
internalTask.priority = newValue
}
}
}
///The code of errors which `ImageDownloader` might encountered.
public enum KingfisherError: Int {
/// badData: The downloaded data is not an image or the data is corrupted.
case badData = 10000
/// notModified: The remote server responsed a 304 code. No image data downloaded.
case notModified = 10001
/// The HTTP status code in response is not valid. If an invalid
/// code error received, you could check the value under `KingfisherErrorStatusCodeKey`
/// in `userInfo` to see the code.
case invalidStatusCode = 10002
/// notCached: The image rquested is not in cache but .onlyFromCache is activated.
case notCached = 10003
/// The URL is invalid.
case invalidURL = 20000
/// The downloading task is cancelled before started.
case downloadCancelledBeforeStarting = 30000
}
/// Key will be used in the `userInfo` of `.invalidStatusCode`
public let KingfisherErrorStatusCodeKey = "statusCode"
/// Protocol of `ImageDownloader`.
public protocol ImageDownloaderDelegate: class {
/**
Called when the `ImageDownloader` object successfully downloaded an image from specified URL.
- parameter downloader: The `ImageDownloader` object finishes the downloading.
- parameter image: Downloaded image.
- parameter url: URL of the original request URL.
- parameter response: The response object of the downloading process.
*/
func imageDownloader(_ downloader: ImageDownloader, didDownload image: Image, for url: URL, with response: URLResponse?)
/**
Called when the `ImageDownloader` object starts to download an image from specified URL.
- parameter downloader: The `ImageDownloader` object starts the downloading.
- parameter url: URL of the original request.
- parameter response: The request object of the downloading process.
*/
func imageDownloader(_ downloader: ImageDownloader, willDownloadImageForURL url: URL, with request: URLRequest?)
/**
Check if a received HTTP status code is valid or not.
By default, a status code between 200 to 400 (excluded) is considered as valid.
If an invalid code is received, the downloader will raise an .invalidStatusCode error.
It has a `userInfo` which includes this statusCode and localizedString error message.
- parameter code: The received HTTP status code.
- parameter downloader: The `ImageDownloader` object asking for validate status code.
- returns: Whether this HTTP status code is valid or not.
- Note: If the default 200 to 400 valid code does not suit your need,
you can implement this method to change that behavior.
*/
func isValidStatusCode(_ code: Int, for downloader: ImageDownloader) -> Bool
}
extension ImageDownloaderDelegate {
public func imageDownloader(_ downloader: ImageDownloader, didDownload image: Image, for url: URL, with response: URLResponse?) {}
public func imageDownloader(_ downloader: ImageDownloader, willDownloadImageForURL url: URL, with request: URLRequest?) {}
public func isValidStatusCode(_ code: Int, for downloader: ImageDownloader) -> Bool {
return (200..<400).contains(code)
}
}
/// Protocol indicates that an authentication challenge could be handled.
public protocol AuthenticationChallengeResponsable: class {
/**
Called when an session level authentication challenge is received.
This method provide a chance to handle and response to the authentication challenge before downloading could start.
- parameter downloader: The downloader which receives this challenge.
- parameter challenge: An object that contains the request for authentication.
- parameter completionHandler: A handler that your delegate method must call.
- Note: This method is a forward from `URLSessionDelegate.urlSession(:didReceiveChallenge:completionHandler:)`. Please refer to the document of it in `URLSessionDelegate`.
*/
func downloader(_ downloader: ImageDownloader, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
/**
Called when an session level authentication challenge is received.
This method provide a chance to handle and response to the authentication challenge before downloading could start.
- parameter downloader: The downloader which receives this challenge.
- parameter task: The task whose request requires authentication.
- parameter challenge: An object that contains the request for authentication.
- parameter completionHandler: A handler that your delegate method must call.
- Note: This method is a forward from `URLSessionTaskDelegate.urlSession(:task:didReceiveChallenge:completionHandler:)`. Please refer to the document of it in `URLSessionTaskDelegate`.
*/
func downloader(_ downloader: ImageDownloader, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
}
extension AuthenticationChallengeResponsable {
func downloader(_ downloader: ImageDownloader, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
if let trustedHosts = downloader.trustedHosts, trustedHosts.contains(challenge.protectionSpace.host) {
let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
completionHandler(.useCredential, credential)
return
}
}
completionHandler(.performDefaultHandling, nil)
}
func downloader(_ downloader: ImageDownloader, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
completionHandler(.performDefaultHandling, nil)
}
}
/// `ImageDownloader` represents a downloading manager for requesting the image with a URL from server.
open class ImageDownloader {
class ImageFetchLoad {
var contents = [(callback: CallbackPair, options: KingfisherOptionsInfo)]()
var responseData = NSMutableData()
var downloadTaskCount = 0
var downloadTask: RetrieveImageDownloadTask?
var cancelSemaphore: DispatchSemaphore?
}
// MARK: - Public property
/// The duration before the download is timeout. Default is 15 seconds.
open var downloadTimeout: TimeInterval = 15.0
/// A set of trusted hosts when receiving server trust challenges. A challenge with host name contained in this set will be ignored.
/// You can use this set to specify the self-signed site. It only will be used if you don't specify the `authenticationChallengeResponder`.
/// If `authenticationChallengeResponder` is set, this property will be ignored and the implemention of `authenticationChallengeResponder` will be used instead.
open var trustedHosts: Set<String>?
/// Use this to set supply a configuration for the downloader. By default, NSURLSessionConfiguration.ephemeralSessionConfiguration() will be used.
/// You could change the configuration before a downloaing task starts. A configuration without persistent storage for caches is requsted for downloader working correctly.
open var sessionConfiguration = URLSessionConfiguration.ephemeral {
didSet {
session?.invalidateAndCancel()
session = URLSession(configuration: sessionConfiguration, delegate: sessionHandler, delegateQueue: OperationQueue.main)
}
}
/// Whether the download requests should use pipeling or not. Default is false.
open var requestsUsePipelining = false
fileprivate let sessionHandler: ImageDownloaderSessionHandler
fileprivate var session: URLSession?
/// Delegate of this `ImageDownloader` object. See `ImageDownloaderDelegate` protocol for more.
open weak var delegate: ImageDownloaderDelegate?
/// A responder for authentication challenge.
/// Downloader will forward the received authentication challenge for the downloading session to this responder.
open weak var authenticationChallengeResponder: AuthenticationChallengeResponsable?
// MARK: - Internal property
let barrierQueue: DispatchQueue
let processQueue: DispatchQueue
let cancelQueue: DispatchQueue
typealias CallbackPair = (progressBlock: ImageDownloaderProgressBlock?, completionHandler: ImageDownloaderCompletionHandler?)
var fetchLoads = [URL: ImageFetchLoad]()
// MARK: - Public method
/// The default downloader.
public static let `default` = ImageDownloader(name: "default")
/**
Init a downloader with name.
- parameter name: The name for the downloader. It should not be empty.
- returns: The downloader object.
*/
public init(name: String) {
if name.isEmpty {
fatalError("[Kingfisher] You should specify a name for the downloader. A downloader with empty name is not permitted.")
}
barrierQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Barrier.\(name)", attributes: .concurrent)
processQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Process.\(name)", attributes: .concurrent)
cancelQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Cancel.\(name)")
sessionHandler = ImageDownloaderSessionHandler()
// Provide a default implement for challenge responder.
authenticationChallengeResponder = sessionHandler
session = URLSession(configuration: sessionConfiguration, delegate: sessionHandler, delegateQueue: .main)
}
deinit {
session?.invalidateAndCancel()
}
func fetchLoad(for url: URL) -> ImageFetchLoad? {
var fetchLoad: ImageFetchLoad?
barrierQueue.sync(flags: .barrier) { fetchLoad = fetchLoads[url] }
return fetchLoad
}
/**
Download an image with a URL and option.
- parameter url: Target URL.
- parameter retrieveImageTask: The task to cooporate with cache. Pass `nil` if you are not trying to use downloader and cache.
- parameter options: The options could control download behavior. See `KingfisherOptionsInfo`.
- parameter progressBlock: Called when the download progress updated.
- parameter completionHandler: Called when the download progress finishes.
- returns: A downloading task. You could call `cancel` on it to stop the downloading process.
*/
@discardableResult
open func downloadImage(with url: URL,
retrieveImageTask: RetrieveImageTask? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: ImageDownloaderProgressBlock? = nil,
completionHandler: ImageDownloaderCompletionHandler? = nil) -> RetrieveImageDownloadTask?
{
if let retrieveImageTask = retrieveImageTask, retrieveImageTask.cancelledBeforeDownloadStarting {
completionHandler?(nil, NSError(domain: KingfisherErrorDomain, code: KingfisherError.downloadCancelledBeforeStarting.rawValue, userInfo: nil), nil, nil)
return nil
}
let timeout = self.downloadTimeout == 0.0 ? 15.0 : self.downloadTimeout
// We need to set the URL as the load key. So before setup progress, we need to ask the `requestModifier` for a final URL.
var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: timeout)
request.httpShouldUsePipelining = requestsUsePipelining
if let modifier = options?.modifier {
guard let r = modifier.modified(for: request) else {
completionHandler?(nil, NSError(domain: KingfisherErrorDomain, code: KingfisherError.downloadCancelledBeforeStarting.rawValue, userInfo: nil), nil, nil)
return nil
}
request = r
}
// There is a possiblility that request modifier changed the url to `nil` or empty.
guard let url = request.url, !url.absoluteString.isEmpty else {
completionHandler?(nil, NSError(domain: KingfisherErrorDomain, code: KingfisherError.invalidURL.rawValue, userInfo: nil), nil, nil)
return nil
}
var downloadTask: RetrieveImageDownloadTask?
setup(progressBlock: progressBlock, with: completionHandler, for: url, options: options) {(session, fetchLoad) -> Void in
if fetchLoad.downloadTask == nil {
let dataTask = session.dataTask(with: request)
fetchLoad.downloadTask = RetrieveImageDownloadTask(internalTask: dataTask, ownerDownloader: self)
dataTask.priority = options?.downloadPriority ?? URLSessionTask.defaultPriority
dataTask.resume()
self.delegate?.imageDownloader(self, willDownloadImageForURL: url, with: request)
// Hold self while the task is executing.
self.sessionHandler.downloadHolder = self
}
fetchLoad.downloadTaskCount += 1
downloadTask = fetchLoad.downloadTask
retrieveImageTask?.downloadTask = downloadTask
}
return downloadTask
}
}
// MARK: - Download method
extension ImageDownloader {
// A single key may have multiple callbacks. Only download once.
func setup(progressBlock: ImageDownloaderProgressBlock?, with completionHandler: ImageDownloaderCompletionHandler?, for url: URL, options: KingfisherOptionsInfo?, started: @escaping ((URLSession, ImageFetchLoad) -> Void)) {
func prepareFetchLoad() {
barrierQueue.sync(flags: .barrier) {
let loadObjectForURL = fetchLoads[url] ?? ImageFetchLoad()
let callbackPair = (progressBlock: progressBlock, completionHandler: completionHandler)
loadObjectForURL.contents.append((callbackPair, options ?? KingfisherEmptyOptionsInfo))
fetchLoads[url] = loadObjectForURL
if let session = session {
started(session, loadObjectForURL)
}
}
}
if let fetchLoad = fetchLoad(for: url), fetchLoad.downloadTaskCount == 0 {
if fetchLoad.cancelSemaphore == nil {
fetchLoad.cancelSemaphore = DispatchSemaphore(value: 0)
}
cancelQueue.async {
_ = fetchLoad.cancelSemaphore?.wait(timeout: .distantFuture)
fetchLoad.cancelSemaphore = nil
prepareFetchLoad()
}
} else {
prepareFetchLoad()
}
}
func cancelDownloadingTask(_ task: RetrieveImageDownloadTask) {
barrierQueue.sync(flags: .barrier) {
if let URL = task.internalTask.originalRequest?.url, let imageFetchLoad = self.fetchLoads[URL] {
imageFetchLoad.downloadTaskCount -= 1
if imageFetchLoad.downloadTaskCount == 0 {
task.internalTask.cancel()
}
}
}
}
func clean(for url: URL) {
barrierQueue.sync(flags: .barrier) {
fetchLoads.removeValue(forKey: url)
return
}
}
}
// MARK: - NSURLSessionDataDelegate
/// Delegate class for `NSURLSessionTaskDelegate`.
/// The session object will hold its delegate until it gets invalidated.
/// If we use `ImageDownloader` as the session delegate, it will not be released.
/// So we need an additional handler to break the retain cycle.
// See https://github.com/onevcat/Kingfisher/issues/235
class ImageDownloaderSessionHandler: NSObject, URLSessionDataDelegate, AuthenticationChallengeResponsable {
// The holder will keep downloader not released while a data task is being executed.
// It will be set when the task started, and reset when the task finished.
var downloadHolder: ImageDownloader?
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
guard let downloader = downloadHolder else {
completionHandler(.cancel)
return
}
if let statusCode = (response as? HTTPURLResponse)?.statusCode,
let url = dataTask.originalRequest?.url,
!(downloader.delegate ?? downloader).isValidStatusCode(statusCode, for: downloader)
{
let error = NSError(domain: KingfisherErrorDomain,
code: KingfisherError.invalidStatusCode.rawValue,
userInfo: [KingfisherErrorStatusCodeKey: statusCode, NSLocalizedDescriptionKey: HTTPURLResponse.localizedString(forStatusCode: statusCode)])
callCompletionHandlerFailure(error: error, url: url)
}
completionHandler(.allow)
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
guard let downloader = downloadHolder else {
return
}
if let url = dataTask.originalRequest?.url, let fetchLoad = downloader.fetchLoad(for: url) {
fetchLoad.responseData.append(data)
if let expectedLength = dataTask.response?.expectedContentLength {
for content in fetchLoad.contents {
DispatchQueue.main.async {
content.callback.progressBlock?(Int64(fetchLoad.responseData.length), expectedLength)
}
}
}
}
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
guard let url = task.originalRequest?.url else {
return
}
guard error == nil else {
callCompletionHandlerFailure(error: error!, url: url)
return
}
processImage(for: task, url: url)
}
/**
This method is exposed since the compiler requests. Do not call it.
*/
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
guard let downloader = downloadHolder else {
return
}
downloader.authenticationChallengeResponder?.downloader(downloader, didReceive: challenge, completionHandler: completionHandler)
}
func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
guard let downloader = downloadHolder else {
return
}
downloader.authenticationChallengeResponder?.downloader(downloader, task: task, didReceive: challenge, completionHandler: completionHandler)
}
private func cleanFetchLoad(for url: URL) {
guard let downloader = downloadHolder else {
return
}
downloader.clean(for: url)
if downloader.fetchLoads.isEmpty {
downloadHolder = nil
}
}
private func callCompletionHandlerFailure(error: Error, url: URL) {
guard let downloader = downloadHolder, let fetchLoad = downloader.fetchLoad(for: url) else {
return
}
// We need to clean the fetch load first, before actually calling completion handler.
cleanFetchLoad(for: url)
var leftSignal: Int
repeat {
leftSignal = fetchLoad.cancelSemaphore?.signal() ?? 0
} while leftSignal != 0
for content in fetchLoad.contents {
content.options.callbackDispatchQueue.safeAsync {
content.callback.completionHandler?(nil, error as NSError, url, nil)
}
}
}
private func processImage(for task: URLSessionTask, url: URL) {
guard let downloader = downloadHolder else {
return
}
// We are on main queue when receiving this.
downloader.processQueue.async {
guard let fetchLoad = downloader.fetchLoad(for: url) else {
return
}
self.cleanFetchLoad(for: url)
let data = fetchLoad.responseData as Data
// Cache the processed images. So we do not need to re-process the image if using the same processor.
// Key is the identifier of processor.
var imageCache: [String: Image] = [:]
for content in fetchLoad.contents {
let options = content.options
let completionHandler = content.callback.completionHandler
let callbackQueue = options.callbackDispatchQueue
let processor = options.processor
var image = imageCache[processor.identifier]
if image == nil {
image = processor.process(item: .data(data), options: options)
// Add the processed image to cache.
// If `image` is nil, nothing will happen (since the key is not existing before).
imageCache[processor.identifier] = image
}
if let image = image {
downloader.delegate?.imageDownloader(downloader, didDownload: image, for: url, with: task.response)
if options.backgroundDecode {
let decodedImage = image.kf.decoded
callbackQueue.safeAsync { completionHandler?(decodedImage, nil, url, data) }
} else {
callbackQueue.safeAsync { completionHandler?(image, nil, url, data) }
}
} else {
if let res = task.response as? HTTPURLResponse , res.statusCode == 304 {
let notModified = NSError(domain: KingfisherErrorDomain, code: KingfisherError.notModified.rawValue, userInfo: nil)
completionHandler?(nil, notModified, url, nil)
continue
}
let badData = NSError(domain: KingfisherErrorDomain, code: KingfisherError.badData.rawValue, userInfo: nil)
callbackQueue.safeAsync { completionHandler?(nil, badData, url, nil) }
}
}
}
}
}
// Placeholder. For retrieving extension methods of ImageDownloaderDelegate
extension ImageDownloader: ImageDownloaderDelegate {}
| mit | 2fac17c5a2e865ca3e1ba1866ede86ea | 43.634354 | 227 | 0.661726 | 5.7104 | false | false | false | false |
jspahrsummers/Pistachio | Pistachio/Lens.swift | 1 | 4236 | //
// Lens.swift
// Pistachio
//
// Created by Robert Böhnke on 1/17/15.
// Copyright (c) 2015 Robert Böhnke. All rights reserved.
//
import LlamaKit
public struct Lens<A, B> {
private let get: A -> B
private let set: (A, B) -> A
public init(get: A -> B, set: (A, B) -> A) {
self.get = get
self.set = set
}
public init(get: A -> B, set: (inout A, B) -> ()) {
self.get = get
self.set = {
var copy = $0; set(©, $1); return copy
}
}
}
// MARK: - Basics
public func get<A, B>(lens: Lens<A, B>, a: A) -> B {
return lens.get(a)
}
public func get<A, B>(lens: Lens<A, B>)(a: A) -> B {
return lens.get(a)
}
public func get<A, B>(lens: Lens<A, B>, a: A?) -> B? {
return map(a, lens.get)
}
public func get<A, B>(lens: Lens<A, B>)(a: A?) -> B? {
return map(a, lens.get)
}
public func set<A, B>(lens: Lens<A, B>, a: A, b: B) -> A {
return lens.set(a, b)
}
public func set<A, B>(lens: Lens<A, B>, a: A)(b: B) -> A {
return lens.set(a, b)
}
public func mod<A, B>(lens: Lens<A, B>, a: A, f: B -> B) -> A {
return set(lens, a, f(get(lens, a)))
}
// MARK: - Compose
public func compose<A, B, C>(left: Lens<A, B>, right: Lens<B, C>) -> Lens<A, C> {
let get: A -> C = { a in
return right.get(left.get(a))
}
let set: (A, C) -> A = { a, c in
return left.set(a, right.set(left.get(a), c))
}
return Lens(get: get, set: set)
}
infix operator >>> {
associativity right
precedence 170
}
public func >>> <A, B, C>(lhs: Lens<A, B>, rhs: Lens<B, C>) -> Lens<A, C> {
return compose(lhs, rhs)
}
infix operator <<< {
associativity right
precedence 170
}
public func <<< <A, B, C>(lhs: Lens<B, C>, rhs: Lens<A, B>) -> Lens<A, C> {
return compose(rhs, lhs)
}
// MARK: - Lift
public func lift<A, B>(lens: Lens<A, B>) -> Lens<[A], [B]> {
let get: [A] -> [B] = { xs in
return map(xs, lens.get)
}
let set: ([A], [B]) -> [A] = { xs, ys in
return map(zip(xs, ys), lens.set)
}
return Lens(get: get, set: set)
}
public func lift<A, B, E>(lens: Lens<A, B>) -> Lens<Result<A, E>, Result<B, E>> {
let get: Result<A, E> -> Result<B, E> = { a in
return a.map(lens.get)
}
let set: (Result<A, E>, Result<B, E>) -> Result<A, E> = { a, b in
return a.flatMap { a in b.map { b in lens.set(a, b) } }
}
return Lens(get: get, set: set)
}
// MARK: - Transform
public func transform<A, B, C, E>(lens: Lens<A, B>, valueTransformer: ValueTransformer<B, C, E>) -> Lens<Result<A, E>, Result<C, E>> {
return transform(lift(lens), valueTransformer)
}
public func transform<A, B, C, E>(lens: Lens<Result<A, E>, Result<B, E>>, valueTransformer: ValueTransformer<B, C, E>) -> Lens<Result<A, E>, Result<C, E>> {
let get: Result<A, E> -> Result<C, E> = { a in
return lens.get(a).flatMap { valueTransformer.transformedValue($0) }
}
let set: (Result<A, E>, Result<C, E>) -> Result<A, E> = { a, c in
return lens.set(a, c.flatMap { valueTransformer.reverseTransformedValue($0) })
}
return Lens(get: get, set: set)
}
// MARK: - Split
public func split<A, B, C, D>(left: Lens<A, B>, right: Lens<C, D>) -> Lens<(A, C), (B, D)> {
let get: (A, C) -> (B, D) = { (a, c) in
return (left.get(a), right.get(c))
}
let set: ((A, C), (B, D)) -> (A, C) = { (fst, snd) in
return (left.set(fst.0, snd.0), right.set(fst.1, snd.1))
}
return Lens(get: get, set: set)
}
infix operator *** {
associativity left
precedence 150
}
public func *** <A, B, C, D>(lhs: Lens<A, B>, rhs: Lens<C, D>) -> Lens<(A, C), (B, D)> {
return split(lhs, rhs)
}
// MARK: - Fanout
public func fanout<A, B, C>(left: Lens<A, B>, right: Lens<A, C>) -> Lens<A, (B, C)> {
let get: A -> (B, C) = { a in
return (left.get(a), right.get(a))
}
let set: (A, (B, C)) -> A = { (a, input) in
return right.set(left.set(a, input.0), input.1)
}
return Lens(get: get, set: set)
}
infix operator &&& {
associativity left
precedence 120
}
public func &&& <A, B, C>(lhs: Lens<A, B>, rhs: Lens<A, C>) -> Lens<A, (B, C)> {
return fanout(lhs, rhs)
}
| mit | 00e0325d089832b968a5e9ac29775adf | 22.786517 | 156 | 0.526925 | 2.628181 | false | false | false | false |
tombuildsstuff/swiftcity | SwiftCity/Entities/BuildAgent.swift | 1 | 1365 | public struct BuildAgent {
public let agent: BuildAgentSummary
public let connected: Bool
public let enabled: Bool
public let authorized: Bool
public let upToDate: Bool
public let ip: String?
public let properties: Parameters?
public let pool: BuildAgentPoolSummary
init?(dictionary: [String: AnyObject]) {
guard let agent = BuildAgentSummary(dictionary: dictionary),
let connected = dictionary["connected"] as? Bool,
let enabled = dictionary["enabled"] as? Bool,
let authorized = dictionary["authorized"] as? Bool,
let upToDate = dictionary["uptodate"] as? Bool,
let poolDictionary = dictionary["pool"] as? [String: AnyObject],
let pool = BuildAgentPoolSummary(dictionary: poolDictionary)
else {
return nil
}
if let propertiesDictionary = dictionary["properties"] as? [String: AnyObject] {
self.properties = Parameters(dictionary: propertiesDictionary)
} else {
self.properties = nil
}
self.agent = agent
self.connected = connected
self.enabled = enabled
self.authorized = authorized
self.upToDate = upToDate
self.ip = dictionary["ip"] as? String
self.pool = pool
}
} | mit | 0c492697e6a41656196f3855d74d7931 | 34.025641 | 88 | 0.606593 | 5.055556 | false | false | false | false |
JustinM1/S3SignerAWS | Sources/Payload.swift | 1 | 2863 | import OpenCrypto
import Foundation
/// The Payload associated with a request.
///
/// - data: The data of the request.
/// - none: No payload is in the request. i.e. GET request.
/// - unsigned: The size of payload will not go into signature calcuation. Useful if size is unknown at time of signature creation. Less secure as the payload can be changed and the signature won't be effected.
public enum Payload {
case data(Data)
case none
case unsigned
internal var data: Data {
switch self {
case .data(let data):
return data
default:
return "".data(using: .utf8) ?? Data()
}
}
/// Hash the payload being sent to AWS.
/// - Data: Hashed using SHA256
/// - None: Guaranteed no payload being sent, requires an empty string SHA256.
/// - Unsigned: Any size payload will be accepted, wasn't considered in part of the signature.
///
/// - Returns: The hashed hexString.
/// - Throws: Hash Error.
internal func hashed() throws -> String {
switch self {
case .data, .none:
return [UInt8](Data(SHA256.hash(data: data))).hexEncodedString()
case .unsigned:
return "UNSIGNED-PAYLOAD"
}
}
internal var isData: Bool {
switch self {
case .data, .none:
return true
default:
return false
}
}
internal func size() -> String {
switch self {
case .data, .none:
return self.data.count.description
case .unsigned:
return "UNSIGNED-PAYLOAD"
}
}
internal var isUnsigned: Bool {
switch self {
case .unsigned:
return true
default:
return false
}
}
}
// Copied from OpenCrypto for now because it's internal
extension Collection where Element == UInt8 {
func hexEncodedString(uppercase: Bool = false) -> String {
return String(decoding: hexEncodedBytes(uppercase: uppercase), as: Unicode.UTF8.self)
}
func hexEncodedBytes(uppercase: Bool = false) -> [UInt8] {
var bytes = [UInt8]()
bytes.reserveCapacity(count * 2)
let table: [UInt8]
if uppercase {
table = radix16table_uppercase
} else {
table = radix16table_lowercase
}
for byte in self {
bytes.append(table[Int(byte / 16)])
bytes.append(table[Int(byte % 16)])
}
return bytes
}
}
fileprivate let radix16table_uppercase: [UInt8] = [
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46
]
fileprivate let radix16table_lowercase: [UInt8] = [
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66
]
| mit | 6deed1bee3e0ad8f64fbe052d4ec0066 | 27.63 | 210 | 0.582256 | 3.900545 | false | false | false | false |
mike4aday/SwiftlySalesforce | Sources/SwiftlySalesforce/Errors/ResponseError.swift | 1 | 845 | import Foundation
public struct ResponseError: Error {
public var code: String? = nil
public var message: String? = nil
public var fields: [String]? = nil
public let metadata: HTTPURLResponse
private let na = "N/A" // 'Not Applicable' or 'Not Available'
}
extension ResponseError: LocalizedError {
public var errorDescription: String? {
return NSLocalizedString(message ?? na, comment: code ?? na)
}
}
extension ResponseError: CustomDebugStringConvertible {
public var debugDescription: String {
let na = "N/A" // 'Not Applicable' or 'Not Available'
let fieldStr = fields?.joined(separator: ", ") ?? na
return "Salesforce response error. Code: \(code ?? na). Message: \(message ?? na). Fields: \(fieldStr). HTTP Status Code: \(metadata.statusCode))"
}
}
| mit | 5fcdf847d59aad86d8c2a4aa081f8eef | 30.296296 | 154 | 0.653254 | 4.447368 | false | false | false | false |
red-spotted-newts-2014/Im-In | im-in-ios/im-in-ios/untitled folder/APIProfileController.swift | 1 | 2494 | //
// APIController.swift
//
// Created by fahia mohamed on 2014-08-14.
// Copyright (c) 2014 fahia mohamed. All rights reserved.
//
//
import Foundation
protocol APIProfileControllerProtocol {
func didReceiveAPIResults(results: NSDictionary)
func didLogOut(results: NSDictionary)
}
class APIProfileController {
var delegate: APIProfileControllerProtocol?
init() {
}
func loadProfile() {
println("APIController#loadAllEvents")
let urlPath = "http://10.0.2.26:3000/users/profile.json"
let url: NSURL = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
println("Task completed")
if(error) {
// If there is an error in the web request, print it to the console
println(error.localizedDescription)
}
var err: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
if(err != nil) {
// If there is an error parsing JSON, print it to the console
println("JSON Error \(err!.localizedDescription)")
}
self.delegate?.didReceiveAPIResults(jsonResult) // THIS IS THE NEW LINE!!
})
task.resume()
}
func logout() {
println("LOGOUT")
let urlPath = "http://10.0.2.26:3000/users/logout_ios.json"
let url: NSURL = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
println("Task completed")
if(error) {
// If there is an error in the web request, print it to the console
println(error.localizedDescription)
}
var err: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
if(err != nil) {
// If there is an error parsing JSON, print it to the console
println("JSON Error \(err!.localizedDescription)")
}
self.delegate?.didLogOut(jsonResult) // THIS IS THE NEW LINE!!
})
task.resume()
}
} | mit | 290e8e24e390cb908339437b17503325 | 36.80303 | 151 | 0.60425 | 4.899804 | false | false | false | false |
christophhagen/Signal-iOS | Signal/src/Jobs/MultiDeviceProfileKeyUpdateJob.swift | 1 | 2732 | //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import Foundation
import PromiseKit
import SignalServiceKit
import SignalMessaging
/**
* Used to distribute our profile key to legacy linked devices, newly linked devices will have our profile key as part of provisioning.
* Syncing is accomplished via the existing contact syncing mechanism, except the only contact synced is ourself. It's incumbent on the linked device
* to treat this "self contact" record specially.
*/
@objc class MultiDeviceProfileKeyUpdateJob: NSObject {
let TAG = "[MultiDeviceProfileKeyUpdateJob]"
let profileKey: OWSAES256Key
let identityManager: OWSIdentityManager
let messageSender: MessageSender
let profileManager: OWSProfileManager
required init(profileKey: OWSAES256Key, identityManager: OWSIdentityManager, messageSender: MessageSender, profileManager: OWSProfileManager) {
self.profileKey = profileKey
self.identityManager = identityManager
self.messageSender = messageSender
self.profileManager = profileManager
}
class func run(profileKey: OWSAES256Key, identityManager: OWSIdentityManager, messageSender: MessageSender, profileManager: OWSProfileManager) {
return self.init(profileKey: profileKey, identityManager: identityManager, messageSender: messageSender, profileManager: profileManager).run()
}
func run(retryDelay: TimeInterval = 1) {
guard let localNumber = TSAccountManager.localNumber() else {
owsFail("\(self.TAG) localNumber was unexpectedly nil")
return
}
let localSignalAccount = SignalAccount(recipientId: localNumber)
localSignalAccount.contact = Contact()
let syncContactsMessage = OWSSyncContactsMessage(signalAccounts: [localSignalAccount],
identityManager: self.identityManager,
profileManager: self.profileManager)
let dataSource = DataSourceValue.dataSource(withSyncMessage: syncContactsMessage.buildPlainTextAttachmentData())
self.messageSender.enqueueTemporaryAttachment(dataSource,
contentType: OWSMimeTypeApplicationOctetStream,
in: syncContactsMessage,
success: {
Logger.info("\(self.TAG) Successfully synced profile key")
},
failure: { error in
Logger.error("\(self.TAG) in \(#function) failed with error: \(error) retrying in \(retryDelay)s.")
after(interval: retryDelay).then {
self.run(retryDelay: retryDelay * 2)
}.retainUntilComplete()
})
}
}
| gpl-3.0 | bc5c8a516841a6a826351775ccc6466c | 43.064516 | 150 | 0.685944 | 5.453094 | false | false | false | false |
pyconjp/pyconjp-ios | PyConJP/Protocol/DummyJSON/DummyTalksProtocol.swift | 1 | 980 | //
// DummyTalksProtocol.swift
// PyConJP
//
// Created by Yutaro Muta on 2017/06/14.
// Copyright © 2017 PyCon JP. All rights reserved.
//
import Foundation
import Result
protocol DummyTalksProtocol {
func getTalksFromLocalDummyJSON(completionHandler: ((Result<[TalkObject], NSError>) -> Void))
}
extension DummyTalksProtocol {
func getTalksFromLocalDummyJSON(completionHandler: ((Result<[TalkObject], NSError>) -> Void)) {
let path = Bundle.main.path(forResource: "DummyTalks", ofType: "json")
let fileHandle = FileHandle(forReadingAtPath: path!)
let data = fileHandle?.readDataToEndOfFile()
let dictionary = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String: Any]
let presentations = dictionary["presentations"] as? [[String: Any]] ?? [[String: Any]]()
completionHandler(.success(presentations.flatMap({ TalkObject(object: $0) })))
}
}
| mit | 3232a92f45f3fafc3efe59ae210f82c7 | 30.580645 | 115 | 0.673136 | 4.219828 | false | false | false | false |
ZwxWhite/V2EX | V2EX/V2EX/Class/Controller/Other(其他)/UserInfoViewController.swift | 1 | 2562 | //
// UserInfoViewController.swift
// V2EX
//
// Created by wenxuan.zhang on 16/3/7.
// Copyright © 2016年 张文轩. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class UserInfoViewController: UIViewController {
var username: String?
var user: V2UserModel?
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.loadData()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
title = username
}
private func loadData() {
guard let username = username where username.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0 else { return }
request(.GET, "https://www.v2ex.com/api/members/show.json", parameters: ["username": username], encoding: .URL, headers: nil).responseJSON { (response) -> Void in
switch response.result {
case .Success(let responseJson):
self.user = V2UserModel()
self.user?.setupWithJson(JSON(responseJson))
self.tableView.reloadData()
case .Failure(let error):
printLog(error)
}
}
}
}
extension UserInfoViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MemberInfoHeaderCell") as! MemberInfoHeaderCell
if let avatarImageURL = user?.avatar_normal where avatarImageURL.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0 {
let avatarImageView = cell.contentView.viewWithTag(1000) as! UIImageView
avatarImageView.kf_setImageWithURL(NSURL(string: v2exHttps(true) + avatarImageURL)!, placeholderImage: UIImage(named: "avatar_default"))
}
if let index = user?.id, _ = username where index > 0 {
let indexLabel = cell.contentView.viewWithTag(1001) as! UILabel
indexLabel.text = username! + " " + "V2EX 第 \(index) 号会员"
}
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 200
}
} | mit | 5ef3fbbe5faa6eff98d8ff5293d7559c | 32.5 | 170 | 0.646365 | 4.980431 | false | false | false | false |
ProfileCreator/ProfileCreator | ProfileCreator/ProfileCreator/Profile Editor TableView CellViews/PayloadCellViewFooter.swift | 1 | 7468 | //
// PayloadCellViewPadding.swift
// ProfileCreator
//
// Created by Erik Berglund.
// Copyright © 2018 Erik Berglund. All rights reserved.
//
import Cocoa
import ProfilePayloads
class PayloadCellViewFooter: NSTableCellView, ProfileCreatorCellView {
// MARK: -
// MARK: PayloadCellView Variables
var height: CGFloat = 0.0
let separator = NSBox(frame: NSRect(x: 250.0, y: 15.0, width: kPreferencesWindowWidth - (20.0 + 20.0), height: 250.0))
var textFieldRow1 = NSTextField()
var textFieldRow2: NSTextField?
// MARK: -
// MARK: Initialization
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(row1: String, row2 row2String: String?) {
super.init(frame: NSRect.zero)
// ---------------------------------------------------------------------
// Setup Variables
// ---------------------------------------------------------------------
var constraints = [NSLayoutConstraint]()
// ---------------------------------------------------------------------
// Create and add vertical separator
// ---------------------------------------------------------------------
self.setup(separator: self.separator, constraints: &constraints)
// ---------------------------------------------------------------------
// Setup Static View Content
// ---------------------------------------------------------------------
// Row 1
self.setup(row: self.textFieldRow1, lastRow: nil, constraints: &constraints)
self.textFieldRow1.stringValue = row1
// Row 2
if let row2 = row2String {
self.textFieldRow2 = NSTextField()
self.setup(row: self.textFieldRow2!, lastRow: self.textFieldRow1, constraints: &constraints)
self.textFieldRow2?.stringValue = row2
}
// ---------------------------------------------------------------------
// Add spacing to bottom
// ---------------------------------------------------------------------
self.updateHeight(34.0)
// ---------------------------------------------------------------------
// Activate Layout Constraints
// ---------------------------------------------------------------------
NSLayoutConstraint.activate(constraints)
}
func updateHeight(_ height: CGFloat) {
self.height += height
}
// MARK: -
// MARK: Setup Layout Constraints
private func setup(row: NSTextField, lastRow: NSTextField?, constraints: inout [NSLayoutConstraint]) {
// ---------------------------------------------------------------------
// Add TextField to TableCellView
// ---------------------------------------------------------------------
self.addSubview(row)
row.translatesAutoresizingMaskIntoConstraints = false
row.lineBreakMode = .byWordWrapping
row.isBordered = false
row.isBezeled = false
row.drawsBackground = false
row.isEditable = false
row.isSelectable = false
row.textColor = .tertiaryLabelColor
row.preferredMaxLayoutWidth = kEditorTableViewColumnPayloadWidth
row.alignment = .center
row.font = NSFont.systemFont(ofSize: 10, weight: .light)
// ---------------------------------------------------------------------
// Add constraints
// ---------------------------------------------------------------------
// Top
if let lastRowTextField = lastRow {
constraints.append(NSLayoutConstraint(item: row,
attribute: .top,
relatedBy: .equal,
toItem: lastRowTextField,
attribute: .bottom,
multiplier: 1.0,
constant: 2.0))
self.updateHeight(8 + row.intrinsicContentSize.height)
} else {
constraints.append(NSLayoutConstraint(item: row,
attribute: .top,
relatedBy: .equal,
toItem: self.separator,
attribute: .top,
multiplier: 1.0,
constant: 8.0))
self.updateHeight(16 + row.intrinsicContentSize.height)
}
// Leading
constraints.append(NSLayoutConstraint(item: row,
attribute: .leading,
relatedBy: .equal,
toItem: self,
attribute: .leading,
multiplier: 1.0,
constant: 8.0))
// Trailing
constraints.append(NSLayoutConstraint(item: self,
attribute: .trailing,
relatedBy: .equal,
toItem: row,
attribute: .trailing,
multiplier: 1.0,
constant: 8.0))
}
private func setup(separator: NSBox, constraints: inout [NSLayoutConstraint]) {
separator.translatesAutoresizingMaskIntoConstraints = false
separator.boxType = .separator
// ---------------------------------------------------------------------
// Add TextField to TableCellView
// ---------------------------------------------------------------------
self.addSubview(separator)
constraints.append(NSLayoutConstraint(item: separator,
attribute: .top,
relatedBy: .equal,
toItem: self,
attribute: .top,
multiplier: 1,
constant: 16.0))
// Leading
constraints.append(NSLayoutConstraint(item: separator,
attribute: .leading,
relatedBy: .equal,
toItem: self,
attribute: .leading,
multiplier: 1,
constant: 8.0))
// Trailing
constraints.append(NSLayoutConstraint(item: self,
attribute: .trailing,
relatedBy: .equal,
toItem: separator,
attribute: .trailing,
multiplier: 1,
constant: 8.0))
}
}
| mit | 3d9bbddf8958d578474566a04ece0655 | 42.16185 | 122 | 0.37284 | 7.327772 | false | false | false | false |
xusader/firefox-ios | Client/Frontend/Settings/SearchSettingsTableViewController.swift | 3 | 8717 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
class SearchSettingsTableViewController: UITableViewController {
private let SectionDefault = 0
private let ItemDefaultEngine = 0
private let ItemDefaultSuggestions = 1
private let NumberOfItemsInSectionDefault = 2
private let SectionOrder = 1
private let NumberOfSections = 2
var model: SearchEngines!
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = NSLocalizedString("Search", comment: "Navigation title for search settings.")
// To allow re-ordering the list of search engines at all times.
tableView.editing = true
// So that we push the default search engine controller on selection.
tableView.allowsSelectionDuringEditing = true
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell!
var engine: OpenSearchEngine!
if indexPath.section == SectionDefault {
switch indexPath.item {
case ItemDefaultEngine:
engine = model.defaultEngine
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil)
cell.editingAccessoryType = UITableViewCellAccessoryType.DisclosureIndicator
cell.accessibilityLabel = NSLocalizedString("Default Search Engine", comment: "Accessibility label for default search engine setting.")
cell.accessibilityValue = engine.shortName
cell.textLabel?.text = engine.shortName
cell.imageView?.image = engine.image
case ItemDefaultSuggestions:
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil)
cell.textLabel?.text = NSLocalizedString("Show search suggestions", comment: "Label for show search suggestions setting.")
let toggle = UISwitch()
toggle.addTarget(self, action: "SELdidToggleSearchSuggestions:", forControlEvents: UIControlEvents.ValueChanged)
toggle.on = model.shouldShowSearchSuggestions
cell.editingAccessoryView = toggle
default:
// Should not happen.
break
}
} else {
// The default engine is not a quick search engine.
let index = indexPath.item + 1
engine = model.orderedEngines[index]
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil)
cell.showsReorderControl = true
let toggle = UISwitch()
// This is an easy way to get from the toggle control to the corresponding index.
toggle.tag = index
toggle.addTarget(self, action: "SELdidToggleEngine:", forControlEvents: UIControlEvents.ValueChanged)
toggle.on = model.isEngineEnabled(engine)
cell.editingAccessoryView = toggle
cell.textLabel?.text = engine.shortName
cell.imageView?.image = engine.image
}
// So that the seperator line goes all the way to the left edge.
cell.separatorInset = UIEdgeInsetsZero
return cell
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return NumberOfSections
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == SectionDefault {
return NumberOfItemsInSectionDefault
} else {
// The first engine -- the default engine -- is not shown in the quick search engine list.
return model.orderedEngines.count - 1
}
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == SectionDefault {
return NSLocalizedString("Default Search Engine", comment: "Title for default search engine settings section.")
} else {
return NSLocalizedString("Quick-search Engines", comment: "Title for quick-search engines settings section.")
}
}
override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
if indexPath.section == SectionDefault && indexPath.item == ItemDefaultEngine {
let searchEnginePicker = SearchEnginePicker()
// Order alphabetically, so that picker is always consistently ordered.
// Every engine is a valid choice for the default engine, even the current default engine.
searchEnginePicker.engines = model.orderedEngines.sorted { e, f in e.shortName < f.shortName }
searchEnginePicker.delegate = self
searchEnginePicker.selectedSearchEngineName = model.defaultEngine.shortName
navigationController?.pushViewController(searchEnginePicker, animated: true)
}
return nil
}
// Don't show delete button on the left.
override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
return UITableViewCellEditingStyle.None
}
// Don't reserve space for the delete button on the left.
override func tableView(tableView: UITableView, shouldIndentWhileEditingRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
// Hide a thin vertical line that iOS renders between the accessoryView and the reordering control.
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if cell.editing {
for v in cell.subviews as! [UIView] {
if v.frame.width == 1.0 {
v.backgroundColor = UIColor.clearColor()
}
}
}
}
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
if indexPath.section == SectionDefault {
return false
} else {
return true
}
}
override func tableView(tableView: UITableView, moveRowAtIndexPath indexPath: NSIndexPath, toIndexPath newIndexPath: NSIndexPath) {
// The first engine (default engine) is not shown in the list, so the indices are off-by-1.
let index = indexPath.item + 1
let newIndex = newIndexPath.item + 1
let engine = model.orderedEngines.removeAtIndex(index)
model.orderedEngines.insert(engine, atIndex: newIndex)
tableView.reloadData()
}
// Snap to first or last row of the list of engines.
override func tableView(tableView: UITableView, targetIndexPathForMoveFromRowAtIndexPath sourceIndexPath: NSIndexPath, toProposedIndexPath proposedDestinationIndexPath: NSIndexPath) -> NSIndexPath {
// You can't drag or drop on the default engine.
if sourceIndexPath.section == SectionDefault || proposedDestinationIndexPath.section == SectionDefault {
return sourceIndexPath
}
if (sourceIndexPath.section != proposedDestinationIndexPath.section) {
var row = 0
if (sourceIndexPath.section < proposedDestinationIndexPath.section) {
row = tableView.numberOfRowsInSection(sourceIndexPath.section) - 1
}
return NSIndexPath(forRow: row, inSection: sourceIndexPath.section)
}
return proposedDestinationIndexPath
}
func SELdidToggleEngine(toggle: UISwitch) {
let engine = model.orderedEngines[toggle.tag] // The tag is 1-based.
if toggle.on {
model.enableEngine(engine)
} else {
model.disableEngine(engine)
}
}
func SELdidToggleSearchSuggestions(toggle: UISwitch) {
// Setting the value in settings dismisses any opt-in.
model.shouldShowSearchSuggestionsOptIn = false
model.shouldShowSearchSuggestions = toggle.on
}
func SELcancel() {
navigationController?.popViewControllerAnimated(true)
}
}
extension SearchSettingsTableViewController: SearchEnginePickerDelegate {
func searchEnginePicker(searchEnginePicker: SearchEnginePicker, didSelectSearchEngine searchEngine: OpenSearchEngine?) {
if let engine = searchEngine {
model.defaultEngine = engine
self.tableView.reloadData()
}
navigationController?.popViewControllerAnimated(true)
}
}
| mpl-2.0 | f322c19547e3750ee398aa9b23bb8ae0 | 42.80402 | 202 | 0.673167 | 5.901828 | false | false | false | false |
sergdort/CleanArchitectureRxSwift | CleanArchitectureRxSwiftTests/Scenes/AllPosts/PostsUseCaseMock.swift | 1 | 702 | @testable import CleanArchitectureRxSwift
import RxSwift
import Domain
class PostsUseCaseMock: Domain.PostsUseCase {
var posts_ReturnValue: Observable<[Post]> = Observable.just([])
var posts_Called = false
var save_ReturnValue: Observable<Void> = Observable.just(())
var save_Called = false
var delete_ReturnValue: Observable<Void> = Observable.just(())
var delete_Called = false
func posts() -> Observable<[Post]> {
posts_Called = true
return posts_ReturnValue
}
func save(post: Post) -> Observable<Void> {
save_Called = true
return save_ReturnValue
}
func delete(post: Post) -> Observable<Void> {
delete_Called = true
return delete_ReturnValue
}
}
| mit | 2b1a9b3dce5985cb83fb4c35ad587e86 | 25 | 65 | 0.706553 | 4.129412 | false | false | false | false |
DeliciousRaspberryPi/ShameGame | Sources/ShameGame/LionlyProgressTracker.swift | 1 | 4147 | import Kitura
import KituraNet
import LoggerAPI
import SwiftyJSON
import Dispatch
import Foundation
public class LionlyProgressTracker {
public let router = Router()
let queue = DispatchQueue(label: "com.pridelands.lionlyProgressTracker")
public init() {
router.all("/", middleware: BodyParser())
//MARK: 'Person' routes
router.get("/v1/persons", handler: getPeople)
router.get("/v1/persons/:name", handler: getPerson)
router.post("/v1/persons", handler: createPerson)
router.put("/v1/persons", handler: putPerson)
router.patch("/v1/persons/:name", handler: patchPerson)
router.delete("/v1/persons/:name", handler: deletePerson)
}
}
//MARK: - Person CrUD
extension LionlyProgressTracker {
func getPeople(request: RouterRequest, response: RouterResponse, next: @escaping() -> Void) throws {
let peopleJSON = JSON(sharedPersonDatabase.map({$1}).stringValuePairs)
try response.send(peopleJSON.rawString(encoding: .utf8, options: .prettyPrinted) ?? "").end()
}
func getPerson(request: RouterRequest, response: RouterResponse, next: @escaping() -> Void) throws {
guard let requestedPerson = sharedPersonDatabase[request.parameters["name"] ?? ""] else {
response.statusCode = .notFound
try response.send("").end()
return
}
let personJSON = JSON(requestedPerson.stringValuePairs)
try response.send(personJSON.rawString(encoding: .utf8, options: .prettyPrinted) ?? "").end()
}
func createPerson(request: RouterRequest, response: RouterResponse, next: @escaping() -> Void) throws {
guard let parsedBody = request.body,
case .json(let jsonBody) = parsedBody else {
response.statusCode = .badRequest
try response.send("").end()
return
}
guard let person = Person(json: jsonBody) else {
response.statusCode = .unprocessableEntity
try response.send("").end()
return
}
sharedPersonDatabase[person.name] = person
try response.send("").end()
}
func putPerson(request: RouterRequest, response: RouterResponse, next: @escaping() -> Void) throws {
guard let selectedPerson = sharedPersonDatabase[request.parameters["name"] ?? ""] else {
response.statusCode = .notFound
try response.send("").end()
return
}
selectedPerson.habits = [:]
try patchPerson(request: request, response: response, next: next)
}
func patchPerson(request: RouterRequest, response: RouterResponse, next: @escaping() -> Void) throws {
guard let body = request.body,
case .json(let jsonBody) = body else {
response.statusCode = .badRequest
try response.send("").end()
return
}
guard let selectedPerson = sharedPersonDatabase[request.parameters["name"] ?? ""] else {
response.statusCode = .notFound
try response.send("").end()
return
}
selectedPerson.name = jsonBody["name"].string ?? selectedPerson.name
selectedPerson.avatarURL = URL(string: jsonBody["avatarURL"].stringValue) ?? selectedPerson.avatarURL
let newHabits = jsonBody["habits"].array?.flatMap({ Habit(json: $0) }) ?? []
newHabits.forEach {
if let existingHabit = selectedPerson.habits[$0.name] { existingHabit.entriesContainer.merge(other: $0.entriesContainer) }
else { selectedPerson.habits[$0.name] = $0 }
}
let personJSON = JSON(selectedPerson.stringValuePairs)
try response.send(personJSON.rawString(encoding: .utf8, options: .prettyPrinted) ?? "").end()
}
func deletePerson(request: RouterRequest, response: RouterResponse, next: @escaping() -> Void) throws {
sharedPersonDatabase.removeValue(forKey: request.parameters["name"] ?? "")
try response.send("").end()
}
}
| apache-2.0 | 7cda0cdb15f7658a35a00450a419ef79 | 38.875 | 134 | 0.616349 | 4.659551 | false | false | false | false |
taewan0530/TWPageEmbed | TWPageEmbedViewControllerDemo/TWPageEmbedViewControllerDemo/ViewController.swift | 1 | 1211 | //
// ViewController.swift
// TWPageEmbedViewControllerDemo
//
// Created by kimtaewan on 2015. 12. 24..
// Copyright © 2015년 prnd. All rights reserved.
//
import UIKit
class ViewController: TWContainerEmbedController {
// var containerEmbedController: TWContainerEmbedController!
override func viewDidLoad() {
super.viewDidLoad()
self.currentSegueIdentifier = "first"
// 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.
}
@IBAction func tapFirst(_ sender: AnyObject) {
self.currentSegueIdentifier = "first"
}
@IBAction func tapSecound(_ sender: AnyObject) {
self.currentSegueIdentifier = "secound"
}
// override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// super.prepareForSegue(segue, sender: sender)
// if segue.identifier == "container" {
// print("!@!@!")
// self.containerEmbedController = segue.destinationViewController as? TWContainerEmbedController
// }
// }
}
| mit | 4b27c2ca8a64d1054596b69ae03a577f | 27.093023 | 108 | 0.663907 | 4.490706 | false | false | false | false |
waterskier2007/NVActivityIndicatorView | NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallTrianglePath.swift | 1 | 5255 | //
// NVActivityIndicatorAnimationBallTrianglePath.swift
// NVActivityIndicatorViewDemo
//
// The MIT License (MIT)
// Copyright (c) 2016 Vinh Nguyen
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
class NVActivityIndicatorAnimationBallTrianglePath: NVActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let circleSize = size.width / 5
let deltaX = size.width / 2 - circleSize / 2
let deltaY = size.height / 2 - circleSize / 2
let x = (layer.bounds.width - size.width) / 2
let y = (layer.bounds.height - size.height) / 2
let duration: CFTimeInterval = 2
let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
// Animation
let animation = CAKeyframeAnimation(keyPath: "transform")
animation.keyTimes = [0, 0.33, 0.66, 1]
animation.timingFunctions = [timingFunction, timingFunction, timingFunction]
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Top-center circle
let topCenterCircle = NVActivityIndicatorShape.ring.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color)
changeAnimation(animation, values: ["{0,0}", "{hx,fy}", "{-hx,fy}", "{0,0}"], deltaX: deltaX, deltaY: deltaY)
topCenterCircle.frame = CGRect(x: x + size.width / 2 - circleSize / 2, y: y, width: circleSize, height: circleSize)
topCenterCircle.add(animation, forKey: "animation")
layer.addSublayer(topCenterCircle)
// Bottom-left circle
let bottomLeftCircle = NVActivityIndicatorShape.ring.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color)
changeAnimation(animation, values: ["{0,0}", "{hx,-fy}", "{fx,0}", "{0,0}"], deltaX: deltaX, deltaY: deltaY)
bottomLeftCircle.frame = CGRect(x: x, y: y + size.height - circleSize, width: circleSize, height: circleSize)
bottomLeftCircle.add(animation, forKey: "animation")
layer.addSublayer(bottomLeftCircle)
// Bottom-right circle
let bottomRightCircle = NVActivityIndicatorShape.ring.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color)
changeAnimation(animation, values: ["{0,0}", "{-fx,0}", "{-hx,-fy}", "{0,0}"], deltaX: deltaX, deltaY: deltaY)
bottomRightCircle.frame = CGRect(x: x + size.width - circleSize, y: y + size.height - circleSize, width: circleSize, height: circleSize)
bottomRightCircle.add(animation, forKey: "animation")
layer.addSublayer(bottomRightCircle)
}
func changeAnimation(_ animation: CAKeyframeAnimation, values rawValues: [String], deltaX: CGFloat, deltaY: CGFloat) {
let values = NSMutableArray(capacity: 5)
for rawValue in rawValues {
let point = CGPointFromString(translateString(rawValue, deltaX: deltaX, deltaY: deltaY))
values.add(NSValue(caTransform3D: CATransform3DMakeTranslation(point.x, point.y, 0)))
}
animation.values = values as [AnyObject]
}
func translateString(_ valueString: String, deltaX: CGFloat, deltaY: CGFloat) -> String {
let valueMutableString = NSMutableString(string: valueString)
let fullDeltaX = 2 * deltaX
let fullDeltaY = 2 * deltaY
var range = NSMakeRange(0, valueMutableString.length)
valueMutableString.replaceOccurrences(of: "hx", with: "\(deltaX)", options: NSString.CompareOptions.caseInsensitive, range: range)
range.length = valueMutableString.length
valueMutableString.replaceOccurrences(of: "fx", with: "\(fullDeltaX)", options: NSString.CompareOptions.caseInsensitive, range: range)
range.length = valueMutableString.length
valueMutableString.replaceOccurrences(of: "hy", with: "\(deltaY)", options: NSString.CompareOptions.caseInsensitive, range: range)
range.length = valueMutableString.length
valueMutableString.replaceOccurrences(of: "fy", with: "\(fullDeltaY)", options: NSString.CompareOptions.caseInsensitive, range: range)
return valueMutableString as String
}
}
| mit | 78e84b89954dc2c57bfc177edca700db | 50.519608 | 144 | 0.707136 | 4.621812 | false | false | false | false |
cheft/30DaysofDesign | 05-Life/code/Life/Life/ViewController.swift | 1 | 1411 | //
// ViewController.swift
// Life
//
// Created by chenhaifeng on 16/10/26.
// Copyright © 2016年 cheft. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var lifeTime: UILabel!
@IBOutlet weak var lifeTip: UILabel!
var timer = Timer()
var count = 10
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.
}
override var preferredStatusBarStyle: UIStatusBarStyle {
get {
return UIStatusBarStyle.lightContent
}
}
@IBAction func continueLife(_ sender: UIButton) {
if timer == nil {
lifeTip.text = "指纹续命"
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.lifeTick), userInfo: nil, repeats: true)
} else {
count = count + 10
}
lifeTime.text = String(count)
}
func lifeTick() {
if (count == 0) {
timer.invalidate()
timer = Timer()
lifeTip.text = "卒,荣获新生命!"
return
}
count = count - 1
lifeTime.text = String(count)
}
}
| mit | b5fc5f9a5e0a40b76ec2f4d5cbbe6926 | 24.163636 | 147 | 0.58526 | 4.464516 | false | false | false | false |
antonio081014/LeetCode-CodeBase | Swift/find-duplicate-file-in-system.swift | 2 | 1164 | /**
* https://leetcode.com/problems/find-duplicate-file-in-system/
*
*
*/
// Date: Tue May 18 14:06:06 PDT 2021
class Solution {
func findDuplicate(_ paths: [String]) -> [[String]] {
var dict = [String : [String]]()
for path in paths {
let fileList = pathToFile(path)
for (path, content) in fileList {
dict[content, default: []].append(path)
}
}
var result = [[String]]()
for value in dict.values {
if value.count > 1 {
result.append(value)
}
}
return result
}
private func pathToFile(_ filePath: String) -> [(path: String, content: String)] {
var result = [(String, String)]()
let components = filePath.components(separatedBy: " ")
let root = components.first!
for index in 1 ..< components.count {
let text = components[index].components(separatedBy: "(")
let path = root + "/" + text[0]
let content = String(text[1].dropLast())
result.append((path: path, content: content))
}
return result
}
} | mit | 386dad54d1a8807ea85b18c7d0ecdea9 | 30.486486 | 86 | 0.524914 | 4.311111 | false | false | false | false |
mittenimraum/CVGenericDataSource | Example/CVGenericDataSourceExample/Classes/Coordination/LoadingCoordinator.swift | 1 | 1233 | //
// LoadingCoordinator.swift
// CVGenericDataSourceExample
//
// Created by Stephan Schulz on 22.04.17.
// Copyright © 2017 Stephan Schulz. All rights reserved.
//
import Foundation
import UIKit
import CVGenericDataSource
class LoadingCoordinator: NSObject, CoordinatorProtocol {
// MARK: - Variables <CoordinatorProtocol>
var parentCoordinator: CoordinatorProtocol?
var childCoordinators: [CoordinatorProtocol] = []
// MARK: - Variables
var navigationController: UINavigationController!
var loadingViewController: LoadingViewController!
// MARK: - Init
init(parentCoordinator: CoordinatorProtocol?, navigationController: UINavigationController) {
super.init()
self.parentCoordinator = parentCoordinator
self.navigationController = navigationController
}
// MARK: - CoordinatorProtocol
func start() {
loadingViewController = LoadingViewController(nibName: String(describing: LoadingViewController.self), bundle: nil)
loadingViewController.viewModel = LoadingViewModel(coordinator: self)
navigationController.pushViewController(loadingViewController, animated: true)
}
}
| mit | eb6ad20287aac9e8d6f1deb0ed58452c | 28.333333 | 123 | 0.715097 | 5.703704 | false | false | false | false |
diegosanchezr/Chatto | ChattoApp/ChattoApp/ChatItemsDemoDecorator.swift | 1 | 3926 | /*
The MIT License (MIT)
Copyright (c) 2015-present Badoo Trading Limited.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import Foundation
import Chatto
import ChattoAdditions
final class ChatItemsDemoDecorator: ChatItemsDecoratorProtocol {
struct Constants {
static let shortSeparation: CGFloat = 3
static let normalSeparation: CGFloat = 10
static let timeIntervalThresholdToIncreaseSeparation: NSTimeInterval = 120
}
func decorateItems(chatItems: [ChatItemProtocol]) -> [DecoratedChatItem] {
var decoratedChatItems = [DecoratedChatItem]()
for (index, chatItem) in chatItems.enumerate() {
let next: ChatItemProtocol? = (index + 1 < chatItems.count) ? chatItems[index + 1] : nil
let bottomMargin = self.separationAfterItem(chatItem, next: next)
var showsTail = false
var additionalItems = [DecoratedChatItem]()
if let currentMessage = chatItem as? MessageModelProtocol {
if let nextMessage = next as? MessageModelProtocol {
showsTail = currentMessage.senderId != nextMessage.senderId
} else {
showsTail = true
}
if self.showsStatusForMessage(currentMessage) {
additionalItems.append(
DecoratedChatItem(
chatItem: SendingStatusModel(uid: "\(currentMessage.uid)-decoration-status", status: currentMessage.status),
decorationAttributes: nil)
)
}
}
decoratedChatItems.append(DecoratedChatItem(
chatItem: chatItem,
decorationAttributes: ChatItemDecorationAttributes(bottomMargin: bottomMargin, showsTail: showsTail))
)
decoratedChatItems.appendContentsOf(additionalItems)
}
return decoratedChatItems
}
func separationAfterItem(current: ChatItemProtocol?, next: ChatItemProtocol?) -> CGFloat {
guard let nexItem = next else { return 0 }
guard let currentMessage = current as? MessageModelProtocol else { return Constants.normalSeparation }
guard let nextMessage = nexItem as? MessageModelProtocol else { return Constants.normalSeparation }
if self.showsStatusForMessage(currentMessage) {
return 0
} else if currentMessage.senderId != nextMessage.senderId {
return Constants.normalSeparation
} else if nextMessage.date.timeIntervalSinceDate(currentMessage.date) > Constants.timeIntervalThresholdToIncreaseSeparation {
return Constants.normalSeparation
} else {
return Constants.shortSeparation
}
}
func showsStatusForMessage(message: MessageModelProtocol) -> Bool {
return message.status == .Failed || message.status == .Sending
}
}
| mit | f918df55c324fb9b66fb36d74716888f | 42.142857 | 136 | 0.682374 | 5.437673 | false | false | false | false |
GargoyleSoft/RFC5545 | RFC5545/EKRecurrenceRule.swift | 1 | 13386 | //
// EKRecurrenceRule.swift
//
// Copyright © 2016 Gargoyle Software, LLC.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import EventKit
/**
* Splits the input string by comma and returns an array of all values which are less than the
* constraint value.
*
* - Parameter lessThan: The value that the numbers must be less than.
* - Parameter csv: The comma separated input data.
*
* - Throws: `RFC5545Exception.InvalidRecurrenceRule`
*
* - Returns: An array of `Int`
*/
private func allValues(lessThan: Int, csv: String) throws -> [Int] {
var ret: [Int] = []
for dayNum in csv.components(separatedBy: ",") {
guard let num = Int(dayNum) , abs(num) < lessThan else {
throw RFC5545Exception.invalidRecurrenceRule
}
ret.append(num)
}
return ret
}
extension EKRecurrenceRule {
/**
* Converts the recurrence rule into an RFC5545 compatible format.
*
* - Returns: The generated RFC5545 RRULE string.
*
* - SeeAlso: [RFC5545 RRULE](https://tools.ietf.org/html/rfc5545#section-3.8.5.3)
* - SeeAlso: [RFC5545 RECUR](https://tools.ietf.org/html/rfc5545#section-3.3.10)
*/
func rfc5545() -> String {
let freq: String
switch frequency {
case .daily:
freq = "DAILY"
case .monthly:
freq = "MONTHLY"
case .weekly:
freq = "WEEKLY"
case .yearly:
freq = "YEARLY"
}
var text = "RRULE:FREQ=\(freq)"
if interval > 1 {
text += ";INTERVAL=\(interval)"
}
if firstDayOfTheWeek > 0 {
let days = ["", "SU", "MO", "TU", "WE", "TH", "FR", "SA"]
text += ";WKST=" + days[firstDayOfTheWeek]
}
if let end = recurrenceEnd {
if let date = end.endDate {
/*
TODO: Implement this timezone stuff from the RFC spec:
The UNTIL rule part defines a DATE or DATE-TIME value that bounds
the recurrence rule in an inclusive manner. If the value
specified by UNTIL is synchronized with the specified recurrence,
this DATE or DATE-TIME becomes the last instance of the
recurrence. The value of the UNTIL rule part MUST have the same
value type as the "DTSTART" property. Furthermore, if the
"DTSTART" property is specified as a date with local time, then
the UNTIL rule part MUST also be specified as a date with local
time. If the "DTSTART" property is specified as a date with UTC
time or a date with local time and time zone reference, then the
UNTIL rule part MUST be specified as a date with UTC time. In the
case of the "STANDARD" and "DAYLIGHT" sub-components the UNTIL
rule part MUST always be specified as a date with UTC time. If
specified as a DATE-TIME value, then it MUST be specified in a UTC
time format. If not present, and the COUNT rule part is also not
present, the "RRULE" is considered to repeat forever.
*/
text += ";UNTIL=\(date.rfc5545(format: .utc))"
} else {
text += ";COUNT=\(end.occurrenceCount)"
}
}
return text
}
/**
* Parse an RFC5545 RRULE specification and return an `EKRecurrenceRule`
*
* - Parameter rrule: The RFC5545 block representing an RRULE.
*
* - Throws: An `RFC5545Exception` if something goes wrong.
*
* - Returns: An `EKRecurrenceRule`
*
* - SeeAlso: [RFC5545 RRULE](https://tools.ietf.org/html/rfc5545#section-3.8.5.3)
* - SeeAlso: [RFC5545 RECUR](https://tools.ietf.org/html/rfc5545#section-3.3.10)
*/
convenience init(rrule: String) throws {
// Make sure it's not just the RRULE: part
guard rrule.count > 6 else { throw RFC5545Exception.invalidRecurrenceRule }
var foundUntilOrCount = false
var frequency: EKRecurrenceFrequency?
var endDate: Date?
var count: Int?
var interval: Int?
var daysOfTheWeek: [EKRecurrenceDayOfWeek]?
var daysOfTheMonth: [Int]?
var weeksOfTheYear: [Int]?
var monthsOfTheYear: [Int]?
var daysOfTheYear: [Int]?
var positions: [Int]?
let index = rrule.index(rrule.startIndex, offsetBy: 6)
for part in String(rrule[index...]).components(separatedBy: ";") {
let pair = part.components(separatedBy: "=")
guard pair.count == 2 else { throw RFC5545Exception.invalidRecurrenceRule }
let key = pair[0].uppercased()
if key.hasPrefix("X-") {
// TODO: Save all of these somewhere
continue
}
let value = pair[1]
switch key {
case "FREQ":
guard frequency == nil else { throw RFC5545Exception.invalidRecurrenceRule }
switch value {
case "DAILY": frequency = .daily
case "MONTHLY": frequency = .monthly
case "WEEKLY": frequency = .weekly
case "YEARLY": frequency = .yearly
case "SECONDLY", "MINUTELY", "HOURLY": break
default: throw RFC5545Exception.invalidRecurrenceRule
}
case "UNTIL":
guard foundUntilOrCount == false else { throw RFC5545Exception.invalidRecurrenceRule }
do {
let dateInfo = try parseDateString(value)
endDate = dateInfo.date
} catch {
// The UNITL keyword is allowed to be just a date, without the normal VALUE=DATE specifier....sigh.
var year = 0
var month = 0
var day = 0
var args: [CVarArg] = []
withUnsafeMutablePointer(to: &year) {
y in
withUnsafeMutablePointer(to: &month) {
m in
withUnsafeMutablePointer(to: &day) {
d in
args.append(y)
args.append(m)
args.append(d)
}
}
}
if vsscanf(value, "%4d%2d%2d", getVaList(args)) == 3 {
let components = DateComponents(year: year, month: month, day: day)
// This is bad, because we don't know the timezone...
endDate = Calendar.current.date(from: components)!
}
}
if endDate == nil {
throw RFC5545Exception.invalidRecurrenceRule
}
foundUntilOrCount = true
case "COUNT":
guard foundUntilOrCount == false, let ival = Int(value) else { throw RFC5545Exception.invalidRecurrenceRule }
count = ival
foundUntilOrCount = true
case "INTERVAL":
guard interval == nil, let ival = Int(value) else { throw RFC5545Exception.invalidRecurrenceRule }
interval = ival
case "BYDAY":
guard daysOfTheWeek == nil else { throw RFC5545Exception.invalidRecurrenceRule }
daysOfTheWeek = []
let weekday: [String : EKWeekday] = [
"SU" : .sunday,
"MO" : .monday,
"TU" : .tuesday,
"WE" : .wednesday,
"TH" : .thursday,
"FR" : .friday,
"SA" : .saturday
]
for day in value.components(separatedBy: ",") {
let dayStr: String
var num = 0
if day.count > 2 {
let index = day.index(day.endIndex, offsetBy: -2)
dayStr = String(day[index...])
num = Int(day[..<index]) ?? 0
} else {
dayStr = day
}
if let day = weekday[dayStr] {
daysOfTheWeek!.append(EKRecurrenceDayOfWeek(day, weekNumber: num))
}
}
case "BYMONTHDAY":
guard daysOfTheMonth == nil else { throw RFC5545Exception.invalidRecurrenceRule }
daysOfTheMonth = try allValues(lessThan: 32, csv: value)
case "BYYEARDAY":
guard daysOfTheYear == nil else { throw RFC5545Exception.invalidRecurrenceRule }
daysOfTheYear = try allValues(lessThan: 367, csv: value)
case "BYWEEKNO":
guard weeksOfTheYear == nil else { throw RFC5545Exception.invalidRecurrenceRule }
weeksOfTheYear = try allValues(lessThan: 54, csv: value)
case "BYMONTH":
guard monthsOfTheYear == nil else { throw RFC5545Exception.invalidRecurrenceRule }
monthsOfTheYear = try allValues(lessThan: 13, csv: value)
case "BYSETPOS":
guard positions == nil else { throw RFC5545Exception.invalidRecurrenceRule }
positions = try allValues(lessThan: 367, csv: value)
default:
throw RFC5545Exception.unsupportedRecurrenceProperty(key)
}
}
guard let freq = frequency else { throw RFC5545Exception.invalidRecurrenceRule }
// The BYDAY rule part MUST NOT be specified with a numeric value when the FREQ rule part is
// not set to MONTHLY or YEARLY.
if let daysOfTheWeek = daysOfTheWeek , freq != .monthly && freq != .yearly {
for day in daysOfTheWeek {
if day.weekNumber != 0 {
throw RFC5545Exception.invalidRecurrenceRule
}
}
}
// The BYMONTHDAY rule part MUST NOT be specified when the FREQ rule part is set to WEEKLY.
if daysOfTheMonth != nil && freq == .weekly {
throw RFC5545Exception.invalidRecurrenceRule
}
// The BYYEARDAY rule part MUST NOT be specified when the FREQ rule part is set to DAILY, WEEKLY, or MONTHLY.
if daysOfTheYear != nil && (freq == .daily || freq == .weekly || freq == .monthly) {
throw RFC5545Exception.invalidRecurrenceRule
}
// BYWEEKNO MUST NOT be used when the FREQ rule part is set to anything other than YEARLY
if weeksOfTheYear != nil && freq != .yearly {
throw RFC5545Exception.invalidRecurrenceRule
}
let nonPositionAllNil = daysOfTheYear == nil && daysOfTheMonth == nil && daysOfTheWeek == nil && weeksOfTheYear == nil && monthsOfTheYear == nil
// If BYSETPOS is used, one of the other BY* rules must be used as well
if positions != nil && nonPositionAllNil {
throw RFC5545Exception.invalidRecurrenceRule
}
let end: EKRecurrenceEnd?
if let endDate = endDate {
end = EKRecurrenceEnd(end: endDate)
} else if let count = count {
end = EKRecurrenceEnd(occurrenceCount: count)
} else {
end = nil
}
if nonPositionAllNil && positions == nil {
self.init(recurrenceWith: freq, interval: interval ?? 1, end: end)
} else {
// TODO: This needs to handle multiple BY* rules as defined by the RFC spec. Maybe the EKRecurrenceRule
// constructor does it for us, but it needs to be tested.
self.init(recurrenceWith: freq, interval: interval ?? 1, daysOfTheWeek: daysOfTheWeek, daysOfTheMonth: daysOfTheMonth as [NSNumber]?, monthsOfTheYear: monthsOfTheYear as [NSNumber]?, weeksOfTheYear: weeksOfTheYear as [NSNumber]?, daysOfTheYear: daysOfTheYear as [NSNumber]?, setPositions: positions as [NSNumber]?, end: end)
}
}
}
| mit | 376aed242544e995c858a7f9fc72e1e2 | 34.884718 | 336 | 0.557266 | 4.68007 | false | false | false | false |
convergeeducacao/Charts | Source/Charts/Utils/ChartUtils.swift | 3 | 10314 | //
// Utils.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
open class ChartUtils
{
fileprivate static var _defaultValueFormatter: IValueFormatter = ChartUtils.generateDefaultValueFormatter()
internal struct Math
{
internal static let FDEG2RAD = CGFloat(M_PI / 180.0)
internal static let FRAD2DEG = CGFloat(180.0 / M_PI)
internal static let DEG2RAD = M_PI / 180.0
internal static let RAD2DEG = 180.0 / M_PI
}
internal class func roundToNextSignificant(number: Double) -> Double
{
if number.isInfinite || number.isNaN || number == 0
{
return number
}
let d = ceil(log10(number < 0.0 ? -number : number))
let pw = 1 - Int(d)
let magnitude = pow(Double(10.0), Double(pw))
let shifted = round(number * magnitude)
return shifted / magnitude
}
internal class func decimals(_ number: Double) -> Int
{
if number.isNaN || number.isInfinite || number == 0.0
{
return 0
}
let i = roundToNextSignificant(number: Double(number))
return Int(ceil(-log10(i))) + 2
}
internal class func nextUp(_ number: Double) -> Double
{
if number.isInfinite || number.isNaN
{
return number
}
else
{
return number + DBL_EPSILON
}
}
/// Calculates the position around a center point, depending on the distance from the center, and the angle of the position around the center.
internal class func getPosition(center: CGPoint, dist: CGFloat, angle: CGFloat) -> CGPoint
{
return CGPoint(
x: center.x + dist * cos(angle * Math.FDEG2RAD),
y: center.y + dist * sin(angle * Math.FDEG2RAD)
)
}
open class func drawText(context: CGContext, text: String, point: CGPoint, align: NSTextAlignment, attributes: [String : AnyObject]?)
{
var point = point
if align == .center
{
point.x -= text.size(attributes: attributes).width / 2.0
}
else if align == .right
{
point.x -= text.size(attributes: attributes).width
}
NSUIGraphicsPushContext(context)
(text as NSString).draw(at: point, withAttributes: attributes)
NSUIGraphicsPopContext()
}
open class func drawText(context: CGContext, text: String, point: CGPoint, attributes: [String : AnyObject]?, anchor: CGPoint, angleRadians: CGFloat)
{
var drawOffset = CGPoint()
NSUIGraphicsPushContext(context)
if angleRadians != 0.0
{
let size = text.size(attributes: attributes)
// Move the text drawing rect in a way that it always rotates around its center
drawOffset.x = -size.width * 0.5
drawOffset.y = -size.height * 0.5
var translate = point
// Move the "outer" rect relative to the anchor, assuming its centered
if anchor.x != 0.5 || anchor.y != 0.5
{
let rotatedSize = sizeOfRotatedRectangle(size, radians: angleRadians)
translate.x -= rotatedSize.width * (anchor.x - 0.5)
translate.y -= rotatedSize.height * (anchor.y - 0.5)
}
context.saveGState()
context.translateBy(x: translate.x, y: translate.y)
context.rotate(by: angleRadians)
(text as NSString).draw(at: drawOffset, withAttributes: attributes)
context.restoreGState()
}
else
{
if anchor.x != 0.0 || anchor.y != 0.0
{
let size = text.size(attributes: attributes)
drawOffset.x = -size.width * anchor.x
drawOffset.y = -size.height * anchor.y
}
drawOffset.x += point.x
drawOffset.y += point.y
(text as NSString).draw(at: drawOffset, withAttributes: attributes)
}
NSUIGraphicsPopContext()
}
internal class func drawMultilineText(context: CGContext, text: String, knownTextSize: CGSize, point: CGPoint, attributes: [String : AnyObject]?, constrainedToSize: CGSize, anchor: CGPoint, angleRadians: CGFloat)
{
var rect = CGRect(origin: CGPoint(), size: knownTextSize)
NSUIGraphicsPushContext(context)
if angleRadians != 0.0
{
// Move the text drawing rect in a way that it always rotates around its center
rect.origin.x = -knownTextSize.width * 0.5
rect.origin.y = -knownTextSize.height * 0.5
var translate = point
// Move the "outer" rect relative to the anchor, assuming its centered
if anchor.x != 0.5 || anchor.y != 0.5
{
let rotatedSize = sizeOfRotatedRectangle(knownTextSize, radians: angleRadians)
translate.x -= rotatedSize.width * (anchor.x - 0.5)
translate.y -= rotatedSize.height * (anchor.y - 0.5)
}
context.saveGState()
context.translateBy(x: translate.x, y: translate.y)
context.rotate(by: angleRadians)
(text as NSString).draw(with: rect, options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
context.restoreGState()
}
else
{
if anchor.x != 0.0 || anchor.y != 0.0
{
rect.origin.x = -knownTextSize.width * anchor.x
rect.origin.y = -knownTextSize.height * anchor.y
}
rect.origin.x += point.x
rect.origin.y += point.y
(text as NSString).draw(with: rect, options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
}
NSUIGraphicsPopContext()
}
internal class func drawMultilineText(context: CGContext, text: String, point: CGPoint, attributes: [String : AnyObject]?, constrainedToSize: CGSize, anchor: CGPoint, angleRadians: CGFloat)
{
let rect = text.boundingRect(with: constrainedToSize, options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
drawMultilineText(context: context, text: text, knownTextSize: rect.size, point: point, attributes: attributes, constrainedToSize: constrainedToSize, anchor: anchor, angleRadians: angleRadians)
}
/// - returns: An angle between 0.0 < 360.0 (not less than zero, less than 360)
internal class func normalizedAngleFromAngle(_ angle: CGFloat) -> CGFloat
{
var angle = angle
while (angle < 0.0)
{
angle += 360.0
}
return angle.truncatingRemainder(dividingBy: 360.0)
}
fileprivate class func generateDefaultValueFormatter() -> IValueFormatter
{
let formatter = DefaultValueFormatter(decimals: 1)
return formatter
}
/// - returns: The default value formatter used for all chart components that needs a default
open class func defaultValueFormatter() -> IValueFormatter
{
return _defaultValueFormatter
}
internal class func sizeOfRotatedRectangle(_ rectangleSize: CGSize, degrees: CGFloat) -> CGSize
{
let radians = degrees * Math.FDEG2RAD
return sizeOfRotatedRectangle(rectangleWidth: rectangleSize.width, rectangleHeight: rectangleSize.height, radians: radians)
}
internal class func sizeOfRotatedRectangle(_ rectangleSize: CGSize, radians: CGFloat) -> CGSize
{
return sizeOfRotatedRectangle(rectangleWidth: rectangleSize.width, rectangleHeight: rectangleSize.height, radians: radians)
}
internal class func sizeOfRotatedRectangle(rectangleWidth: CGFloat, rectangleHeight: CGFloat, degrees: CGFloat) -> CGSize
{
let radians = degrees * Math.FDEG2RAD
return sizeOfRotatedRectangle(rectangleWidth: rectangleWidth, rectangleHeight: rectangleHeight, radians: radians)
}
internal class func sizeOfRotatedRectangle(rectangleWidth: CGFloat, rectangleHeight: CGFloat, radians: CGFloat) -> CGSize
{
return CGSize(
width: abs(rectangleWidth * cos(radians)) + abs(rectangleHeight * sin(radians)),
height: abs(rectangleWidth * sin(radians)) + abs(rectangleHeight * cos(radians))
)
}
/// MARK: - Bridging functions
internal class func bridgedObjCGetNSUIColorArray (swift array: [NSUIColor?]) -> [NSObject]
{
var newArray = [NSObject]()
for val in array
{
if val == nil
{
newArray.append(NSNull())
}
else
{
newArray.append(val!)
}
}
return newArray
}
internal class func bridgedObjCGetNSUIColorArray (objc array: [NSObject]) -> [NSUIColor?]
{
var newArray = [NSUIColor?]()
for object in array
{
newArray.append(object as? NSUIColor)
}
return newArray
}
internal class func bridgedObjCGetStringArray (swift array: [String?]) -> [NSObject]
{
var newArray = [NSObject]()
for val in array
{
if val == nil
{
newArray.append(NSNull())
}
else
{
newArray.append(val! as NSObject)
}
}
return newArray
}
internal class func bridgedObjCGetStringArray (objc array: [NSObject]) -> [String?]
{
var newArray = [String?]()
for object in array
{
newArray.append(object as? String)
}
return newArray
}
}
| apache-2.0 | 8ca8db7b6b8bfa3ab717840b7e527dd2 | 32.487013 | 216 | 0.573201 | 5.043521 | false | false | false | false |
Ryan-Vanderhoef/Antlers | AppIdea/Frameworks/Bond/Bond/Bond+UITextField.swift | 1 | 4061 | //
// 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 ?? "", faulty: false)
self.helper.listener = { [unowned self] in self.value = $0 }
}
}
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] v in if let s = self { 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 | 927e9b8d69b617cb312c4570f3c54fcd | 30.726563 | 129 | 0.710662 | 4.17369 | false | false | false | false |
hulinSun/MyRx | MyRx/MyRx/Classes/Topic/View/TopicTitleCell.swift | 1 | 1493 | //
// TopicTitleCell.swift
// MyRx
//
// Created by Hony on 2016/12/30.
// Copyright © 2016年 Hony. All rights reserved.
//
import UIKit
import ReusableKit
class TopicTitleCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
@IBOutlet weak var iconView: UIImageView!
@IBOutlet weak var topicMemoLabel: UILabel!
@IBOutlet weak var topicTitleLale: UILabel!{
didSet{
topicTitleLale.preferredMaxLayoutWidth = UIScreen.main.bounds.width - 35
}
}
func config(_ model: TopicInfo) {
topicTitleLale.text = model.topic_name ?? "😝"
var typeStr = ""
guard let type = model.topic_type else {
topicMemoLabel.text = model.view! + "次浏览"
return
}
if type == "imagetext" {
iconView.isHidden = true
}else if type == "image"{
typeStr = " · 图片话题"
iconView.isHidden = false
iconView.image = UIImage(named: "createTopic_photo")
}else if type == "voice"{
typeStr = " · 语音话题"
iconView.isHidden = false
iconView.image = UIImage(named: "createTopic_voice")
}
topicMemoLabel.text = model.view! + "次浏览" + typeStr
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
| mit | 3ad0076e030ba45a7714c78658eeee66 | 25.981481 | 84 | 0.578586 | 4.223188 | false | false | false | false |
breadwallet/breadwallet-ios | breadwalletWidget/Views/ChartView/ChartViewModel.swift | 1 | 3445 | //
// ChartViewModel.swift
// ChartDemo
//
// Created by stringcode on 11/02/2021.
// Copyright © 2021 Breadwinner AG. All rights reserved.
//
// See the LICENSE file at the project root for license information.
//
import Foundation
import SwiftUI
struct ChartViewModel {
let candles: [Candle]
let greenCandle: Color
let redCandle: Color
let colorOverride: Color?
var chartColor: Color {
if let color = colorOverride {
return color
}
guard candles.count > 1 else {
return greenCandle
}
let rising = candles[candles.count - 1].close >= candles[candles.count - 2].close
return rising ? greenCandle : redCandle
}
}
// MARK: - Candle
extension ChartViewModel {
struct Candle {
let open: Float
let close: Float
let high: Float
let low: Float
}
}
// MARK: - Default mock
extension ChartViewModel {
static func mock(_ count: Int = 30, greenCandle: Color = .green, redCandle: Color = .red) -> ChartViewModel {
guard let url = Bundle.main.url(forResource: "mock-candles", withExtension: "json") else {
fatalError("mock-candles.json not found")
}
guard let data = try? Data(contentsOf: url) else {
fatalError("could not load data from mock-candles.json")
}
guard let candles = try? JSONDecoder().decode([ChartViewModel.Candle].self, from: data) else {
fatalError("could not decode data from mock-candles.json")
}
return .init(candles: normalized(candles),
greenCandle: greenCandle,
redCandle: redCandle,
colorOverride: nil)
}
static func normalized(_ candles: [ChartViewModel.Candle]) -> [Candle] {
let high = candles.sorted { $0.high > $1.high }.first?.high ?? 1
let low = candles.sorted { $0.low < $1.low }.first?.low ?? 0
let delta = high - low
return candles.map {
return .init(
open: ($0.open - low) / delta,
close: ($0.close - low) / delta,
high: ($0.high - low) / delta,
low: ($0.low - low) / delta
)
}
}
}
// MARK: - ChartViewModel.Candle Decodable
extension ChartViewModel.Candle: Decodable {
enum CodingKeys: String, CodingKey {
case open
case high
case low
case close
}
init(from decoder: Decoder) throws {
let cont = try decoder.container(keyedBy: CodingKeys.self)
open = try (try cont.decode(String.self, forKey: .open)).float()
high = try (try cont.decode(String.self, forKey: .high)).float()
low = try (try cont.decode(String.self, forKey: .low)).float()
close = try (try cont.decode(String.self, forKey: .close)).float()
}
}
// MARK: - MarketInfo.Candle
extension ChartViewModel.Candle {
static func candles(_ candles: [MarketInfo.Candle]) -> [ChartViewModel.Candle] {
var bounded = candles
if candles.count > 90 {
bounded = Array(candles[candles.count-90..<candles.count])
}
let chartCandles: [ChartViewModel.Candle] = bounded.map {
.init(open: $0.open, close: $0.close, high: $0.high, low: $0.low)
}
return ChartViewModel.normalized(chartCandles)
}
}
| mit | ceb50046a4ab52c5c34f4f6c345bb5c0 | 28.435897 | 113 | 0.578688 | 4.004651 | false | false | false | false |
Jamnitzer/MBJ_CubeMapping | MBJ_CubeMapping/MBJ_CubeMapping/MBJViewController.swift | 1 | 5802 | //
// MBEViewController.m
// MetalCubeMapping
//
// Created by Warren Moore on 11/7/14.
// Copyright (c) 2014 Metal By Example. All rights reserved.
//------------------------------------------------------------------------
// converted to Swift by Jamnitzer (Jim Wrenholt)
//------------------------------------------------------------------------
import Foundation
import UIKit
import CoreMotion
import Metal
import simd
//------------------------------------------------------------------------------
class MBJViewController: UIViewController
{
var renderer:MBJRenderer! = nil
var displayLink:CADisplayLink! = nil
var motionManager:CMMotionManager! = nil
//------------------------------------------------------------------------
func metalView() -> MBJMetalView?
{
return self.view as? MBJMetalView
}
//------------------------------------------------------------------------
override func viewDidLoad()
{
super.viewDidLoad()
if let myView = self.view as? MBJMetalView
{
let metal_layer:CAMetalLayer = myView.metalLayer
self.renderer = MBJRenderer(layer:metal_layer)
}
}
//------------------------------------------------------------------------
override func viewDidAppear(animated: Bool)
{
super.viewDidAppear(animated)
self.displayLink = CADisplayLink(target: self, selector: Selector("displayLinkDidFire:"))
displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes)
self.motionManager = CMMotionManager()
if (self.motionManager.deviceMotionAvailable)
{
self.motionManager.deviceMotionUpdateInterval = 1.0 / 60.0
// let frame:CMAttitudeReferenceFrame = CMAttitudeReferenceFrame.XTrueNorthZVertical
// self.motionManager.startDeviceMotionUpdatesUsingReferenceFrame(frame)
self.motionManager.startDeviceMotionUpdates()
}
let tapRecognizer = UITapGestureRecognizer(target: self, action: "tap:")
self.view.addGestureRecognizer(tapRecognizer)
}
//------------------------------------------------------------------------
override func prefersStatusBarHidden() -> Bool
{
return true
}
//------------------------------------------------------------------------
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask
{
return .Portrait
}
//------------------------------------------------------------------------
func tap(recognize: UITapGestureRecognizer)
{
self.renderer.useRefractionMaterial = !self.renderer.useRefractionMaterial
}
//------------------------------------------------------------------------
func updateDeviceOrientation()
{
if (self.motionManager.deviceMotionAvailable)
{
// print("_ ", terminator:"")
// self.renderer.sceneOrientation = translation(float4(0.0, -5.0, 0.0, 0.0))
// self.renderer.sceneOrientation = identity()
// if (self.motionManager.deviceMotionActive)
// {
// print("deviceMotionActive")
// }
// self.motionManager.startDeviceMotionUpdates()
if let motion:CMDeviceMotion = self.motionManager.deviceMotion
{
// let aat:CMAttitude = motion.attitude
// // let aam:CMRotationMatrix = aat.rotationMatrix
// print("m.roll = \(aat.roll)")
// print("m.pitch = \(aat.pitch)")
// print("m.yaw = \(aat.yaw)")
//assert(false)
let m:CMRotationMatrix = motion.attitude.rotationMatrix
//------------------------------------------------------------------------
// permute rotation matrix from Core Motion to get scene orientation
//------------------------------------------------------------------------
let X = float4( Float(m.m12), Float(m.m22), Float(m.m32), 0.0 )
let Y = float4( Float(m.m13), Float(m.m23), Float(m.m33), 0.0 )
let Z = float4( Float(m.m11), Float(m.m21), Float(m.m31), 0.0 )
let W = float4( 0.0, 0.0, 0.0, 1.0 )
let orientation = float4x4([ X, Y, Z, W ])
self.renderer.sceneOrientation = orientation
//-----------------------------------------------
// if (m.m12 != 0.0) { print("m.m12 = \(m.m12)") }
// if (m.m22 != 0.0) { print("m.m22 = \(m.m22)") }
// if (m.m32 != 0.0) { print("m.m32 = \(m.m32)") }
// //-----------------------------------------------
// if (m.m13 != 0.0) { print("m.m13 = \(m.m13)") }
// if (m.m23 != 0.0) { print("m.m23 = \(m.m23)") }
// if (m.m33 != 0.0) { print("m.m33 = \(m.m33)") }
// //-----------------------------------------------
// if (m.m11 != 0.0) { print("m.m11 = \(m.m11)") }
// if (m.m21 != 0.0) { print("m.m21 = \(m.m21)") }
// if (m.m31 != 0.0) { print("m.m31 = \(m.m31)") }
//-----------------------------------------------
}
}
}
//------------------------------------------------------------------------
func displayLinkDidFire(sender:CADisplayLink)
{
updateDeviceOrientation()
redraw()
}
//------------------------------------------------------------------------
func redraw()
{
self.renderer.draw()
}
//------------------------------------------------------------------------
}
| mit | 674eaa9aba0e939b27c3742855cb2427 | 41.350365 | 97 | 0.417615 | 5.102902 | false | false | false | false |
ingresse/ios-sdk | IngresseSDKTests/URLBuilderTests.swift | 1 | 3040 | //
// Copyright © 2017 Gondek. All rights reserved.
//
import XCTest
import IngresseSDK
class URLBuilderTests: XCTestCase {
var builder: URLBuilder!
override func setUp() {
super.setUp()
let client = IngresseClient(apiKey: "1234", userAgent: "", env: .prod)
builder = URLBuilder(client: client)
}
public func testMakeURL() {
// When
let request = try? builder
.setPath("test/")
.setKeys(apiKey: "4321")
.addParameter(key: "param1", value: "value1")
.addParameter(key: "param2", value: "value2")
.build()
let generated = request?.url?.absoluteString ?? ""
// Then
XCTAssert(generated.contains("apikey=4321"))
XCTAssert(generated.contains("param1=value1"))
XCTAssert(generated.contains("param2=value2"))
}
public func testMakeURLNoParameters() {
// Given
let authString = "apikey=1234"
let expected = "https://api.ingresse.com/test/?\(authString)"
// When
let request = try? builder
.setPath("test/")
.setKeys(apiKey: "1234")
.build()
let generated = request?.url?.absoluteString ?? ""
// Then
XCTAssertEqual(expected, generated)
}
func testGestHostUrlHmlSearch() {
// Given
let expected = "https://hml-event.ingresse.com/search/company/"
// When
let request = try? builder
.setHost(.search)
.setEnvironment(.hml)
.build()
let generated = request?.url?.absoluteString ?? ""
// Then
XCTAssertEqual(generated, expected)
}
func testGestHostUrl() {
// Given
let selectedEnv = Environment.prod
let selectedHost = Host.api
let expected = "https://\(selectedEnv.rawValue)\(selectedHost.rawValue)?apikey=1234"
// When
let request = try? builder
.setHost(selectedHost)
.setEnvironment(selectedEnv)
.build()
let generated = request?.url?.absoluteString ?? ""
// Then
XCTAssertEqual(generated, expected)
}
func testEnvironmentInitWithProd() {
// When
let env = Environment(envType: "prod")
// Then
XCTAssertEqual(env, .prod)
}
func testEnvironmentInitWithHml() {
// When
let env = Environment(envType: "hml")
// Then
XCTAssertEqual(env, .hml)
}
func testEnvironmentInitWithTest() {
// When
let env = Environment(envType: "test")
// Then
XCTAssertEqual(env, .test)
}
func testEnvironmentInitWithStg() {
// When
let env = Environment(envType: "stg")
// Then
XCTAssertEqual(env, .stg)
}
func testEnvironmentInitWithUndefined() {
// When
let env = Environment(envType: "abcd")
// Then
XCTAssertEqual(env, .undefined)
}
}
| mit | 73248bbc2d9fe743480759febacad72b | 23.909836 | 92 | 0.554788 | 4.549401 | false | true | false | false |
PJayRushton/stats | Stats/UIView+Helpers.swift | 1 | 2982 | /*
| _ ____ ____ _
| | |‾| ⚈ |-| ⚈ |‾| |
| | | ‾‾‾‾| |‾‾‾‾ | |
| ‾ ‾ ‾
*/
import UIKit
public extension UIView {
@IBInspectable public var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
}
}
@IBInspectable public var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
@IBInspectable public var borderColor: UIColor? {
get {
guard let CGColor = layer.borderColor else { return nil }
return UIColor(cgColor: CGColor)
}
set {
layer.borderColor = newValue?.cgColor
}
}
@IBInspectable public var shadowColor: UIColor? {
get {
guard let CGColor = layer.shadowColor else { return nil }
return UIColor(cgColor: CGColor)
}
set {
layer.shadowColor = newValue?.cgColor
}
}
// MARK: - Constraining full size
public struct Margins: OptionSet {
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
public static let leading = Margins(rawValue: 1)
public static let top = Margins(rawValue: 2)
public static let trailing = Margins(rawValue: 4)
public static let bottom = Margins(rawValue: 8)
public static let all: Margins = [.leading, .top, .trailing, .bottom]
}
public func constrainFullSize(leading: CGFloat = 0, top: CGFloat = 0, trailing: CGFloat = 0, bottom: CGFloat = 0) {
guard let _ = self.superview else { fatalError("\(self) has no superview") }
constrainFullSize(insets: UIEdgeInsets(top: top, left: leading, bottom: bottom, right: trailing), margins: [])
}
public func constrainFullSize(insets: UIEdgeInsets = .zero, margins: Margins) {
guard let superview = self.superview else { fatalError("\(self) has no superview") }
self.translatesAutoresizingMaskIntoConstraints = false
self.leadingAnchor.constraint(equalTo: margins.contains(.leading) ? superview.layoutMarginsGuide.leadingAnchor : superview.leadingAnchor, constant: insets.left).isActive = true
self.topAnchor.constraint(equalTo: margins.contains(.top) ? superview.layoutMarginsGuide.topAnchor : superview.topAnchor, constant: insets.top).isActive = true
self.trailingAnchor.constraint(equalTo: margins.contains(.trailing) ? superview.layoutMarginsGuide.trailingAnchor : superview.trailingAnchor, constant: -insets.right).isActive = true
self.bottomAnchor.constraint(equalTo: margins.contains(.bottom) ? superview.layoutMarginsGuide.bottomAnchor : superview.bottomAnchor, constant: -insets.bottom).isActive = true
}
}
| mit | 3e3a1a1da9eb53c137d4667dc7ed65b5 | 34.566265 | 190 | 0.609079 | 4.863262 | false | false | false | false |
dobleuber/my-swift-exercises | Challenge3/Challenge3/ViewController.swift | 1 | 2210 | //
// ViewController.swift
// Challenge3
//
// Created by Wbert Castro on 16/06/17.
// Copyright © 2017 Wbert Castro. All rights reserved.
//
import UIKit
import Social
class ViewController: UITableViewController {
var shoppingList = [String]()
override func viewDidLoad() {
super.viewDidLoad()
let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addItem))
let shareButton = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(shareList))
navigationItem.rightBarButtonItems = [addButton, shareButton]
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return shoppingList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Item", for: indexPath)
cell.textLabel?.text = shoppingList[indexPath.row]
return cell
}
func addItem() {
let ac = UIAlertController(title: "New Item", message: nil, preferredStyle: .alert)
ac.addTextField()
let submitAction = UIAlertAction(title: "Add", style: .default) { [unowned self, ac] (action: UIAlertAction) in
let newItem = ac.textFields![0]
self.submit(newItem: newItem.text!)
}
ac.addAction(submitAction)
present(ac, animated: true)
}
func shareList() {
let shoppingListString = shoppingList.joined(separator: "\n")
if let vc = SLComposeViewController(forServiceType: SLServiceTypeFacebook) {
vc.setInitialText("My shopping list: \n\(shoppingListString)")
present(vc, animated: true)
}
}
func submit(newItem: String) {
shoppingList.insert(newItem, at: 0)
let indexPath = IndexPath(row: 0, section: 0)
tableView.insertRows(at: [indexPath], with: .automatic)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 66652701d7e9480423189556ec4343d3 | 32.469697 | 119 | 0.648257 | 4.87638 | false | false | false | false |
glennposadas/gpkit-ios | GPKit/Categories/UIViewContorller+GPKit.swift | 1 | 12099 | //
// UIViewContorller+GPKit.swift
// GPKit
//
// Created by Glenn Posadas on 5/10/17.
// Copyright © 2017 Citus Labs. All rights reserved.
//
import UIKit
public extension UIViewController {
// MARK: - Properties
public typealias GPKitAlertControllerCallBack = (_ sourceType: UIImagePickerControllerSourceType) -> Void
public typealias GPKitAlertCallBack = (_ userDidTapOk: Bool) -> Void
// MARK: - Shorter public functions
/** Shorter syntax for popping view controllers
*/
public func popVC() {
_ = self.navigationController?.popViewController(animated: true)
}
public func dismiss() {
self.dismiss(animated: true, completion: nil)
}
// MARK: - Status Bar
/** Status Bar Configuration
*/
public func showStatusBar() {
UIApplication.shared.isStatusBarHidden = false
}
public func hideStatusBar() {
UIApplication.shared.isStatusBarHidden = true
}
public func makeStatusBarLight() {
UIApplication.shared.statusBarStyle = .lightContent
}
public func makeStatusBarDark() {
UIApplication.shared.statusBarStyle = .default
}
/** Navigation Bar Configuration
*/
public func hideBackButton() {
self.navigationController?.navigationItem.setHidesBackButton(true, animated: false)
}
public func hideBackButtonForTabBarController() {
self.tabBarController?.navigationItem.setHidesBackButton(true, animated: false)
}
public func setupNavBarTitleCustomFont(font: UIFont, textColor: UIColor? = nil) {
var attributes: [NSAttributedStringKey : Any] = [NSAttributedStringKey.font : font]
if let textColor = textColor {
attributes[NSAttributedStringKey.foregroundColor] = textColor
}
self.navigationController?.navigationBar.titleTextAttributes = attributes
}
public func setupBackButtonTitleCustomFont(font: UIFont, textColor: UIColor? = nil) {
var attributes: [NSAttributedStringKey : Any] = [NSAttributedStringKey.font : font]
if let textColor = textColor {
attributes[NSAttributedStringKey.foregroundColor] = textColor
}
self.navigationController?.navigationBar.backItem?.backBarButtonItem?.setTitleTextAttributes(attributes, for: .normal)
}
public func makeNavBarTransparent() {
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = true
self.navigationController?.view.backgroundColor = .clear
self.navigationController?.navigationBar.backgroundColor = .clear
self.navigationController?.navigationBar.tintColor = .black
self.makeStatusBarDark()
}
public func makeNavBarTransparentWithoutBGImage() {
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = true
self.navigationController?.view.backgroundColor = .clear
self.navigationController?.navigationBar.backgroundColor = .clear
self.navigationController?.navigationBar.tintColor = .black
self.hideNavBar()
}
@available(*, deprecated, message: "Use makeNavBarColor(color: UIColor, itemsTintColor: UIColor)")
public func makeNavBarWhite() {
self.navigationController?.navigationBar.isTranslucent = false
let whiteImage = UIImage(color: .white)
self.navigationController?.navigationBar.setBackgroundImage(whiteImage, for: .default)
self.navigationController?.navigationBar.barTintColor = .white
self.navigationController?.navigationBar.backgroundColor = .white
self.navigationController?.view.backgroundColor = .white
self.navigationController?.navigationBar.tintColor = .black
self.makeStatusBarDark()
}
@available(*, deprecated, message: "Use makeNavBarColor(color: UIColor, itemsTintColor: UIColor)")
public func makeNavBarBlack() {
self.navigationController?.navigationBar.isTranslucent = false
let blackImage = UIImage(color: .black)
self.navigationController?.navigationBar.setBackgroundImage(blackImage, for: .default)
self.navigationController?.navigationBar.barTintColor = .black
self.navigationController?.navigationBar.backgroundColor = .black
self.navigationController?.view.backgroundColor = .black
self.navigationController?.navigationBar.tintColor = .white
self.makeStatusBarLight()
}
public func makeNavBarColor(color: UIColor, itemsTintColor: UIColor) {
self.navigationController?.navigationBar.isTranslucent = false
let colorImage = UIImage(color: color)
self.navigationController?.navigationBar.setBackgroundImage(colorImage, for: .default)
self.navigationController?.navigationBar.barTintColor = color
self.navigationController?.navigationBar.backgroundColor = color
self.navigationController?.view.backgroundColor = color
self.navigationController?.navigationBar.tintColor = itemsTintColor
}
public func makeNavBarDefaultColor(color: UIColor, animated: Bool) {
self.navigationController?.navigationBar.tintColor = .white
self.navigationController?.view.backgroundColor = color
self.navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
if animated {
UIView.transition(with: self.navigationController!.navigationBar,
duration: 1.0,
options: [.beginFromCurrentState, .transitionCrossDissolve],
animations: {
self.navigationController?.navigationBar.isTranslucent = false
self.navigationController?.navigationBar.backgroundColor = color
}, completion: nil)
} else {
self.navigationController?.navigationBar.isTranslucent = false
self.navigationController?.navigationBar.backgroundColor = color
}
}
public func makeNavBarItemsTintColor(color: UIColor) {
self.navigationController?.navigationBar.tintColor = color
}
public func showNavBar() {
self.navigationController?.setNavigationBarHidden(false, animated: false)
}
public func showNavBarAnimated() {
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
public func hideNavBar() {
self.navigationController?.setNavigationBarHidden(true, animated: true)
}
// MARK: - BackButton
/** Configures the back button
*/
public func setBackButtonVisible(animated: Bool) {
self.navigationItem.setHidesBackButton(false, animated: animated)
}
public func setBackButtonHidden(animated: Bool) {
self.navigationItem.setHidesBackButton(true, animated: animated)
}
// MARK: - NavBar Logos
/** Configures te logos of the nav bar
*/
public func removeLogoTitleView() {
self.navigationItem.titleView = nil
}
/** Sets the navbar title with image and feedback from the button.
* Will call delegate if the navbar title is tapped.
*/
public func setNavBarTitleWithFeedback(image: UIImage, navBarTintColor: UIColor) {
self.navigationController?.navigationBar.tintColor = navBarTintColor
let gpKitBundle = Bundle(for: GPTitleView.self)
if let gpTitleView = UINib(nibName: "GPTitleView", bundle: gpKitBundle).instantiate(withOwner: nil, options: nil)[0]
as? GPTitleView {
gpTitleView.delegate = self as? GPTitleViewDelegate
gpTitleView.image_Title.image = image
self.navigationItem.titleView = gpTitleView
}
}
public func setNavBarTitle(image: UIImage, navBarTintColor: UIColor) {
self.navigationController?.navigationBar.tintColor = navBarTintColor
let gpKitBundle = Bundle(identifier: "ph.cituslabs.app.gpkit")
if let gpTitleView = UINib(nibName: "GPTitleView", bundle: gpKitBundle).instantiate(withOwner: nil, options: nil)[0]
as? GPTitleView {
gpTitleView.delegate = self as? GPTitleViewDelegate
gpTitleView.image_Title.image = image
self.navigationItem.titleView = gpTitleView
}
}
/** Sets the title with attributed string
*/
public func setNavBarTitleWithAttributedString(title: String, color: UIColor, font: UIFont) {
let titleLabel = UILabel()
let attributes = [NSAttributedStringKey.foregroundColor: color,
NSAttributedStringKey.font : font as Any]
titleLabel.attributedText = NSAttributedString(string: title, attributes: attributes)
titleLabel.sizeToFit()
self.navigationItem.titleView = titleLabel
}
// MARK: - Alerts
/**
Generates and shows an alertController with a native design
*/
public func showAlert(
title: String,
message: String? = nil,
okayButtonTitle: String,
cancelButtonTitle: String? = nil,
withBlock completion: @escaping GPKitAlertCallBack) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: okayButtonTitle, style: .default) { _ in
completion(true)
}
alertController.addAction(okAction)
if let cancelButtonTitle = cancelButtonTitle {
let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .default) { _ in
completion(false)
}
alertController.addAction(cancelAction)
}
alertController.view.tintColor = .black
present(alertController, animated: true, completion: nil)
}
// MARK: - AlertController for Image Picker and Camera Source
public func showAlertControllerForPhoto(sourceView: UIView, tintColor: UIColor, withBlock completion: @escaping GPKitAlertControllerCallBack) {
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
// provide the view source
alertController.popoverPresentationController?.sourceView = sourceView
alertController.popoverPresentationController?.sourceRect = sourceView.bounds
alertController.view.tintColor = tintColor
if UIImagePickerController.isSourceTypeAvailable(.camera) {
let cameraAction = UIAlertAction(title: "Camera", style: .default, handler: {
_ in
alertController.view.tintColor = tintColor
completion(.camera)
})
alertController.addAction(cameraAction)
}
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
let photoLibraryAction = UIAlertAction(title: "Photo Library", style: .default, handler: {
_ in
alertController.view.tintColor = tintColor
completion(.photoLibrary)
})
alertController.addAction(photoLibraryAction)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
}
}
| mit | 8cfb02e9664f2d2e5f0baadad9a41705 | 37.164038 | 147 | 0.656885 | 5.766444 | false | false | false | false |
ivlevAstef/DITranquillity | Samples/SampleChaos/SampleChaos/ViewController.swift | 1 | 2282 | //
// ViewController.swift
// SampleChaos
//
// Created by Alexander Ivlev on 09/06/16.
// Copyright © 2016 Alexander Ivlev. All rights reserved.
//
import UIKit
import DITranquillity
class ViewController: UIViewController {
internal var container: DIContainer!
internal var injectGlobal: Inject?
override func viewDidLoad() {
super.viewDidLoad()
let vc1_1: UIView = container.resolve()
print("Create VC1_1: \(vc1_1)")
let vc1_2: UIView = *container
print("Create VC1_2: \(vc1_2)")
let vc2_2: UIAppearance = container.resolve()
print("Create VC2_2: \(vc2_2)")
let inject1: Inject = *container
print("Create Inject1: \(inject1.description)")
let injectMany: InjectMany = *container
print("Create injectMany: \(injectMany)")
print("Create injectGlobal: \(String(describing: injectGlobal))")
// Optional
let fooOpt: FooService? = *container
let barOpt: BarService? = *container
print("Optional Foo:\(String(describing: fooOpt)) Optional Bar: \(String(describing: barOpt))" )
// Optional Tag
let fooTagOpt: FooService? = by(tag: CatTag.self, on: *container)
let barTagOpt: BarService? = by(tag: DogTag.self, on: *container)
print("Optional tag Foo:\(String(describing: fooTagOpt)) Optional tag Bar: \(String(describing: barTagOpt))" )
// Many
let fooMany: [FooService] = many(*container)
let barMany: [BarService] = many(*container)
print("Many Foo:\(fooMany) Many Bar: \(barMany)" )
// Animals
let cat: Animal = by(tag: CatTag.self, on: *container)
let dog: Animal = by(tag: DogTag.self, on: *container)
let bear: Animal = container.resolve(tag: BearTag.self)
let animals: [Animal] = many(*container)
print(animals.map{ $0.name })
let defaultAnimal: Animal = *container
print("Cat: \(cat.name) Dog: \(dog.name) Bear: \(bear.name) Default(Dog): \(defaultAnimal.name)")
//Circular
let circularT1: Circular1 = *container
let circularT2: Circular2 = *container
print("Circular test 1: \(circularT1.description) + \(circularT1.ref.description)")
print("Circular test 2: \(circularT2.description) + \(circularT2.ref.description)")
}
}
| mit | d3d2db62f85ec1a62bf4b91b07bbd2e8 | 29.413333 | 114 | 0.649715 | 3.714984 | false | false | false | false |
JackEsad/Eureka | Source/Core/Section.swift | 4 | 16499 | // Section.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/// The delegate of the Eureka sections.
public protocol SectionDelegate: class {
func rowsHaveBeenAdded(_ rows: [BaseRow], at: IndexSet)
func rowsHaveBeenRemoved(_ rows: [BaseRow], at: IndexSet)
func rowsHaveBeenReplaced(oldRows: [BaseRow], newRows: [BaseRow], at: IndexSet)
}
// MARK: Section
extension Section : Equatable {}
public func == (lhs: Section, rhs: Section) -> Bool {
return lhs === rhs
}
extension Section : Hidable, SectionDelegate {}
extension Section {
public func reload(with rowAnimation: UITableViewRowAnimation = .none) {
guard let tableView = (form?.delegate as? FormViewController)?.tableView, let index = index else { return }
tableView.reloadSections(IndexSet(integer: index), with: rowAnimation)
}
}
extension Section {
internal class KVOWrapper: NSObject {
dynamic private var _rows = NSMutableArray()
var rows: NSMutableArray {
return mutableArrayValue(forKey: "_rows")
}
var _allRows = [BaseRow]()
private weak var section: Section?
init(section: Section) {
self.section = section
super.init()
addObserver(self, forKeyPath: "_rows", options: NSKeyValueObservingOptions.new.union(.old), context:nil)
}
deinit {
removeObserver(self, forKeyPath: "_rows")
_rows.removeAllObjects()
_allRows.removeAll()
}
public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
let newRows = change![NSKeyValueChangeKey.newKey] as? [BaseRow] ?? []
let oldRows = change![NSKeyValueChangeKey.oldKey] as? [BaseRow] ?? []
guard let keyPathValue = keyPath, let changeType = change?[NSKeyValueChangeKey.kindKey] else { return }
let delegateValue = section?.form?.delegate
guard keyPathValue == "_rows" else { return }
switch (changeType as! NSNumber).uintValue {
case NSKeyValueChange.setting.rawValue:
section?.rowsHaveBeenAdded(newRows, at: IndexSet(integer: 0))
delegateValue?.rowsHaveBeenAdded(newRows, at:[IndexPath(index: 0)])
case NSKeyValueChange.insertion.rawValue:
let indexSet = change![NSKeyValueChangeKey.indexesKey] as! IndexSet
section?.rowsHaveBeenAdded(newRows, at: indexSet)
if let _index = section?.index {
delegateValue?.rowsHaveBeenAdded(newRows, at: indexSet.map { IndexPath(row: $0, section: _index ) })
}
case NSKeyValueChange.removal.rawValue:
let indexSet = change![NSKeyValueChangeKey.indexesKey] as! IndexSet
section?.rowsHaveBeenRemoved(oldRows, at: indexSet)
if let _index = section?.index {
delegateValue?.rowsHaveBeenRemoved(oldRows, at: indexSet.map { IndexPath(row: $0, section: _index ) })
}
case NSKeyValueChange.replacement.rawValue:
let indexSet = change![NSKeyValueChangeKey.indexesKey] as! IndexSet
section?.rowsHaveBeenReplaced(oldRows: oldRows, newRows: newRows, at: indexSet)
if let _index = section?.index {
delegateValue?.rowsHaveBeenReplaced(oldRows: oldRows, newRows: newRows, at: indexSet.map { IndexPath(row: $0, section: _index)})
}
default:
assertionFailure()
}
}
}
/**
* If this section contains a row (hidden or not) with the passed parameter as tag then that row will be returned.
* If not, it returns nil.
*/
public func rowBy<Row: RowType>(tag: String) -> Row? {
guard let index = kvoWrapper._allRows.index(where: { $0.tag == tag }) else { return nil }
return kvoWrapper._allRows[index] as? Row
}
}
/// The class representing the sections in a Eureka form.
open class Section {
/// The tag is used to uniquely identify a Section. Must be unique among sections and rows.
public var tag: String?
/// The form that contains this section
public internal(set) weak var form: Form?
/// The header of this section.
public var header: HeaderFooterViewRepresentable? {
willSet {
headerView = nil
}
}
/// The footer of this section
public var footer: HeaderFooterViewRepresentable? {
willSet {
footerView = nil
}
}
/// Index of this section in the form it belongs to.
public var index: Int? { return form?.index(of: self) }
/// Condition that determines if the section should be hidden or not.
public var hidden: Condition? {
willSet { removeFromRowObservers() }
didSet { addToRowObservers() }
}
/// Returns if the section is currently hidden or not
public var isHidden: Bool { return hiddenCache }
public required init() {}
public init(_ initializer: (Section) -> Void) {
initializer(self)
}
public init(_ header: String, _ initializer: (Section) -> Void = { _ in }) {
self.header = HeaderFooterView(stringLiteral: header)
initializer(self)
}
public init(header: String, footer: String, _ initializer: (Section) -> Void = { _ in }) {
self.header = HeaderFooterView(stringLiteral: header)
self.footer = HeaderFooterView(stringLiteral: footer)
initializer(self)
}
public init(footer: String, _ initializer: (Section) -> Void = { _ in }) {
self.footer = HeaderFooterView(stringLiteral: footer)
initializer(self)
}
// MARK: SectionDelegate
/**
* Delegate method called by the framework when one or more rows have been added to the section.
*/
open func rowsHaveBeenAdded(_ rows: [BaseRow], at: IndexSet) {}
/**
* Delegate method called by the framework when one or more rows have been removed from the section.
*/
open func rowsHaveBeenRemoved(_ rows: [BaseRow], at: IndexSet) {}
/**
* Delegate method called by the framework when one or more rows have been replaced in the section.
*/
open func rowsHaveBeenReplaced(oldRows: [BaseRow], newRows: [BaseRow], at: IndexSet) {}
// MARK: Private
lazy var kvoWrapper: KVOWrapper = { [unowned self] in return KVOWrapper(section: self) }()
var headerView: UIView?
var footerView: UIView?
var hiddenCache = false
}
extension Section : MutableCollection, BidirectionalCollection {
// MARK: MutableCollectionType
public var startIndex: Int { return 0 }
public var endIndex: Int { return kvoWrapper.rows.count }
public subscript (position: Int) -> BaseRow {
get {
if position >= kvoWrapper.rows.count {
assertionFailure("Section: Index out of bounds")
}
return kvoWrapper.rows[position] as! BaseRow
}
set { kvoWrapper.rows[position] = newValue }
}
public subscript (range: Range<Int>) -> [BaseRow] {
get { return kvoWrapper.rows.objects(at: IndexSet(integersIn: range)) as! [BaseRow] }
set { kvoWrapper.rows.replaceObjects(in: NSRange(range), withObjectsFrom: newValue) }
}
public func index(after i: Int) -> Int {return i + 1}
public func index(before i: Int) -> Int {return i - 1}
}
extension Section : RangeReplaceableCollection {
// MARK: RangeReplaceableCollectionType
public func append(_ formRow: BaseRow) {
kvoWrapper.rows.insert(formRow, at: kvoWrapper.rows.count)
kvoWrapper._allRows.append(formRow)
formRow.wasAddedTo(section: self)
}
public func append<S: Sequence>(contentsOf newElements: S) where S.Iterator.Element == BaseRow {
kvoWrapper.rows.addObjects(from: newElements.map { $0 })
kvoWrapper._allRows.append(contentsOf: newElements)
for row in newElements {
row.wasAddedTo(section: self)
}
}
public func replaceSubrange<C: Collection>(_ subRange: Range<Int>, with newElements: C) where C.Iterator.Element == BaseRow {
for i in subRange.lowerBound..<subRange.upperBound {
if let row = kvoWrapper.rows.object(at: i) as? BaseRow {
row.willBeRemovedFromForm()
kvoWrapper._allRows.remove(at: kvoWrapper._allRows.index(of: row)!)
}
}
kvoWrapper.rows.replaceObjects(in: NSRange(location: subRange.lowerBound, length: subRange.upperBound - subRange.lowerBound),
withObjectsFrom: newElements.map { $0 })
kvoWrapper._allRows.insert(contentsOf: newElements, at: indexForInsertion(at: subRange.lowerBound))
for row in newElements {
row.wasAddedTo(section: self)
}
}
public func removeAll(keepingCapacity keepCapacity: Bool = false) {
// not doing anything with capacity
for row in kvoWrapper._allRows {
row.willBeRemovedFromForm()
}
kvoWrapper.rows.removeAllObjects()
kvoWrapper._allRows.removeAll()
}
private func indexForInsertion(at index: Int) -> Int {
guard index != 0 else { return 0 }
let row = kvoWrapper.rows[index-1]
if let i = kvoWrapper._allRows.index(of: row as! BaseRow) {
return i + 1
}
return kvoWrapper._allRows.count
}
}
extension Section /* Condition */{
// MARK: Hidden/Disable Engine
/**
Function that evaluates if the section should be hidden and updates it accordingly.
*/
public final func evaluateHidden() {
if let h = hidden, let f = form {
switch h {
case .function(_, let callback):
hiddenCache = callback(f)
case .predicate(let predicate):
hiddenCache = predicate.evaluate(with: self, substitutionVariables: f.dictionaryValuesToEvaluatePredicate())
}
if hiddenCache {
form?.hideSection(self)
} else {
form?.showSection(self)
}
}
}
/**
Internal function called when this section was added to a form.
*/
func wasAddedTo(form: Form) {
self.form = form
addToRowObservers()
evaluateHidden()
for row in kvoWrapper._allRows {
row.wasAddedTo(section: self)
}
}
/**
Internal function called to add this section to the observers of certain rows. Called when the hidden variable is set and depends on other rows.
*/
func addToRowObservers() {
guard let h = hidden else { return }
switch h {
case .function(let tags, _):
form?.addRowObservers(to: self, rowTags: tags, type: .hidden)
case .predicate(let predicate):
form?.addRowObservers(to: self, rowTags: predicate.predicateVars, type: .hidden)
}
}
/**
Internal function called when this section was removed from a form.
*/
func willBeRemovedFromForm() {
for row in kvoWrapper._allRows {
row.willBeRemovedFromForm()
}
removeFromRowObservers()
self.form = nil
}
/**
Internal function called to remove this section from the observers of certain rows. Called when the hidden variable is changed.
*/
func removeFromRowObservers() {
guard let h = hidden else { return }
switch h {
case .function(let tags, _):
form?.removeRowObservers(from: self, rowTags: tags, type: .hidden)
case .predicate(let predicate):
form?.removeRowObservers(from: self, rowTags: predicate.predicateVars, type: .hidden)
}
}
func hide(row: BaseRow) {
row.baseCell.cellResignFirstResponder()
(row as? BaseInlineRowType)?.collapseInlineRow()
kvoWrapper.rows.remove(row)
}
func show(row: BaseRow) {
guard !kvoWrapper.rows.contains(row) else { return }
guard var index = kvoWrapper._allRows.index(of: row) else { return }
var formIndex = NSNotFound
while formIndex == NSNotFound && index > 0 {
index = index - 1
let previous = kvoWrapper._allRows[index]
formIndex = kvoWrapper.rows.index(of: previous)
}
kvoWrapper.rows.insert(row, at: formIndex == NSNotFound ? 0 : formIndex + 1)
}
}
/**
* Navigation options for a form view controller.
*/
public struct MultivaluedOptions: OptionSet {
private enum Options: Int {
case none = 0, insert = 1, delete = 2, reorder = 4
}
public let rawValue: Int
public init(rawValue: Int) { self.rawValue = rawValue}
private init(_ options: Options) { self.rawValue = options.rawValue }
/// No multivalued.
public static let None = MultivaluedOptions(.none)
/// Allows user to insert rows.
public static let Insert = MultivaluedOptions(.insert)
/// Allows user to delete rows.
public static let Delete = MultivaluedOptions(.delete)
/// Allows user to reorder rows
public static let Reorder = MultivaluedOptions(.reorder)
}
/**
* Multivalued sections allows us to easily create insertable, deletable and reorderable sections. By using a multivalued section we can add multiple values for a certain field, such as telephone numbers in a contact.
*/
open class MultivaluedSection: Section {
public var multivaluedOptions: MultivaluedOptions
public var showInsertIconInAddButton = true
public var addButtonProvider: ((MultivaluedSection) -> ButtonRow) = { _ in
return ButtonRow {
$0.title = "Add"
$0.cellStyle = .value1
}.cellUpdate { cell, _ in
cell.textLabel?.textAlignment = .left
}
}
public var multivaluedRowToInsertAt: ((Int) -> BaseRow)?
public required init(multivaluedOptions: MultivaluedOptions = MultivaluedOptions.Insert.union(.Delete),
header: String = "",
footer: String = "",
_ initializer: (MultivaluedSection) -> Void = { _ in }) {
self.multivaluedOptions = multivaluedOptions
super.init(header: header, footer: footer, {section in initializer(section as! MultivaluedSection) })
guard multivaluedOptions.contains(.Insert) else { return }
let addRow = addButtonProvider(self)
addRow.onCellSelection { cell, row in
guard let tableView = cell.formViewController()?.tableView, let indexPath = row.indexPath else { return }
cell.formViewController()?.tableView(tableView, commit: .insert, forRowAt: indexPath)
}
self <<< addRow
}
public required init() {
self.multivaluedOptions = MultivaluedOptions.Insert.union(.Delete)
super.init()
let addRow = addButtonProvider(self)
addRow.onCellSelection { cell, row in
guard let tableView = cell.formViewController()?.tableView, let indexPath = row.indexPath else { return }
cell.formViewController()?.tableView(tableView, commit: .insert, forRowAt: indexPath)
}
self <<< addRow
}
}
| mit | 63213d3a64ee673a8087c4d1a65c2399 | 36.412698 | 218 | 0.637554 | 4.757497 | false | false | false | false |
apple/swift | benchmark/single-source/StringComparison.swift | 10 | 26520 | //===--- StringComparison.swift -------------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 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
//
//===----------------------------------------------------------------------===//
////////////////////////////////////////////////////////////////////////////////
// WARNING: This file is manually generated from .gyb template and should not
// be directly modified. Instead, make changes to StringComparison.swift.gyb and run
// scripts/generate_harness/generate_harness.py to regenerate this file.
////////////////////////////////////////////////////////////////////////////////
//
// Test String iteration performance over a variety of workloads, languages,
// and symbols.
//
import TestsUtils
extension String {
func lines() -> [String] {
return self.split(separator: "\n").map { String($0) }
}
}
public let benchmarks: [BenchmarkInfo] = [
BenchmarkInfo(
name: "StringComparison_ascii",
runFunction: run_StringComparison_ascii,
tags: [.validation, .api, .String],
setUpFunction: { blackHole(workload_ascii) }
),
BenchmarkInfo(
name: "StringComparison_latin1",
runFunction: run_StringComparison_latin1,
tags: [.validation, .api, .String],
setUpFunction: { blackHole(workload_latin1) },
legacyFactor: 2
),
BenchmarkInfo(
name: "StringComparison_fastPrenormal",
runFunction: run_StringComparison_fastPrenormal,
tags: [.validation, .api, .String],
setUpFunction: { blackHole(workload_fastPrenormal) },
legacyFactor: 10
),
BenchmarkInfo(
name: "StringComparison_slowerPrenormal",
runFunction: run_StringComparison_slowerPrenormal,
tags: [.validation, .api, .String],
setUpFunction: { blackHole(workload_slowerPrenormal) },
legacyFactor: 10
),
BenchmarkInfo(
name: "StringComparison_nonBMPSlowestPrenormal",
runFunction: run_StringComparison_nonBMPSlowestPrenormal,
tags: [.validation, .api, .String],
setUpFunction: { blackHole(workload_nonBMPSlowestPrenormal) },
legacyFactor: 10
),
BenchmarkInfo(
name: "StringComparison_emoji",
runFunction: run_StringComparison_emoji,
tags: [.validation, .api, .String],
setUpFunction: { blackHole(workload_emoji) },
legacyFactor: 4
),
BenchmarkInfo(
name: "StringComparison_abnormal",
runFunction: run_StringComparison_abnormal,
tags: [.validation, .api, .String],
setUpFunction: { blackHole(workload_abnormal) },
legacyFactor: 20
),
BenchmarkInfo(
name: "StringComparison_zalgo",
runFunction: run_StringComparison_zalgo,
tags: [.validation, .api, .String],
setUpFunction: { blackHole(workload_zalgo) },
legacyFactor: 25
),
BenchmarkInfo(
name: "StringComparison_longSharedPrefix",
runFunction: run_StringComparison_longSharedPrefix,
tags: [.validation, .api, .String],
setUpFunction: { blackHole(workload_longSharedPrefix) }
),
BenchmarkInfo(
name: "StringHashing_ascii",
runFunction: run_StringHashing_ascii,
tags: [.validation, .api, .String],
setUpFunction: { blackHole(workload_ascii) }
),
BenchmarkInfo(
name: "StringHashing_latin1",
runFunction: run_StringHashing_latin1,
tags: [.validation, .api, .String],
setUpFunction: { blackHole(workload_latin1) },
legacyFactor: 2
),
BenchmarkInfo(
name: "StringHashing_fastPrenormal",
runFunction: run_StringHashing_fastPrenormal,
tags: [.validation, .api, .String],
setUpFunction: { blackHole(workload_fastPrenormal) },
legacyFactor: 10
),
BenchmarkInfo(
name: "StringHashing_slowerPrenormal",
runFunction: run_StringHashing_slowerPrenormal,
tags: [.validation, .api, .String],
setUpFunction: { blackHole(workload_slowerPrenormal) },
legacyFactor: 10
),
BenchmarkInfo(
name: "StringHashing_nonBMPSlowestPrenormal",
runFunction: run_StringHashing_nonBMPSlowestPrenormal,
tags: [.validation, .api, .String],
setUpFunction: { blackHole(workload_nonBMPSlowestPrenormal) },
legacyFactor: 10
),
BenchmarkInfo(
name: "StringHashing_emoji",
runFunction: run_StringHashing_emoji,
tags: [.validation, .api, .String],
setUpFunction: { blackHole(workload_emoji) },
legacyFactor: 4
),
BenchmarkInfo(
name: "StringHashing_abnormal",
runFunction: run_StringHashing_abnormal,
tags: [.validation, .api, .String],
setUpFunction: { blackHole(workload_abnormal) },
legacyFactor: 20
),
BenchmarkInfo(
name: "StringHashing_zalgo",
runFunction: run_StringHashing_zalgo,
tags: [.validation, .api, .String],
setUpFunction: { blackHole(workload_zalgo) },
legacyFactor: 25
),
BenchmarkInfo(
name: "NormalizedIterator_ascii",
runFunction: run_StringNormalization_ascii,
tags: [.validation, .String],
setUpFunction: { blackHole(workload_ascii) }
),
BenchmarkInfo(
name: "NormalizedIterator_latin1",
runFunction: run_StringNormalization_latin1,
tags: [.validation, .String],
setUpFunction: { blackHole(workload_latin1) },
legacyFactor: 2
),
BenchmarkInfo(
name: "NormalizedIterator_fastPrenormal",
runFunction: run_StringNormalization_fastPrenormal,
tags: [.validation, .String],
setUpFunction: { blackHole(workload_fastPrenormal) },
legacyFactor: 10
),
BenchmarkInfo(
name: "NormalizedIterator_slowerPrenormal",
runFunction: run_StringNormalization_slowerPrenormal,
tags: [.validation, .String],
setUpFunction: { blackHole(workload_slowerPrenormal) },
legacyFactor: 10
),
BenchmarkInfo(
name: "NormalizedIterator_nonBMPSlowestPrenormal",
runFunction: run_StringNormalization_nonBMPSlowestPrenormal,
tags: [.validation, .String],
setUpFunction: { blackHole(workload_nonBMPSlowestPrenormal) },
legacyFactor: 10
),
BenchmarkInfo(
name: "NormalizedIterator_emoji",
runFunction: run_StringNormalization_emoji,
tags: [.validation, .String],
setUpFunction: { blackHole(workload_emoji) },
legacyFactor: 4
),
BenchmarkInfo(
name: "NormalizedIterator_abnormal",
runFunction: run_StringNormalization_abnormal,
tags: [.validation, .String],
setUpFunction: { blackHole(workload_abnormal) },
legacyFactor: 20
),
BenchmarkInfo(
name: "NormalizedIterator_zalgo",
runFunction: run_StringNormalization_zalgo,
tags: [.validation, .String],
setUpFunction: { blackHole(workload_zalgo) },
legacyFactor: 25
),
]
let workload_ascii: Workload! = Workload.ascii
let workload_latin1: Workload! = Workload.latin1
let workload_fastPrenormal: Workload! = Workload.fastPrenormal
let workload_slowerPrenormal: Workload! = Workload.slowerPrenormal
let workload_nonBMPSlowestPrenormal: Workload! = Workload.nonBMPSlowestPrenormal
let workload_emoji: Workload! = Workload.emoji
let workload_abnormal: Workload! = Workload.abnormal
let workload_zalgo: Workload! = Workload.zalgo
let workload_longSharedPrefix: Workload! = Workload.longSharedPrefix
@inline(never)
public func run_StringComparison_ascii(_ n: Int) {
let workload: Workload = workload_ascii
let tripCount = workload.tripCount
let payload = workload.payload
for _ in 1...tripCount*n {
for s1 in payload {
for s2 in payload {
blackHole(s1 < s2)
}
}
}
}
@inline(never)
public func run_StringComparison_latin1(_ n: Int) {
let workload: Workload = workload_latin1
let tripCount = workload.tripCount
let payload = workload.payload
for _ in 1...tripCount*n {
for s1 in payload {
for s2 in payload {
blackHole(s1 < s2)
}
}
}
}
@inline(never)
public func run_StringComparison_fastPrenormal(_ n: Int) {
let workload: Workload = workload_fastPrenormal
let tripCount = workload.tripCount
let payload = workload.payload
for _ in 1...tripCount*n {
for s1 in payload {
for s2 in payload {
blackHole(s1 < s2)
}
}
}
}
@inline(never)
public func run_StringComparison_slowerPrenormal(_ n: Int) {
let workload: Workload = workload_slowerPrenormal
let tripCount = workload.tripCount
let payload = workload.payload
for _ in 1...tripCount*n {
for s1 in payload {
for s2 in payload {
blackHole(s1 < s2)
}
}
}
}
@inline(never)
public func run_StringComparison_nonBMPSlowestPrenormal(_ n: Int) {
let workload: Workload = workload_nonBMPSlowestPrenormal
let tripCount = workload.tripCount
let payload = workload.payload
for _ in 1...tripCount*n {
for s1 in payload {
for s2 in payload {
blackHole(s1 < s2)
}
}
}
}
@inline(never)
public func run_StringComparison_emoji(_ n: Int) {
let workload: Workload = workload_emoji
let tripCount = workload.tripCount
let payload = workload.payload
for _ in 1...tripCount*n {
for s1 in payload {
for s2 in payload {
blackHole(s1 < s2)
}
}
}
}
@inline(never)
public func run_StringComparison_abnormal(_ n: Int) {
let workload: Workload = workload_abnormal
let tripCount = workload.tripCount
let payload = workload.payload
for _ in 1...tripCount*n {
for s1 in payload {
for s2 in payload {
blackHole(s1 < s2)
}
}
}
}
@inline(never)
public func run_StringComparison_zalgo(_ n: Int) {
let workload: Workload = workload_zalgo
let tripCount = workload.tripCount
let payload = workload.payload
for _ in 1...tripCount*n {
for s1 in payload {
for s2 in payload {
blackHole(s1 < s2)
}
}
}
}
@inline(never)
public func run_StringComparison_longSharedPrefix(_ n: Int) {
let workload: Workload = workload_longSharedPrefix
let tripCount = workload.tripCount
let payload = workload.payload
for _ in 1...tripCount*n {
for s1 in payload {
for s2 in payload {
blackHole(s1 < s2)
}
}
}
}
@inline(never)
public func run_StringHashing_ascii(_ n: Int) {
let workload: Workload = Workload.ascii
let tripCount = workload.tripCount
let payload = workload.payload
for _ in 1...tripCount*n {
for str in payload {
blackHole(str.hashValue)
}
}
}
@inline(never)
public func run_StringHashing_latin1(_ n: Int) {
let workload: Workload = Workload.latin1
let tripCount = workload.tripCount
let payload = workload.payload
for _ in 1...tripCount*n {
for str in payload {
blackHole(str.hashValue)
}
}
}
@inline(never)
public func run_StringHashing_fastPrenormal(_ n: Int) {
let workload: Workload = Workload.fastPrenormal
let tripCount = workload.tripCount
let payload = workload.payload
for _ in 1...tripCount*n {
for str in payload {
blackHole(str.hashValue)
}
}
}
@inline(never)
public func run_StringHashing_slowerPrenormal(_ n: Int) {
let workload: Workload = Workload.slowerPrenormal
let tripCount = workload.tripCount
let payload = workload.payload
for _ in 1...tripCount*n {
for str in payload {
blackHole(str.hashValue)
}
}
}
@inline(never)
public func run_StringHashing_nonBMPSlowestPrenormal(_ n: Int) {
let workload: Workload = Workload.nonBMPSlowestPrenormal
let tripCount = workload.tripCount
let payload = workload.payload
for _ in 1...tripCount*n {
for str in payload {
blackHole(str.hashValue)
}
}
}
@inline(never)
public func run_StringHashing_emoji(_ n: Int) {
let workload: Workload = Workload.emoji
let tripCount = workload.tripCount
let payload = workload.payload
for _ in 1...tripCount*n {
for str in payload {
blackHole(str.hashValue)
}
}
}
@inline(never)
public func run_StringHashing_abnormal(_ n: Int) {
let workload: Workload = Workload.abnormal
let tripCount = workload.tripCount
let payload = workload.payload
for _ in 1...tripCount*n {
for str in payload {
blackHole(str.hashValue)
}
}
}
@inline(never)
public func run_StringHashing_zalgo(_ n: Int) {
let workload: Workload = Workload.zalgo
let tripCount = workload.tripCount
let payload = workload.payload
for _ in 1...tripCount*n {
for str in payload {
blackHole(str.hashValue)
}
}
}
@inline(never)
public func run_StringNormalization_ascii(_ n: Int) {
let workload: Workload = Workload.ascii
let tripCount = workload.tripCount
let payload = workload.payload
for _ in 1...tripCount*n {
for str in payload {
str._withNFCCodeUnits { cu in
blackHole(cu)
}
}
}
}
@inline(never)
public func run_StringNormalization_latin1(_ n: Int) {
let workload: Workload = Workload.latin1
let tripCount = workload.tripCount
let payload = workload.payload
for _ in 1...tripCount*n {
for str in payload {
str._withNFCCodeUnits { cu in
blackHole(cu)
}
}
}
}
@inline(never)
public func run_StringNormalization_fastPrenormal(_ n: Int) {
let workload: Workload = Workload.fastPrenormal
let tripCount = workload.tripCount
let payload = workload.payload
for _ in 1...tripCount*n {
for str in payload {
str._withNFCCodeUnits { cu in
blackHole(cu)
}
}
}
}
@inline(never)
public func run_StringNormalization_slowerPrenormal(_ n: Int) {
let workload: Workload = Workload.slowerPrenormal
let tripCount = workload.tripCount
let payload = workload.payload
for _ in 1...tripCount*n {
for str in payload {
str._withNFCCodeUnits { cu in
blackHole(cu)
}
}
}
}
@inline(never)
public func run_StringNormalization_nonBMPSlowestPrenormal(_ n: Int) {
let workload: Workload = Workload.nonBMPSlowestPrenormal
let tripCount = workload.tripCount
let payload = workload.payload
for _ in 1...tripCount*n {
for str in payload {
str._withNFCCodeUnits { cu in
blackHole(cu)
}
}
}
}
@inline(never)
public func run_StringNormalization_emoji(_ n: Int) {
let workload: Workload = Workload.emoji
let tripCount = workload.tripCount
let payload = workload.payload
for _ in 1...tripCount*n {
for str in payload {
str._withNFCCodeUnits { cu in
blackHole(cu)
}
}
}
}
@inline(never)
public func run_StringNormalization_abnormal(_ n: Int) {
let workload: Workload = Workload.abnormal
let tripCount = workload.tripCount
let payload = workload.payload
for _ in 1...tripCount*n {
for str in payload {
str._withNFCCodeUnits { cu in
blackHole(cu)
}
}
}
}
@inline(never)
public func run_StringNormalization_zalgo(_ n: Int) {
let workload: Workload = Workload.zalgo
let tripCount = workload.tripCount
let payload = workload.payload
for _ in 1...tripCount*n {
for str in payload {
str._withNFCCodeUnits { cu in
blackHole(cu)
}
}
}
}
struct Workload {
static let n = 100
let name: String
let payload: [String]
var scaleMultiplier: Double
init(name: String, payload: [String], scaleMultiplier: Double = 1.0) {
self.name = name
self.payload = payload
self.scaleMultiplier = scaleMultiplier
}
var tripCount: Int {
return Int(Double(Workload.n) * scaleMultiplier)
}
static let ascii = Workload(
name: "ASCII",
payload: """
woodshed
lakism
gastroperiodynia
afetal
Casearia
ramsch
Nickieben
undutifulness
decorticate
neognathic
mentionable
tetraphenol
pseudonymal
dislegitimate
Discoidea
criminative
disintegratory
executer
Cylindrosporium
complimentation
Ixiama
Araceae
silaginoid
derencephalus
Lamiidae
marrowlike
ninepin
trihemimer
semibarbarous
heresy
existence
fretless
Amiranha
handgravure
orthotropic
Susumu
teleutospore
sleazy
shapeliness
hepatotomy
exclusivism
stifler
cunning
isocyanuric
pseudepigraphy
carpetbagger
unglory
""".lines(),
scaleMultiplier: 0.25
)
static let latin1 = Workload(
name: "Latin1",
payload: """
café
résumé
caférésumé
¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º
1+1=3
¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹
¡¢£¤¥¦§¨©ª«¬®
»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍ
ÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãä
åæçèéêëìíîïðñò
ÎÏÐÑÒÓÔÕÖëìíîïðñò
óôõö÷øùúûüýþÿ
123.456£=>¥
123.456
""".lines(),
scaleMultiplier: 1/2
)
static let fastPrenormal = Workload(
name: "FastPrenormal",
payload: """
ĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥ
ĦħĨĩĪīĬĭĮįİıIJijĴĵĶķĸ
ĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲ
ųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆ
ƇƈƉƊƋƌƍƎƏƐƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀ
Ƈ
ǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖ
ǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴǵǶǷǸǹǺǻǼǽǾǿȀȁȂȃȄȅȆȇȈȉȊȋȌȍȎȏȐȑ
ȒȓȔȕȖȗȘșȚțȜȝȞȟȠȡȢȣȤȥȦȧȨȩȪȫȬ
ȒȓȔȕȖȗȘșȚțȜȝȞȟȠȡȢȣȤȥȦȧȨȩȪȫȬDzdzǴǵǶǷǸǹǺǻǼǽǾǿȀȁȂȃȄȅȆȇȈȉȊȋȌȍȎȏȐȑ
ȭȮȯȰȱȲȳȴȵȶȷȸȹȺȻȼȽȾȿɀɁɂɃɄɅɆɇɈɉɊɋɌɍɎɏɐɑɒɓɔɕɖɗɘəɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰ
ɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄ
ɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃ
ʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰ
ʱʲʳʴʵʶʷʸʹʺʻʼʽʾʿˀˁ˂˃˄˅ˆˇˈˉˊˋˌˍˎˏːˑ˒˓˔˕˖˗˘˙˚˛˜˝˞˟ˠˡˢˣˤ˥˦
˧˨˩˪˫ˬ˭ˮ˯˰˱˲˳˴˵˶˷˸˹˺˻˼˽˾
""".lines(),
scaleMultiplier: 1/10
)
static let slowerPrenormal = Workload(
name: "SlowerPrenormal",
payload: """
Swiftに大幅な改良が施され、
安定していてしかも
直感的に使うことができる
向けプログラミング言語になりました。
이번 업데이트에서는 강력하면서도
\u{201c}Hello\u{2010}world\u{2026}\u{201d}
平台的编程语言
功能强大且直观易用
而本次更新对其进行了全面优化
в чащах юга жил-был цитрус
\u{300c}\u{300e}今日は\u{3001}世界\u{3002}\u{300f}\u{300d}
но фальшивый экземпляр
""".lines(),
scaleMultiplier: 1/10
)
// static let slowestPrenormal = """
// """.lines()
static let nonBMPSlowestPrenormal = Workload(
name: "NonBMPSlowestPrenormal",
payload: """
𓀀𓀤𓁓𓁲𓃔𓃗
𓀀𓀁𓀂𓀃𓀄𓀇𓀈𓀉𓀊𓀋𓀌𓀍𓀎𓀏𓀓𓀔𓀕𓀖𓀗𓀘𓀙𓀚𓀛𓀜𓀞𓀟𓀠𓀡𓀢𓀣
𓀤𓀥𓀦𓀧𓀨𓀩𓀪𓀫𓀬𓀭
𓁡𓁢𓁣𓁤𓁥𓁦𓁧𓁨𓁩𓁫𓁬𓁭𓁮𓁯𓁰𓁱𓁲𓁳𓁴𓁵𓁶𓁷𓁸
𓁹𓁺𓁓𓁔𓁕𓁻𓁼𓁽𓁾𓁿
𓀀𓀁𓀂𓀃𓀄𓃒𓃓𓃔𓃕𓃻𓃼𓃽𓃾𓃿𓄀𓄁𓄂𓄃𓄄𓄅𓄆𓄇𓄈𓄉𓄊𓄋𓄌𓄍𓄎
𓂿𓃀𓃁𓃂𓃃𓃄𓃅
𓃘𓃙𓃚𓃛𓃠𓃡𓃢𓃣𓃦𓃧𓃨𓃩𓃬𓃭𓃮𓃯𓃰𓃲𓃳𓃴𓃵𓃶𓃷𓃸
𓃘𓃙𓃚𓃛𓃠𓃡𓃢𓃣𓃦𓃧𓃨𓃩𓃬𓃭𓃮𓃯𓃰𓃲𓃳𓃴𓃵𓃶𓃷
𓀀𓀁𓀂𓀃𓀄𓆇𓆈𓆉𓆊𓆋𓆌𓆍𓆎𓆏𓆐𓆑𓆒𓆓𓆔𓆗𓆘𓆙𓆚𓆛𓆝𓆞𓆟𓆠𓆡𓆢𓆣𓆤
𓆥𓆦𓆧𓆨𓆩𓆪𓆫𓆬𓆭𓆮𓆯𓆰𓆱𓆲𓆳𓆴𓆵𓆶𓆷𓆸𓆹𓆺𓆻
""".lines(),
scaleMultiplier: 1/10
)
static let emoji = Workload(
name: "Emoji",
payload: """
👍👩👩👧👧👨👨👦👦🇺🇸🇨🇦🇲🇽👍🏻👍🏼👍🏽👍🏾👍🏿
👍👩👩👧👧👨👨👦👦🇺🇸🇨🇦🇲🇽👍🏿👍🏻👍🏼👍🏽👍🏾
😀🧀😀😃😄😁🤣😂😅😆
😺🎃🤖👾😸😹😻😼😾😿🙀😽🙌🙏🤝👍✌🏽
☺️😊😇🙂😍😌😉🙃😘😗😙😚😛😝😜
😋🤑🤗🤓😎😒😏🤠🤡😞😔😟😕😖😣☹️🙁😫😩😤😠😑😐😶😡😯
😦😧😮😱😳😵😲😨😰😢😥
😪😓😭🤤😴🙄🤔🤥🤧🤢🤐😬😷🤒🤕😈💩👺👹👿👻💀☠️👽
""".lines(),
scaleMultiplier: 1/4
)
static let abnormal = Workload(
name: "Abnormal",
payload: """
ae\u{301}ae\u{301}ae\u{302}ae\u{303}ae\u{304}ae\u{305}ae\u{306}ae\u{307}
ae\u{301}ae\u{301}ae\u{301}ae\u{301}ae\u{301}ae\u{301}ae\u{301}ae\u{300}
\u{f900}\u{f901}\u{f902}\u{f903}\u{f904}\u{f905}\u{f906}\u{f907}\u{f908}\u{f909}\u{f90a}
\u{f90b}\u{f90c}\u{f90d}\u{f90e}\u{f90f}\u{f910}\u{f911}\u{f912}\u{f913}\u{f914}\u{f915}\u{f916}\u{f917}\u{f918}\u{f919}
\u{f900}\u{f91a}\u{f91b}\u{f91c}\u{f91d}\u{f91e}\u{f91f}\u{f920}\u{f921}\u{f922}
""".lines(),
scaleMultiplier: 1/20
)
// static let pathological = """
// """.lines()
static let zalgo = Workload(
name: "Zalgo",
payload: """
ṭ̴̵̶̷̸̢̧̨̡̛̤̥̦̩̪̫̬̭̮̯̰̖̗̘̙̜̝̞̟̠̱̲̳̹̺̻̼͇͈͉͍͎̀́̂̃̄̅̆̇̈̉ͣͤ̊̋̌̍̎̏̐̑̒̓̔̽̾̿̀́͂̓̈́͆͊͋͌̕̚͜͟͢͝͞͠͡ͅ͏͓͔͕͖͙͚͐͑͒͗͛ͣͤͥͦͧͨͩͪͫͬͭͮ͘͜͟͢͝͞͠͡
h̀́̂̃
è͇͈͉͍͎́̂̃̄̅̆̇̈̉͊͋͌͏̡̢̧̨̛͓͔͕͖͙͚̖̗̘̙̜̝̞̟̠̣̤̥̦̩̪̫̬̭͇͈͉͍͎͐͑͒͗͛̊̋̌̍̎̏̐̑̒̓̔̀́͂̓̈́͆͊͋͌͘̕̚͜͟͝͞͠ͅ͏͓͔͕͖͐͑͒
q̴̵̶̷̸̡̢̧̨̛̖̗̘̙̜̝̞̟̠̣̤̥̦̩̪̫̬̭̮̯̰̱̲̳̹̺̻̼͇̀́̂̃̄̅̆̇̈̉̊̋̌̍̎̏̐̑̒̓̔̽̾̿̀́͂̓̈́͆̕̚ͅ
ư̴̵̶̷̸̗̘̙̜̹̺̻̼͇͈͉͍͎̽̾̿̀́͂̓̈́͆͊͋͌̚ͅ͏͓͔͕͖͙͚͐͑͒͗͛ͣͤͥͦͧͨͩͪͫͬͭͮ͘͜͟͢͝͞͠͡
ì̡̢̧̨̝̞̟̠̣̤̥̦̩̪̫̬̭̮̯̰̹̺̻̼͇͈͉͍͎́̂̃̄̉̊̋̌̍̎̏̐̑̒̓̽̾̿̀́͂̓̈́͆͊͋͌ͅ͏͓͔͕͖͙͐͑͒͗ͬͭͮ͘
c̴̵̶̷̸̡̢̧̨̛̖̗̘̙̜̝̞̟̠̣̤̥̦̩̪̫̬̭̮̯̰̱̲̳̹̺̻̼̀́̂̃̄̔̽̾̿̀́͂̓̈́͆ͣͤͥͦͧͨͩͪͫͬͭͮ̕̚͢͡ͅ
k̴̵̶̷̸̡̢̧̨̛̖̗̘̙̜̝̞̟̠̣̤̥̦̩̪̫̬̭̮̯̰̱̲̳̹̺̻̼͇͈͉͍͎̀́̂̃̄̅̆̇̈̉̊̋̌̍̎̏̐̑̒̓̔̽̾̿̀́͂̓̈́͆͊͋͌̕̚ͅ͏͓͔͕͖͙͚͐͑͒͗͛ͣͤͥͦͧͨͩͪͫͬͭͮ͘͜͟͢͝͞͠͡
b̴̵̶̷̸̡̢̛̗̘̙̜̝̞̟̠̹̺̻̼͇͈͉͍͎̽̾̿̀́͂̓̈́͆͊͋͌̚ͅ͏͓͔͕͖͙͚͐͑͒͗͛ͣͤͥͦͧͨͩͪͫͬͭͮ͘͜͟͢͝͞͠͡
ŗ̴̵̶̷̸̨̛̩̪̫̯̰̱̲̳̹̺̻̼̬̭̮͇̗̘̙̜̝̞̟̤̥̦͉͍͎̽̾̿̀́͂̓̈́͆͊͋͌̚ͅ͏̡̢͓͔͕͖͙͚̠̣͐͑͒͗͛ͣͤͥͦͧͨͩͪͫͬͭͮ͘͜͟͢͝͞͠͡
o
w̗̘͇͈͉͍͎̓̈́͆͊͋͌ͅ͏̛͓͔͕͖͙͚̙̜̹̺̻̼͐͑͒͗͛ͣͤͥͦ̽̾̿̀́͂ͧͨͩͪͫͬͭͮ͘̚͜͟͢͝͞͠͡
n͇͈͉͍͎͊͋͌ͧͨͩͪͫͬͭͮ͏̛͓͔͕͖͙͚̗̘̙̜̹̺̻̼͐͑͒͗͛ͣͤͥͦ̽̾̿̀́͂̓̈́͆ͧͨͩͪͫͬͭͮ͘̚͜͟͢͝͞͠͡ͅ
f̛̗̘̙̜̹̺̻̼͇͈͉͍͎̽̾̿̀́͂̓̈́͆͊͋͌̚ͅ͏͓͔͕͖͙͚͐͑͒͗͛ͣͤͥͦ͘͜͟͢͝͞͠͡
ơ̗̘̙̜̹̺̻̼͇͈͉͍͎̽̾̿̀́͂̓̈́͆͊͋͌̚ͅ͏͓͔͕͖͙͚͐͑͒͗͛ͥͦͧͨͩͪͫͬͭͮ͘
xͣͤͥͦͧͨͩͪͫͬͭͮ
""".lines(),
scaleMultiplier: 1/100
)
static let longSharedPrefix = Workload(
name: "LongSharedPrefix",
payload: """
http://www.dogbook.com/dog/239495828/friends/mutual/2939493815
http://www.dogbook.com/dog/239495828/friends/mutual/3910583739
http://www.dogbook.com/dog/239495828/friends/mutual/3910583739/shared
http://www.dogbook.com/dog/239495828/friends/mutual/3910583739/shared
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.🤔
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
🤔Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.🤔
""".lines()
)
}
// Local Variables:
// eval: (read-only-mode 1)
// End:
| apache-2.0 | 6916c86224357a4b3f610ee52049fd75 | 28.811224 | 451 | 0.640852 | 3.09686 | false | false | false | false |
skela/SwiftyDropbox | TestSwiftyDropbox/TestSwiftyDropbox_iOS/AppDelegate.swift | 1 | 4605 | ///
/// Copyright (c) 2016 Dropbox, Inc. All rights reserved.
///
import UIKit
import SwiftyDropbox
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if (TestData.fullDropboxAppKey.range(of:"<") != nil || TestData.teamMemberFileAccessAppKey.range(of:"<") != nil || TestData.teamMemberManagementAppKey.range(of:"<") != nil) {
print("\n\n\nMust set test data (in TestData.swift) before launching app.\n\n\nTerminating.....\n\n")
exit(0);
}
switch(appPermission) {
case .fullDropbox:
DropboxClientsManager.setupWithAppKey(TestData.fullDropboxAppKey)
case .teamMemberFileAccess:
DropboxClientsManager.setupWithTeamAppKey(TestData.teamMemberFileAccessAppKey)
case .teamMemberManagement:
DropboxClientsManager.setupWithTeamAppKey(TestData.teamMemberManagementAppKey)
}
return true
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
switch(appPermission) {
case .fullDropbox:
if let authResult = DropboxClientsManager.handleRedirectURL(url) {
switch authResult {
case .success:
print("Success! User is logged into DropboxClientsManager.")
case .cancel:
print("Authorization flow was manually canceled by user!")
case .error(_, let description):
print("Error: \(description)")
}
}
case .teamMemberFileAccess:
if let authResult = DropboxClientsManager.handleRedirectURLTeam(url) {
switch authResult {
case .success:
print("Success! User is logged into DropboxClientsManager.")
case .cancel:
print("Authorization flow was manually canceled by user!")
case .error(_, let description):
print("Error: \(description)")
}
}
case .teamMemberManagement:
if let authResult = DropboxClientsManager.handleRedirectURLTeam(url) {
switch authResult {
case .success:
print("Success! User is logged into DropboxClientsManager.")
case .cancel:
print("Authorization flow was manually canceled by user!")
case .error(_, let description):
print("Error: \(description)")
}
}
}
let mainController = self.window!.rootViewController as! ViewController
mainController.checkButtons()
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 | b21882b79fb8aec0902a842421a08b93 | 49.054348 | 285 | 0.654072 | 5.799748 | false | true | false | false |
grgcombs/PlayingCards-Swift | Pod/Classes/RandomNumber.swift | 1 | 1822 | //
// RandomNumber.swift
// PlayingCards (Swift)
//
// Created by Gregory Combs on 7/14/15.
//
import Foundation
public extension Int
{
/**
Returns a random number with the given lower and upper boundary integers
:param: lower The lowest possible integer to return
:param: upper The highest possible integer to return
:returns: A random integer within the limits provided
Derived from http://stackoverflow.com/a/26140302/136582
*/
public static func random(#lower: Int, upper: Int) -> Int {
var offset = 0;
// allow negative boundaries
if lower < 0
{
offset = abs(lower);
}
let mini = UInt32(lower + offset);
let maxi = UInt32(upper + offset);
return Int(mini + arc4random_uniform(maxi - mini)) - offset;
}
/**
Returns a random number with the given range of integers
var aNumber = Int.random(-500...100);
:param: range A range of integers. Negative boundaries are permitted.
:returns: A random integer within the range provided.
From http://stackoverflow.com/a/26140302/136582
*/
public static func random(range: Range<Int> ) -> Int
{
return random(lower: range.startIndex, upper: range.endIndex);
}
}
public func randomWithType <T: IntegerLiteralConvertible> (type: T.Type) -> T {
var r: T = 0;
arc4random_buf(&r, Int(sizeof(T)));
return r;
}
public extension Double {
/**
Create a random num Double
:param: lower number Double
:param: upper number Double
:return: random number Double
By DaRkDOG
*/
public static func random(#lower: Double, upper: Double) -> Double {
let r = Double(randomWithType(UInt64)) / Double(UInt64.max)
return (r * (upper - lower)) + lower
}
}
| mit | 8d37251753dca3969e5ff5ec3117738c | 24.305556 | 79 | 0.632272 | 4.004396 | false | false | false | false |
kickstarter/ios-oss | Kickstarter-iOS/Features/BackerDashboardProjects/Views/Cells/BackerDashboardProjectCell.swift | 1 | 4005 | import Foundation
import KsApi
import Library
import Prelude
import UIKit
internal final class BackerDashboardProjectCell: UITableViewCell, ValueCell {
fileprivate let viewModel: BackerDashboardProjectCellViewModelType = BackerDashboardProjectCellViewModel()
@IBOutlet fileprivate var cardView: UIView!
@IBOutlet fileprivate var mainContentContainerView: UIView!
@IBOutlet fileprivate var metadataBackgroundView: UIView!
@IBOutlet fileprivate var metadataIconImageView: UIImageView!
@IBOutlet fileprivate var metadataLabel: UILabel!
@IBOutlet fileprivate var metadataStackView: UIStackView!
@IBOutlet fileprivate var percentFundedLabel: UILabel!
@IBOutlet fileprivate var projectNameLabel: UILabel!
@IBOutlet fileprivate var projectImageView: UIImageView!
@IBOutlet fileprivate var progressStaticView: UIView!
@IBOutlet fileprivate var progressBarView: UIView!
@IBOutlet fileprivate var savedIconImageView: UIImageView!
internal func configureWith(value: Project) {
self.viewModel.inputs.configureWith(project: value)
}
internal override func bindViewModel() {
self.metadataBackgroundView.rac.backgroundColor = self.viewModel.outputs.metadataBackgroundColor
self.metadataLabel.rac.text = self.viewModel.outputs.metadataText
self.metadataIconImageView.rac.hidden = self.viewModel.outputs.metadataIconIsHidden
self.percentFundedLabel.rac.attributedText = self.viewModel.outputs.percentFundedText
self.projectNameLabel.rac.attributedText = self.viewModel.outputs.projectTitleText
self.projectImageView.rac.ksr_imageUrl = self.viewModel.outputs.photoURL
self.progressBarView.rac.backgroundColor = self.viewModel.outputs.progressBarColor
self.savedIconImageView.rac.hidden = self.viewModel.outputs.savedIconIsHidden
self.viewModel.outputs.progress
.observeForUI()
.observeValues { [weak element = progressBarView] progress in
let anchorX = progress == 0 ? 0 : 0.5 / progress
element?.layer.anchorPoint = CGPoint(x: CGFloat(max(anchorX, 0.5)), y: 0.5)
element?.transform = CGAffineTransform(scaleX: CGFloat(min(progress, 1.0)), y: 1.0)
}
}
internal override func bindStyles() {
super.bindStyles()
_ = self
|> baseTableViewCellStyle()
|> UITableViewCell.lens.isAccessibilityElement .~ true
|> UITableViewCell.lens.accessibilityHint %~ { _ in Strings.Opens_project() }
|> UITableViewCell.lens.accessibilityTraits .~ UIAccessibilityTraits.button
|> UITableViewCell.lens.contentView.layoutMargins %~~ { _, cell in
cell.traitCollection.isRegularRegular
? .init(topBottom: Styles.grid(2), leftRight: Styles.grid(20))
: .init(topBottom: Styles.grid(1), leftRight: Styles.grid(2))
}
_ = self.cardView
|> cardStyle()
_ = self.mainContentContainerView
|> UIView.lens.layoutMargins .~ .init(
top: Styles.gridHalf(3),
left: Styles.grid(2),
bottom: Styles.grid(1),
right: Styles.grid(2)
)
_ = self.metadataBackgroundView
|> UIView.lens.layer.borderColor .~ UIColor.ksr_white.cgColor
|> UIView.lens.layer.borderWidth .~ 1.0
_ = self.metadataStackView
|> UIStackView.lens.layoutMargins .~ .init(topBottom: Styles.grid(30), leftRight: Styles.grid(20))
_ = self.metadataLabel
|> UILabel.lens.textColor .~ .ksr_white
|> UILabel.lens.font .~ .ksr_headline(size: 12)
_ = self.metadataIconImageView
|> UIImageView.lens.tintColor .~ .ksr_white
_ = self.percentFundedLabel
|> UILabel.lens.backgroundColor .~ .ksr_white
_ = self.projectNameLabel
|> UILabel.lens.backgroundColor .~ .ksr_white
_ = self.progressStaticView
|> UIView.lens.backgroundColor .~ .ksr_support_700
|> UIView.lens.alpha .~ 0.15
_ = self.projectImageView
|> ignoresInvertColorsImageViewStyle
_ = self.savedIconImageView
|> UIImageView.lens.tintColor .~ .init(white: 1.0, alpha: 0.99)
}
}
| apache-2.0 | 79410960f10130f467942d2f575e59b9 | 38.653465 | 108 | 0.724345 | 4.51522 | false | false | false | false |
the-blue-alliance/the-blue-alliance-ios | Frameworks/TBAData/Tests/Event/EventStatusAllianceTests.swift | 1 | 6074 | import CoreData
import TBADataTesting
import TBAKit
import XCTest
@testable import TBAData
class EventStatusAllianceTestCase: TBADataTestCase {
func test_name() {
let status = EventStatusAlliance.init(entity: EventStatusAlliance.entity(), insertInto: persistentContainer.viewContext)
XCTAssertNil(status.name)
status.nameRaw = "qual"
XCTAssertEqual(status.name, "qual")
}
func test_number() {
let status = EventStatusAlliance.init(entity: EventStatusAlliance.entity(), insertInto: persistentContainer.viewContext)
status.numberRaw = NSNumber(value: 2)
XCTAssertEqual(status.number, 2)
}
func test_pick() {
let status = EventStatusAlliance.init(entity: EventStatusAlliance.entity(), insertInto: persistentContainer.viewContext)
status.pickRaw = NSNumber(value: 2)
XCTAssertEqual(status.pick, 2)
}
func test_backup() {
let status = EventStatusAlliance.init(entity: EventStatusAlliance.entity(), insertInto: persistentContainer.viewContext)
XCTAssertNil(status.backup)
let backup = EventAllianceBackup.init(entity: EventAllianceBackup.entity(), insertInto: persistentContainer.viewContext)
status.backupRaw = backup
XCTAssertEqual(status.backup, backup)
}
func test_eventStatus() {
let status = EventStatusAlliance.init(entity: EventStatusAlliance.entity(), insertInto: persistentContainer.viewContext)
let eventStatus = EventStatus.init(entity: EventStatus.entity(), insertInto: persistentContainer.viewContext)
status.eventStatusRaw = eventStatus
XCTAssertEqual(status.eventStatus, eventStatus)
}
func test_fetchRequest() {
let fr: NSFetchRequest<EventStatusAlliance> = EventStatusAlliance.fetchRequest()
XCTAssertEqual(fr.entityName, EventStatusAlliance.entityName)
}
func test_insert() {
let event = insertDistrictEvent()
let backupModel = TBAAllianceBackup(teamIn: "frc3", teamOut: "frc2")
let model = TBAEventStatusAlliance(number: 2, pick: 1, name: "Alliance One", backup: backupModel)
let allianceStatus = EventStatusAlliance.insert(model, eventKey: event.key, teamKey: "frc1", in: persistentContainer.viewContext)
XCTAssertEqual(allianceStatus.name, "Alliance One")
XCTAssertEqual(allianceStatus.number, 2)
XCTAssertEqual(allianceStatus.pick, 1)
XCTAssertNotNil(allianceStatus.backup)
// Should fail - needs an EventStatus
XCTAssertThrowsError(try persistentContainer.viewContext.save())
let modelEventStatus = TBAEventStatus(teamKey: "frc1", eventKey: event.key)
let eventStatus = EventStatus.insert(modelEventStatus, in: persistentContainer.viewContext)
eventStatus.eventRaw = event
eventStatus.allianceRaw = allianceStatus
XCTAssertNoThrow(try persistentContainer.viewContext.save())
}
func test_update() {
let event = insertDistrictEvent()
let backupModel = TBAAllianceBackup(teamIn: "frc3", teamOut: "frc2")
let modelOne = TBAEventStatusAlliance(number: 2, pick: 1, name: "Alliance One", backup: backupModel)
let allianceStatusOne = EventStatusAlliance.insert(modelOne, eventKey: event.key, teamKey: "frc1", in: persistentContainer.viewContext)
let backup = allianceStatusOne.backup!
let modelEventStatus = TBAEventStatus(teamKey: "frc1", eventKey: event.key)
let eventStatus = EventStatus.insert(modelEventStatus, in: persistentContainer.viewContext)
eventStatus.eventRaw = event
eventStatus.allianceRaw = allianceStatusOne
let modelTwo = TBAEventStatusAlliance(number: 3, pick: 2)
let allianceStatusTwo = EventStatusAlliance.insert(modelTwo, eventKey: event.key, teamKey: "frc1", in: persistentContainer.viewContext)
// Sanity check
XCTAssertEqual(allianceStatusOne, allianceStatusTwo)
// Make sure our values got updated properly
XCTAssertEqual(allianceStatusOne.pick, 2)
XCTAssertEqual(allianceStatusOne.number, 3)
XCTAssertNil(allianceStatusOne.name)
XCTAssertNil(allianceStatusOne.backup)
XCTAssertNoThrow(try persistentContainer.viewContext.save())
// Our Backup should be deleted
XCTAssertNil(backup.managedObjectContext)
}
func test_delete() {
let event = insertDistrictEvent()
let backupModel = TBAAllianceBackup(teamIn: "frc3", teamOut: "frc2")
let model = TBAEventStatusAlliance(number: 2, pick: 1, name: "Alliance One", backup: backupModel)
let allianceStatus = EventStatusAlliance.insert(model, eventKey: event.key, teamKey: "frc1", in: persistentContainer.viewContext)
let backup = allianceStatus.backup!
persistentContainer.viewContext.delete(allianceStatus)
XCTAssertNoThrow(try persistentContainer.viewContext.save())
// Backup should be deleted as well
XCTAssertNil(backup.managedObjectContext)
}
func test_delete_backup() {
let event = insertDistrictEvent()
let backupModel = TBAAllianceBackup(teamIn: "frc3", teamOut: "frc2")
let model = TBAEventStatusAlliance(number: 2, pick: 1, name: "Alliance One", backup: backupModel)
let allianceStatus = EventStatusAlliance.insert(model, eventKey: event.key, teamKey: "frc1", in: persistentContainer.viewContext)
let backup = allianceStatus.backup!
let allianceModel = TBAAlliance(name: nil, backup: backupModel, declines: nil, picks: ["frc1"], status: nil)
let alliance = EventAlliance.insert(allianceModel, eventKey: event.key, in: persistentContainer.viewContext)
alliance.eventRaw = event
// Sanity check
XCTAssertEqual(alliance.backup, backup)
persistentContainer.viewContext.delete(allianceStatus)
XCTAssertNoThrow(try persistentContainer.viewContext.save())
// Backup should not be deleted
XCTAssertNotNil(backup.managedObjectContext)
}
}
| mit | a55ef83d308af7f657c77a9000eebe1a | 41.774648 | 143 | 0.714356 | 4.878715 | false | true | false | false |
uasys/swift | benchmark/single-source/StrToInt.swift | 11 | 1889 | //===--- StrToInt.swift ---------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This test checks performance of String to Int conversion.
// It is reported to be very slow: <rdar://problem/17255477>
import TestsUtils
@inline(never)
public func run_StrToInt(_ N: Int) {
// 64 numbers from -500_000 to 500_000 generated randomly
let input = ["-237392", "293715", "126809", "333779", "-362824", "144198",
"-394973", "-163669", "-7236", "376965", "-400783", "-118670",
"454728", "-38915", "136285", "-448481", "-499684", "68298",
"382671", "105432", "-38385", "39422", "-267849", "-439886",
"292690", "87017", "404692", "27692", "486408", "336482",
"-67850", "56414", "-340902", "-391782", "414778", "-494338",
"-413017", "-377452", "-300681", "170194", "428941", "-291665",
"89331", "329496", "-364449", "272843", "-10688", "142542",
"-417439", "167337", "96598", "-264104", "-186029", "98480",
"-316727", "483808", "300149", "-405877", "-98938", "283685",
"-247856", "-46975", "346060", "160085",]
let ref_result = 517492
func DoOneIter(_ arr: [String]) -> Int {
var r = 0
for n in arr {
r += Int(n)!
}
if r < 0 {
r = -r
}
return r
}
var res = Int.max
for _ in 1...1000*N {
res = res & DoOneIter(input)
}
CheckResults(res == ref_result)
}
| apache-2.0 | e3accc221e39c3f5121fc8078edc533c | 39.191489 | 80 | 0.520911 | 3.440801 | false | false | false | false |
uasys/swift | test/SILGen/generic_literals.swift | 3 | 2454 | // RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
// CHECK-LABEL: sil hidden @_T016generic_literals0A14IntegerLiteralyx1x_ts013ExpressibleBycD0RzlF
func genericIntegerLiteral<T : ExpressibleByIntegerLiteral>(x: T) {
var x = x
// CHECK: [[TCONV:%.*]] = witness_method $T, #ExpressibleByIntegerLiteral.init!allocator.1
// CHECK: [[ADDR:%.*]] = alloc_stack $T
// CHECK: [[TMETA:%.*]] = metatype $@thick T.Type
// CHECK: [[BUILTINCONV:%.*]] = witness_method $T.IntegerLiteralType, #_ExpressibleByBuiltinIntegerLiteral.init!allocator.1
// CHECK: [[LITVAR:%.*]] = alloc_stack $T.IntegerLiteralType
// CHECK: [[LITMETA:%.*]] = metatype $@thick T.IntegerLiteralType.Type
// CHECK: [[INTLIT:%.*]] = integer_literal $Builtin.Int2048, 17
// CHECK: [[LIT:%.*]] = apply [[BUILTINCONV]]<T.IntegerLiteralType>([[LITVAR]], [[INTLIT]], [[LITMETA]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : _ExpressibleByBuiltinIntegerLiteral> (Builtin.Int2048, @thick τ_0_0.Type) -> @out τ_0_0
// CHECK: apply [[TCONV]]<T>([[ADDR]], [[LITVAR]], [[TMETA]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : ExpressibleByIntegerLiteral> (@in τ_0_0.IntegerLiteralType, @thick τ_0_0.Type) -> @out τ_0_0
x = 17
}
// CHECK-LABEL: sil hidden @_T016generic_literals0A15FloatingLiteral{{[_0-9a-zA-Z]*}}F
func genericFloatingLiteral<T : ExpressibleByFloatLiteral>(x: T) {
var x = x
// CHECK: [[CONV:%.*]] = witness_method $T, #ExpressibleByFloatLiteral.init!allocator.1
// CHECK: [[TVAL:%.*]] = alloc_stack $T
// CHECK: [[TMETA:%.*]] = metatype $@thick T.Type
// CHECK: [[BUILTIN_CONV:%.*]] = witness_method $T.FloatLiteralType, #_ExpressibleByBuiltinFloatLiteral.init!allocator.1
// CHECK: [[FLT_VAL:%.*]] = alloc_stack $T.FloatLiteralType
// CHECK: [[TFLT_META:%.*]] = metatype $@thick T.FloatLiteralType.Type
// CHECK: [[LIT_VALUE:%.*]] = float_literal $Builtin.FPIEEE{{64|80}}, {{0x4004000000000000|0x4000A000000000000000}}
// CHECK: apply [[BUILTIN_CONV]]<T.FloatLiteralType>([[FLT_VAL]], [[LIT_VALUE]], [[TFLT_META]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : _ExpressibleByBuiltinFloatLiteral> (Builtin.FPIEEE{{64|80}}, @thick τ_0_0.Type) -> @out τ_0_0
// CHECK: apply [[CONV]]<T>([[TVAL]], [[FLT_VAL]], [[TMETA]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : ExpressibleByFloatLiteral> (@in τ_0_0.FloatLiteralType, @thick τ_0_0.Type) -> @out τ_0_0
x = 2.5
}
| apache-2.0 | 73daf1cb71f2eb8f0c8bc73999bac80c | 72.818182 | 246 | 0.667488 | 3.373961 | false | false | false | false |
abunur/quran-ios | Quran/QuranTranslationAyahSectionDataSource.swift | 1 | 3921 | //
// QuranTranslationAyahSectionDataSource.swift
// Quran
//
// Created by Mohamed Afifi on 4/4/17.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import GenericDataSources
class QuranTranslationAyahSectionDataSource: CompositeDataSource {
private static let numberFormatter = NumberFormatter()
let ayah: AyahNumber
var highlightType: QuranHighlightType?
init(ayah: AyahNumber) {
self.ayah = ayah
super.init(sectionType: .single)
}
func add(verse: TranslationVerseLayout, index: Int, hasSeparator: Bool) {
// if start of page or a new sura
if index == 0 || verse.ayah.ayah == 1 {
let sura = QuranTranslationSuraDataSource()
sura.items = [Quran.nameForSura(verse.ayah.sura, withPrefix: true)]
add(sura)
}
// add prefixes
if !verse.arabicPrefixLayouts.isEmpty {
let prefix = QuranTranslationArabicTextDataSource()
prefix.items = verse.arabicPrefixLayouts
add(prefix)
}
// add the verse number
let formatter = QuranTranslationAyahSectionDataSource.numberFormatter
let number = QuranTranslationVerseNumberDataSource()
number.items = ["\(formatter.format(verse.ayah.sura)):\(formatter.format(verse.ayah.ayah))"]
add(number)
let arabic = QuranTranslationArabicTextDataSource()
arabic.items = [verse.arabicTextLayout]
add(arabic)
for translationText in verse.translationLayouts {
if verse.translationLayouts.count > 1 {
let name = QuranTranslationTranslatorNameTextDataSource()
name.items = [translationText]
add(name)
}
if translationText.longTextLayout != nil {
let translation = QuranTranslationLongTextDataSource()
translation.items = [translationText]
add(translation)
} else {
let translation = QuranTranslationTextDataSource()
translation.items = [translationText]
add(translation)
}
}
// add prefixes suffixes
if !verse.arabicSuffixLayouts.isEmpty {
let suffix = QuranTranslationArabicTextDataSource()
suffix.items = verse.arabicSuffixLayouts
add(suffix)
}
// add separator only if next verse is not a start of a new sura
if hasSeparator {
let separator = QuranTranslationVerseSeparatorDataSource()
separator.items = [()]
add(separator)
}
}
override func ds_collectionView(_ collectionView: GeneralCollectionView, cellForItemAt indexPath: IndexPath) -> ReusableCell {
let cell = super.ds_collectionView(collectionView, cellForItemAt: indexPath)
if let cell = cell as? QuranTranslationBaseCollectionViewCell {
cell.ayah = ayah
cell.backgroundColor = highlightType?.color
}
return cell
}
override func ds_collectionView(_ collectionView: GeneralCollectionView, willDisplay cell: ReusableCell, forItemAt indexPath: IndexPath) {
if let cell = cell as? QuranTranslationBaseCollectionViewCell {
cell.ayah = ayah
cell.backgroundColor = highlightType?.color
}
}
}
| gpl-3.0 | 1081ddf57d873e6cbff8ea96ec7e01f5 | 34.645455 | 142 | 0.647539 | 5.007663 | false | false | false | false |
erichoracek/Carthage | Source/carthage/Environment.swift | 2 | 987 | //
// Environment.swift
// Carthage
//
// Created by J.D. Healy on 2/6/15.
// Copyright (c) 2015 Carthage. All rights reserved.
//
import CarthageKit
import Foundation
import Result
internal func getEnvironmentVariable(variable: String) -> Result<String, CarthageError> {
let environment = NSProcessInfo.processInfo().environment
if let value = environment[variable] as? String {
return .success(value)
} else {
return .failure(CarthageError.MissingEnvironmentVariable(variable: variable))
}
}
/// Information about the possible parent terminal.
internal struct Terminal {
/// Terminal type retrieved from `TERM` environment variable.
static var terminalType: String? {
return getEnvironmentVariable("TERM").value
}
/// Whether terminal type is `dumb`.
static var isDumb: Bool {
return (terminalType?.caseInsensitiveCompare("dumb") == .OrderedSame) ?? false
}
/// Whether STDOUT is a TTY.
static var isTTY: Bool {
return isatty(STDOUT_FILENO) != 0
}
}
| mit | f6780ccc3070bc3fc8b75385a6703b26 | 24.307692 | 89 | 0.729483 | 3.724528 | false | false | false | false |
salavert/vainglory-api | VaingloryAPI/Resources/RosterResource.swift | 1 | 1325 | //
// RosterResource.swift
// Pods
//
// Created by Jose Salavert on 26/03/2017.
//
//
import Foundation
import Mapper
import Treasure
public struct RosterResource: Resource {
public let id: String
public let type: String
public let acesEarned: Int?
public let gold: Int?
public let heroKills: Int?
public let krakenCaptures: Int?
public let side: String?
public let turretKills: Int?
public let turretsRemaining: Int?
public let participants: [ParticipantResource]?
public init(map: Mapper) throws {
id = try map.from(Key.id)
type = try map.from(Key.type)
acesEarned = try? map.from(Key.attributes("stats.acesEarned"))
gold = try? map.from(Key.attributes("stats.gold"))
heroKills = try? map.from(Key.attributes("stats.heroKills"))
krakenCaptures = try? map.from(Key.attributes("stats.krakenCaptures"))
side = try? map.from(Key.attributes("stats.side"))
turretKills = try? map.from(Key.attributes("stats.turretKills"))
turretsRemaining = try? map.from(Key.attributes("stats.turretsRemaining"))
let participantsRelationship: ToManyRelationship? = try? map.from(Key.relationships("participants"))
participants = try? map.from(participantsRelationship)
}
}
| mit | b55c795548fb38bb47c033a2fa427ccc | 29.813953 | 108 | 0.667925 | 3.88563 | false | false | false | false |
naturaln0va/Doodler_iOS | UIImage+Addtions.swift | 1 | 2625 |
import UIKit
extension UIImage {
func imageByTintingWithColor(color: UIColor) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
color.setFill()
let bounds = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIRectFill(bounds)
draw(in: bounds, blendMode: .destinationIn, alpha: 1)
let tintedImage = UIGraphicsGetImageFromCurrentImageContext()
return tintedImage
}
func color(at position: CGPoint) -> UIColor? {
guard let cgImage = cgImage else { return nil }
let width = Int(size.width)
let height = Int(size.height)
let adjustedRGBABitmapContext = CGContext(
data: nil,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: width * 4,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
)
guard let adjustedImageRef = adjustedRGBABitmapContext else {
return nil
}
adjustedImageRef.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))
let pixelData = adjustedImageRef.makeImage()?.dataProvider?.data ?? Data() as CFData
let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
let pixelInfo: Int = ((Int(width) * Int(position.y)) + Int(position.x)) * 4
let r = CGFloat(data[pixelInfo + 0]) / 255
let g = CGFloat(data[pixelInfo + 1]) / 255
let b = CGFloat(data[pixelInfo + 2]) / 255
let a = CGFloat(data[pixelInfo + 3]) / 255
if a == 0 { return nil }
return UIColor(red: r, green: g, blue: b, alpha: a)
}
func scale(toSize size: CGSize) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, 1)
draw(in: CGRect(origin: .zero, size: size))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
var verticallyFlipped: UIImage? {
guard let cgImage = cgImage else { return nil }
let img = UIImage(cgImage: cgImage, scale: 1, orientation: .downMirrored)
guard let imgRef = img.cgImage else { return nil }
UIGraphicsBeginImageContext(CGSize(width: imgRef.width, height: imgRef.height))
img.draw(at: .zero)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
| mit | 34a1534e2c862d9ebcd807457d61276a | 33.090909 | 92 | 0.59581 | 4.888268 | false | false | false | false |
Sherlouk/monzo-vapor | Tests/MonzoTests/WebhookTests.swift | 1 | 2328 | import XCTest
@testable import Monzo
class WebhookTests: XCTestCase {
func testListWebhooks() {
let client = MonzoClient(publicKey: "", privateKey: "", httpClient: MockResponder())
let user = client.createUser(userId: "", accessToken: "", refreshToken: nil)
guard let account = (try? user.accounts())?.first else { XCTFail(); return }
let webhooks = account.webhooks
XCTAssertEqual(webhooks.count, 1)
XCTAssertEqual(webhooks.first!.id, "webhook_1")
XCTAssertEqual(webhooks.first!.url.absoluteString, "https://monzo.com")
XCTAssertEqual(webhooks.first!.account.id, "account_1")
}
func testAddWebhook() {
let client = MonzoClient(publicKey: "", privateKey: "", httpClient: MockResponder())
let user = client.createUser(userId: "", accessToken: "", refreshToken: nil)
guard let account = (try? user.accounts())?.first else { XCTFail(); return }
XCTAssertEqual(account.webhooks.count, 1)
try? account.addWebhook(url: URL(string: "http://example.com")!)
XCTAssertEqual(account.webhooks.count, 2)
XCTAssertEqual(account.webhooks.last!.id, "webhook_2")
XCTAssertEqual(account.webhooks.last!.url.absoluteString, "http://example.com")
XCTAssertEqual(account.webhooks.last!.account.id, "account_1")
}
func testRemoveWebhook() {
let client = MonzoClient(publicKey: "", privateKey: "", httpClient: MockResponder())
let user = client.createUser(userId: "", accessToken: "", refreshToken: nil)
guard let account = (try? user.accounts())?.first else { XCTFail(); return }
XCTAssertEqual(account.webhooks.count, 1)
try? account.addWebhook(url: URL(string: "http://example.com")!)
XCTAssertEqual(account.webhooks.count, 2)
XCTAssertEqual(account.webhooks.first!.id, "webhook_1")
XCTAssertEqual(account.webhooks.last!.id, "webhook_2")
try? account.webhooks.last?.remove()
XCTAssertEqual(account.webhooks.count, 1)
XCTAssertEqual(account.webhooks.first!.id, "webhook_1")
}
static var allTests = [
("testListWebhooks", testListWebhooks),
("testAddWebhook", testAddWebhook),
("testRemoveWebhook", testRemoveWebhook),
]
}
| mit | ccaf85bc4c57dde34255f135616c2e5f | 44.647059 | 92 | 0.648625 | 4.319109 | false | true | false | false |
clwm01/RTKitDemo | RCToolsDemo/RCToolsDemo/AnimationTableViewController.swift | 2 | 2578 | //
// AnimationTableViewController.swift
// RCToolsDemo
//
// Created by Rex Tsao on 19/4/2016.
// Copyright © 2016 rexcao. All rights reserved.
//
import UIKit
class AnimationTableViewController: UITableViewController {
let actions = ["circle", "gravity", "attachment", "snap", "push", "catScroll", "chart"]
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Animation"
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "animationCell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func pushVC(index: Int) {
if index == 0 {
self.navigationController?.pushViewController(AnimationCircleViewController(), animated: true)
} else if index == 1 {
self.navigationController?.pushViewController(GravityViewController(), animated: true)
} else if index == 2 {
self.navigationController?.pushViewController(AttachmentViewController(), animated: true)
} else if index == 3 {
self.navigationController?.pushViewController(SnapViewController(), animated: true)
} else if index == 4 {
self.navigationController?.pushViewController(PushViewController(), animated: true)
} else if index == 5 {
self.navigationController?.pushViewController(ScrollCatViewController(), animated: true)
} else if index == 6 {
self.navigationController?.pushViewController(ChartViewController(), animated: true)
}
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return self.actions.count
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.pushVC(indexPath.row)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("animationCell")! as UITableViewCell
cell.textLabel?.text = self.actions[indexPath.row]
return cell
}
}
| mit | 3dd302572aba2e8640c22dcff787d9c4 | 38.045455 | 118 | 0.681801 | 5.436709 | false | false | false | false |
EstebanVallejo/sdk-ios | MercadoPagoSDK/MercadoPagoSDK/PayerCost.swift | 2 | 2397 | //
// PayerCost.swift
// MercadoPagoSDK
//
// Created by Matias Gualino on 28/12/14.
// Copyright (c) 2014 com.mercadopago. All rights reserved.
//
import Foundation
public class PayerCost : NSObject {
public var installments : Int = 0
public var installmentRate : Double = 0
public var labels : [String]!
public var minAllowedAmount : Double = 0
public var maxAllowedAmount : Double = 0
public var recommendedMessage : String!
public var installmentAmount : Double = 0
public var totalAmount : Double = 0
public init (installments : Int, installmentRate : Double, labels : [String],
minAllowedAmount : Double, maxAllowedAmount : Double, recommendedMessage: String!, installmentAmount: Double, totalAmount: Double) {
super.init()
self.installments = installments
self.installmentRate = installmentRate
self.labels = labels
self.minAllowedAmount = minAllowedAmount
self.maxAllowedAmount = maxAllowedAmount
self.recommendedMessage = recommendedMessage
self.installmentAmount = installmentAmount
self.totalAmount = totalAmount
}
public override init() {
super.init()
}
public class func fromJSON(json : NSDictionary) -> PayerCost {
var payerCost : PayerCost = PayerCost()
if json["installments"] != nil && !(json["installments"]! is NSNull) {
payerCost.installments = JSON(json["installments"]!).asInt!
}
if json["installment_rate"] != nil && !(json["installment_rate"]! is NSNull) {
payerCost.installmentRate = JSON(json["installment_rate"]!).asDouble!
}
if json["min_allowed_amount"] != nil && !(json["min_allowed_amount"]! is NSNull) {
payerCost.minAllowedAmount = JSON(json["min_allowed_amount"]!).asDouble!
}
if json["max_allowed_amount"] != nil && !(json["max_allowed_amount"]! is NSNull) {
payerCost.maxAllowedAmount = JSON(json["max_allowed_amount"]!).asDouble!
}
if json["installment_amount"] != nil && !(json["installment_amount"]! is NSNull) {
payerCost.installmentAmount = JSON(json["installment_amount"]!).asDouble!
}
if json["total_amount"] != nil && !(json["total_amount"]! is NSNull) {
payerCost.totalAmount = JSON(json["total_amount"]!).asDouble!
}
payerCost.recommendedMessage = JSON(json["recommended_message"]!).asString
return payerCost
}
} | mit | bbfcb61c2bc8f493e0cb174018ed3ab5 | 38.311475 | 140 | 0.672507 | 4.015075 | false | false | false | false |
benlangmuir/swift | test/Compatibility/exhaustive_switch.swift | 4 | 30910 | // RUN: %target-typecheck-verify-swift -swift-version 4 -enable-library-evolution
func foo(a: Int?, b: Int?) -> Int {
switch (a, b) {
case (.none, _): return 1
case (_, .none): return 2
case (.some(_), .some(_)): return 3
}
switch (a, b) {
case (.none, _): return 1
case (_, .none): return 2
case (_?, _?): return 3
}
switch Optional<(Int?, Int?)>.some((a, b)) {
case .none: return 1
case let (_, x?)?: return x
case let (x?, _)?: return x
case (.none, .none)?: return 0
}
}
func bar(a: Bool, b: Bool) -> Int {
switch (a, b) {
case (false, false):
return 1
case (true, _):
return 2
case (false, true):
return 3
}
}
enum Result<T> {
case Ok(T)
case Error(Error)
func shouldWork<U>(other: Result<U>) -> Int {
switch (self, other) { // No warning
case (.Ok, .Ok): return 1
case (.Error, .Error): return 2
case (.Error, _): return 3
case (_, .Error): return 4
}
}
}
enum Foo {
case A(Int)
case B(Int)
}
func foo() {
switch (Foo.A(1), Foo.B(1)) {
case (.A(_), .A(_)):
()
case (.B(_), _):
()
case (_, .B(_)):
()
}
switch (Foo.A(1), Optional<(Int, Int)>.some((0, 0))) {
case (.A(_), _):
break
case (.B(_), (let q, _)?):
print(q)
case (.B(_), nil):
break
}
}
class C {}
enum Bar {
case TheCase(C?)
}
func test(f: Bar) -> Bool {
switch f {
case .TheCase(_?):
return true
case .TheCase(nil):
return false
}
}
func op(this : Optional<Bool>, other : Optional<Bool>) -> Optional<Bool> {
switch (this, other) { // No warning
case let (.none, w):
return w
case let (w, .none):
return w
case let (.some(e1), .some(e2)):
return .some(e1 && e2)
}
}
enum Threepeat {
case a, b, c
}
func test3(x: Threepeat, y: Threepeat) {
switch (x, y) { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{add missing case: '(.a, .c)'}}
case (.a, .a):
()
case (.b, _):
()
case (.c, _):
()
case (_, .b):
()
}
}
enum A {
case A(Int)
case B(Bool)
case C
case D
}
enum B {
case A
case B
}
func s(a: A, b: B) {
switch (a, b) {
case (.A(_), .A):
break
case (.A(_), .B):
break
case (.B(_), let b):
// expected-warning@-1 {{immutable value 'b' was never used; consider replacing with '_' or removing it}}
break
case (.C, _), (.D, _):
break
}
}
enum Grimble {
case A
case B
case C
}
enum Gromble {
case D
case E
}
func doSomething(foo:Grimble, bar:Gromble) {
switch(foo, bar) { // No warning
case (.A, .D):
break
case (.A, .E):
break
case (.B, _):
break
case (.C, _):
break
}
}
enum E {
case A
case B
}
func f(l: E, r: E) {
switch (l, r) {
case (.A, .A):
return
case (.A, _):
return
case (_, .A):
return
case (.B, .B):
return
}
}
enum TestEnum {
case A, B
}
func switchOverEnum(testEnumTuple: (TestEnum, TestEnum)) {
switch testEnumTuple {
case (_,.B):
// Matches (.A, .B) and (.B, .B)
break
case (.A,_):
// Matches (.A, .A)
// Would also match (.A, .B) but first case takes precedent
break
case (.B,.A):
// Matches (.B, .A)
break
}
}
func tests(a: Int?, b: String?) {
switch (a, b) {
case let (.some(n), _): print("a: ", n, "?")
case (.none, _): print("Nothing", "?")
}
switch (a, b) {
case let (.some(n), .some(s)): print("a: ", n, "b: ", s)
case let (.some(n), .none): print("a: ", n, "Nothing")
case (.none, _): print("Nothing")
}
switch (a, b) {
case let (.some(n), .some(s)): print("a: ", n, "b: ", s)
case let (.some(n), .none): print("a: ", n, "Nothing")
case let (.none, .some(s)): print("Nothing", "b: ", s)
case (.none, _): print("Nothing", "?")
}
switch (a, b) {
case let (.some(n), .some(s)): print("a: ", n, "b: ", s)
case let (.some(n), .none): print("a: ", n, "Nothing")
case let (.none, .some(s)): print("Nothing", "b: ", s)
case (.none, .none): print("Nothing", "Nothing")
}
}
enum X {
case Empty
case A(Int)
case B(Int)
}
func f(a: X, b: X) {
switch (a, b) {
case (_, .Empty): ()
case (.Empty, _): ()
case (.A, .A): ()
case (.B, .B): ()
case (.A, .B): ()
case (.B, .A): ()
}
}
func f2(a: X, b: X) {
switch (a, b) {
case (.A, .A): ()
case (.B, .B): ()
case (.A, .B): ()
case (.B, .A): ()
case (_, .Empty): ()
case (.Empty, _): ()
case (.A, .A): () // expected-warning {{case is already handled by previous patterns; consider removing it}}
case (.B, .B): () // expected-warning {{case is already handled by previous patterns; consider removing it}}
case (.A, .B): () // expected-warning {{case is already handled by previous patterns; consider removing it}}
case (.B, .A): () // expected-warning {{case is already handled by previous patterns; consider removing it}}
default: ()
}
}
enum XX : Int {
case A
case B
case C
case D
case E
}
func switcheroo(a: XX, b: XX) -> Int {
switch(a, b) { // No warning
case (.A, _) : return 1
case (_, .A) : return 2
case (.C, _) : return 3
case (_, .C) : return 4
case (.B, .B) : return 5
case (.B, .D) : return 6
case (.D, .B) : return 7
case (.B, .E) : return 8
case (.E, .B) : return 9
case (.E, _) : return 10
case (_, .E) : return 11
case (.D, .D) : return 12
default:
print("never hits this:", a, b)
return 13
}
}
enum PatternCasts {
case one(Any)
case two
}
func checkPatternCasts() {
// Pattern casts with this structure shouldn't warn about duplicate cases.
let x: PatternCasts = .one("One")
switch x {
case .one(let s as String): print(s)
case .one: break
case .two: break
}
// But should warn here.
switch x {
case .one(_): print(s)
case .one: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
case .two: break
}
}
enum MyNever {}
func ~= (_ : MyNever, _ : MyNever) -> Bool { return true }
func myFatalError() -> MyNever { fatalError() }
func checkUninhabited() {
// Scrutinees of uninhabited type may match any number and kind of patterns
// that Sema is willing to accept at will. After all, it's quite a feat to
// productively inhabit the type of crashing programs.
func test1(x : Never) {
switch x {} // No diagnostic.
}
func test2(x : Never) {
switch (x, x) {} // No diagnostic.
}
func test3(x : MyNever) {
switch x { // No diagnostic.
case myFatalError(): break
case myFatalError(): break
case myFatalError(): break
}
}
}
enum Runcible {
case spoon
case hat
case fork
}
func checkDiagnosticMinimality(x: Runcible?) {
switch (x!, x!) { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{add missing case: '(.fork, _)'}}
// expected-note@-2 {{add missing case: '(.hat, .hat)'}}
// expected-note@-3 {{add missing case: '(_, .fork)'}}
case (.spoon, .spoon):
break
case (.spoon, .hat):
break
case (.hat, .spoon):
break
}
switch (x!, x!) { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{add missing case: '(.fork, _)'}}
// expected-note@-2 {{add missing case: '(.hat, .spoon)'}}
// expected-note@-3 {{add missing case: '(.spoon, .hat)'}}
// expected-note@-4 {{add missing case: '(_, .fork)'}}
case (.spoon, .spoon):
break
case (.hat, .hat):
break
}
}
enum LargeSpaceEnum {
case case0
case case1
case case2
case case3
case case4
case case5
case case6
case case7
case case8
case case9
case case10
}
func notQuiteBigEnough() -> Bool {
switch (LargeSpaceEnum.case1, LargeSpaceEnum.case2) { // expected-error {{switch must be exhaustive}}
// expected-note@-1 110 {{add missing case:}}
case (.case0, .case0): return true
case (.case1, .case1): return true
case (.case2, .case2): return true
case (.case3, .case3): return true
case (.case4, .case4): return true
case (.case5, .case5): return true
case (.case6, .case6): return true
case (.case7, .case7): return true
case (.case8, .case8): return true
case (.case9, .case9): return true
case (.case10, .case10): return true
}
}
enum OverlyLargeSpaceEnum {
case case0
case case1
case case2
case case3
case case4
case case5
case case6
case case7
case case8
case case9
case case10
case case11
}
enum ContainsOverlyLargeEnum {
case one(OverlyLargeSpaceEnum)
case two(OverlyLargeSpaceEnum)
case three(OverlyLargeSpaceEnum, OverlyLargeSpaceEnum)
}
func quiteBigEnough() -> Bool {
switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) { // expected-error {{switch must be exhaustive}}
// expected-note@-1 132 {{add missing case:}}
case (.case0, .case0): return true
case (.case1, .case1): return true
case (.case2, .case2): return true
case (.case3, .case3): return true
case (.case4, .case4): return true
case (.case5, .case5): return true
case (.case6, .case6): return true
case (.case7, .case7): return true
case (.case8, .case8): return true
case (.case9, .case9): return true
case (.case10, .case10): return true
case (.case11, .case11): return true
}
switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{add missing case: '(.case11, _)'}}
case (.case0, _): return true
case (.case1, _): return true
case (.case2, _): return true
case (.case3, _): return true
case (.case4, _): return true
case (.case5, _): return true
case (.case6, _): return true
case (.case7, _): return true
case (.case8, _): return true
case (.case9, _): return true
case (.case10, _): return true
}
switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) { // expected-warning {{switch must be exhaustive}}
// expected-note@-1 {{add missing case: '(.case11, _)'}}
case (.case0, _): return true
case (.case1, _): return true
case (.case2, _): return true
case (.case3, _): return true
case (.case4, _): return true
case (.case5, _): return true
case (.case6, _): return true
case (.case7, _): return true
case (.case8, _): return true
case (.case9, _): return true
case (.case10, _): return true
@unknown default: return false
}
// No diagnostic
switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) {
case (.case0, _): return true
case (.case1, _): return true
case (.case2, _): return true
case (.case3, _): return true
case (.case4, _): return true
case (.case5, _): return true
case (.case6, _): return true
case (.case7, _): return true
case (.case8, _): return true
case (.case9, _): return true
case (.case10, _): return true
case (.case11, _): return true
}
// No diagnostic
switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) {
case (_, .case0): return true
case (_, .case1): return true
case (_, .case2): return true
case (_, .case3): return true
case (_, .case4): return true
case (_, .case5): return true
case (_, .case6): return true
case (_, .case7): return true
case (_, .case8): return true
case (_, .case9): return true
case (_, .case10): return true
case (_, .case11): return true
}
// No diagnostic
switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) {
case (_, _): return true
}
// No diagnostic
switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) {
case (.case0, .case0): return true
case (.case1, .case1): return true
case (.case2, .case2): return true
case (.case3, .case3): return true
case _: return true
}
// No diagnostic
switch ContainsOverlyLargeEnum.one(.case0) {
case .one: return true
case .two: return true
case .three: return true
}
// Make sure we haven't just stopped emitting diagnostics.
switch OverlyLargeSpaceEnum.case1 { // expected-error {{switch must be exhaustive}} expected-note 12 {{add missing case}}
}
}
indirect enum InfinitelySized {
case one
case two
case recur(InfinitelySized)
case mutualRecur(MutuallyRecursive, InfinitelySized)
}
indirect enum MutuallyRecursive {
case one
case two
case recur(MutuallyRecursive)
case mutualRecur(InfinitelySized, MutuallyRecursive)
}
func infinitelySized() -> Bool {
switch (InfinitelySized.one, InfinitelySized.one) { // expected-error {{switch must be exhaustive}}
// expected-note@-1 8 {{add missing case:}}
case (.one, .one): return true
case (.two, .two): return true
}
switch (MutuallyRecursive.one, MutuallyRecursive.one) { // expected-error {{switch must be exhaustive}}
// expected-note@-1 8 {{add missing case:}}
case (.one, .one): return true
case (.two, .two): return true
}
}
func diagnoseDuplicateLiterals() {
let str = "def"
let int = 2
let dbl = 2.5
// No Diagnostics
switch str {
case "abc": break
case "def": break
case "ghi": break
default: break
}
switch str {
case "abc": break
case "def": break // expected-note {{first occurrence of identical literal pattern is here}}
case "def": break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case "ghi": break
default: break
}
switch str {
case "abc", "def": break // expected-note 2 {{first occurrence of identical literal pattern is here}}
case "ghi", "jkl": break
case "abc", "def": break // expected-warning 2 {{literal value is already handled by previous pattern; consider removing it}}
default: break
}
switch str {
case "xyz": break // expected-note {{first occurrence of identical literal pattern is here}}
case "ghi": break
case "def": break
case "abc": break
case "xyz": break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
default: break
}
func someStr() -> String { return "sdlkj" }
let otherStr = "ifnvbnwe"
switch str {
case "sdlkj": break
case "ghi": break // expected-note {{first occurrence of identical literal pattern is here}}
case someStr(): break
case "def": break
case otherStr: break
case "xyz": break // expected-note {{first occurrence of identical literal pattern is here}}
case "ifnvbnwe": break
case "ghi": break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case "xyz": break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
default: break
}
// No Diagnostics
switch int {
case -2: break
case -1: break
case 0: break
case 1: break
case 2: break
case 3: break
default: break
}
switch int {
case -2: break // expected-note {{first occurrence of identical literal pattern is here}}
case -2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 1: break
case 2: break // expected-note {{first occurrence of identical literal pattern is here}}
case 2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 3: break
default: break
}
switch int {
case -2, -2: break // expected-note {{first occurrence of identical literal pattern is here}} expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 1, 2: break // expected-note 3 {{first occurrence of identical literal pattern is here}}
case 2, 3: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 1, 2: break // expected-warning 2 {{literal value is already handled by previous pattern; consider removing it}}
case 4, 5: break
case 7, 7: break // expected-note {{first occurrence of identical literal pattern is here}}
// expected-warning@-1 {{literal value is already handled by previous pattern; consider removing it}}
default: break
}
switch int {
case 1: break // expected-note {{first occurrence of identical literal pattern is here}}
case 2: break // expected-note 2 {{first occurrence of identical literal pattern is here}}
case 3: break
case 17: break // expected-note {{first occurrence of identical literal pattern is here}}
case 4: break
case 2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 001: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 5: break
case 0x11: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 0b10: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
default: break
}
switch int {
case 10: break
case 0b10: break // expected-note {{first occurrence of identical literal pattern is here}}
case -0b10: break // expected-note {{first occurrence of identical literal pattern is here}}
case 3000: break
case 0x12: break // expected-note {{first occurrence of identical literal pattern is here}}
case 400: break
case 2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case -2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 18: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
default: break
}
func someInt() -> Int { return 0x1234 }
let otherInt = 13254
switch int {
case 13254: break
case 3000: break
case 00000002: break // expected-note {{first occurrence of identical literal pattern is here}}
case 0x1234: break
case someInt(): break
case 400: break
case 2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 18: break
case otherInt: break
case 230: break
default: break
}
// No Diagnostics
switch dbl {
case -3.5: break
case -2.5: break
case -1.5: break
case 1.5: break
case 2.5: break
case 3.5: break
default: break
}
switch dbl {
case -3.5: break
case -2.5: break // expected-note {{first occurrence of identical literal pattern is here}}
case -2.5: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case -1.5: break
case 1.5: break
case 2.5: break // expected-note {{first occurrence of identical literal pattern is here}}
case 2.5: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 3.5: break
default: break
}
switch dbl {
case 1.5, 4.5, 7.5, 6.9: break // expected-note 2 {{first occurrence of identical literal pattern is here}}
case 3.4, 1.5: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 7.5, 2.3: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
default: break
}
switch dbl {
case 1: break
case 1.5: break // expected-note 2 {{first occurrence of identical literal pattern is here}}
case 2.5: break
case 3.5: break // expected-note {{first occurrence of identical literal pattern is here}}
case 5.3132: break
case 1.500: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 46.2395: break
case 1.5000: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 0003.50000: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 23452.43: break
default: break
}
func someDouble() -> Double { return 324.4523 }
let otherDouble = 458.2345
switch dbl {
case 1: break // expected-note {{first occurrence of identical literal pattern is here}}
case 1.5: break
case 2.5: break
case 3.5: break // expected-note {{first occurrence of identical literal pattern is here}}
case 5.3132: break
case 46.2395: break
case someDouble(): break
case 0003.50000: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case otherDouble: break
case 2.50505: break // expected-note {{first occurrence of identical literal pattern is here}}
case 23452.43: break
case 00001: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 123453: break
case 2.50505000000: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
default: break
}
}
func checkLiteralTuples() {
let str1 = "abc"
let str2 = "def"
let int1 = 23
let int2 = 7
let dbl1 = 4.23
let dbl2 = 23.45
// No Diagnostics
switch (str1, str2) {
case ("abc", "def"): break
case ("def", "ghi"): break
case ("ghi", "def"): break
case ("abc", "def"): break // We currently don't catch this
default: break
}
// No Diagnostics
switch (int1, int2) {
case (94, 23): break
case (7, 23): break
case (94, 23): break // We currently don't catch this
case (23, 7): break
default: break
}
// No Diagnostics
switch (dbl1, dbl2) {
case (543.21, 123.45): break
case (543.21, 123.45): break // We currently don't catch this
case (23.45, 4.23): break
case (4.23, 23.45): break
default: break
}
}
// https://github.com/apple/swift/issues/49523
do {
enum E {
case a, b
}
let e = E.b
switch e {
case .a as E: // expected-warning {{'as' test is always true}}
print("a")
case .b: // Valid!
print("b")
case .a: // expected-warning {{case is already handled by previous patterns; consider removing it}}
print("second a")
}
}
public enum NonExhaustive {
case a, b
}
public enum NonExhaustivePayload {
case a(Int), b(Bool)
}
@frozen public enum TemporalProxy {
case seconds(Int)
case milliseconds(Int)
case microseconds(Int)
case nanoseconds(Int)
case never
}
// Inlinable code is considered "outside" the module and must include a default
// case.
@inlinable
public func testNonExhaustive(_ value: NonExhaustive, _ payload: NonExhaustivePayload, for interval: TemporalProxy, flag: Bool) {
switch value { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b'}} {{none}}
case .a: break
}
switch value { // no-warning
case .a: break
case .b: break
}
switch value {
case .a: break
case .b: break
default: break // no-warning
}
switch value {
case .a: break
case .b: break
@unknown case _: break // no-warning
}
switch value { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b'}} {{none}}
case .a: break
@unknown case _: break
}
switch value { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.a'}} {{none}} expected-note {{add missing case: '.b'}} {{none}}
@unknown case _: break
}
switch value {
case _: break
@unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
}
// Test being part of other spaces.
switch value as Optional { // no-warning
case .a?: break
case .b?: break
case nil: break
}
switch value as Optional {
case _?: break
case nil: break
} // no-warning
switch value as Optional {
case .a?: break
case .b?: break
case nil: break
@unknown case _: break
} // no-warning
switch (value, flag) { // no-warning
case (.a, _): break
case (.b, false): break
case (_, true): break
}
switch (value, flag) {
case (.a, _): break
case (.b, false): break
case (_, true): break
@unknown case _: break
} // no-warning
switch (flag, value) { // no-warning
case (_, .a): break
case (false, .b): break
case (true, _): break
}
switch (flag, value) {
case (_, .a): break
case (false, .b): break
case (true, _): break
@unknown case _: break
} // no-warning
switch (value, value) { // no-warning
case (.a, _), (_, .a): break
case (.b, _), (_, .b): break
}
switch (value, value) {
case (.a, _), (_, .a): break
case (.b, _), (_, .b): break
@unknown case _: break
} // no-warning
// Test payloaded enums.
switch payload { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(_)'}} {{none}}
case .a: break
}
switch payload { // no-warning
case .a: break
case .b: break
}
switch payload {
case .a: break
case .b: break
default: break // no-warning
}
switch payload {
case .a: break
case .b: break
@unknown case _: break // no-warning
}
switch payload { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(_)'}} {{none}}
case .a: break
@unknown case _: break
}
switch payload { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(true)'}} {{none}}
case .a: break
case .b(false): break
}
switch payload { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(true)'}} {{none}}
case .a: break
case .b(false): break
@unknown case _: break
}
// Test fully-covered switches.
switch interval {
case .seconds, .milliseconds, .microseconds, .nanoseconds: break
case .never: break
@unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
}
switch flag {
case true: break
case false: break
@unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
}
switch flag as Optional {
case _?: break
case nil: break
@unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
}
switch (flag, value) {
case (true, _): break
case (false, _): break
@unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
}
}
public func testNonExhaustiveWithinModule(_ value: NonExhaustive, _ payload: NonExhaustivePayload, flag: Bool) {
switch value { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b'}}
case .a: break
}
switch value { // no-warning
case .a: break
case .b: break
}
switch value {
case .a: break
case .b: break
default: break // no-warning
}
switch value {
case .a: break
case .b: break
@unknown case _: break // no-warning
}
switch value { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b'}} {{none}}
case .a: break
@unknown case _: break
}
switch value { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.a'}} {{none}} expected-note {{add missing case: '.b'}} {{none}}
@unknown case _: break
}
switch value {
case _: break
@unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
}
// Test being part of other spaces.
switch value as Optional { // no-warning
case .a?: break
case .b?: break
case nil: break
}
switch value as Optional {
case _?: break
case nil: break
} // no-warning
switch (value, flag) { // no-warning
case (.a, _): break
case (.b, false): break
case (_, true): break
}
switch (flag, value) { // no-warning
case (_, .a): break
case (false, .b): break
case (true, _): break
}
switch (value, value) { // no-warning
case (.a, _): break
case (.b, _): break
case (_, .a): break
case (_, .b): break
}
switch (value, value) { // no-warning
case (.a, _): break
case (.b, _): break
case (_, .a): break
case (_, .b): break
@unknown case _: break
}
// Test payloaded enums.
switch payload { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(_)'}} {{none}}
case .a: break
}
switch payload { // no-warning
case .a: break
case .b: break
}
switch payload {
case .a: break
case .b: break
default: break // no-warning
}
switch payload {
case .a: break
case .b: break
@unknown case _: break // no-warning
}
switch payload { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(_)'}} {{none}}
case .a: break
@unknown case _: break
}
switch payload { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(true)'}} {{none}}
case .a: break
case .b(false): break
}
switch payload { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(true)'}} {{none}}
case .a: break
case .b(false): break
@unknown case _: break
}
}
enum UnavailableCase {
case a
case b
@available(*, unavailable)
case oopsThisWasABadIdea
}
enum UnavailableCaseOSSpecific {
case a
case b
#if canImport(Darwin)
@available(macOS, unavailable)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
case unavailableOnAllTheseApplePlatforms
#else
@available(*, unavailable)
case dummyCaseForOtherPlatforms
#endif
}
enum UnavailableCaseOSIntroduced {
case a
case b
@available(macOS 50, iOS 50, tvOS 50, watchOS 50, *)
case notYetIntroduced
}
func testUnavailableCases(_ x: UnavailableCase, _ y: UnavailableCaseOSSpecific, _ z: UnavailableCaseOSIntroduced) {
switch x {
case .a: break
case .b: break
} // no-error
switch y {
case .a: break
case .b: break
} // no-error
switch z {
case .a: break
case .b: break
case .notYetIntroduced: break
} // no-error
}
// The following test used to behave differently when the uninhabited enum was
// defined in the same module as the function (as opposed to using Swift.Never).
enum NoError {}
extension Result where T == NoError {
func testUninhabited() {
switch self {
case .Error(_):
break
// No .Ok case possible because of the 'NoError'.
}
switch self {
case .Error(_):
break
case .Ok(_):
break // But it's okay to write one.
}
}
}
// https://github.com/apple/swift/issues/52701
do {
enum Enum<T,E> {
case value(T)
case error(E)
}
enum MyError: Error {
case bad
}
let foo: Enum<String, (Int, Error)>
switch foo {
case .value: break
case .error((_, MyError.bad)): break
case .error((_, let err)):
_ = err
break
}
// 'is'
switch foo {
case .value: break
case .error((_, is MyError)): break
case .error((_, let err)):
_ = err
break
}
// 'as'
switch foo {
case .value: break
case .error((_, let err as MyError)):
_ = err
break
case .error((_, let err)):
_ = err
break
}
}
| apache-2.0 | a93f0454062ccae2816dd9fcd3418e7d | 24.336066 | 191 | 0.63342 | 3.590429 | false | false | false | false |
mshhmzh/firefox-ios | Client/Frontend/Home/HomePanels.swift | 3 | 3053 | /* 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
/**
* Data for identifying and constructing a HomePanel.
*/
struct HomePanelDescriptor {
let makeViewController: (profile: Profile) -> UIViewController
let imageName: String
let accessibilityLabel: String
let accessibilityIdentifier: String
}
class HomePanels {
let enabledPanels = [
HomePanelDescriptor(
makeViewController: { profile in
TopSitesPanel(profile: profile)
},
imageName: "TopSites",
accessibilityLabel: NSLocalizedString("Top sites", comment: "Panel accessibility label"),
accessibilityIdentifier: "HomePanels.TopSites"),
HomePanelDescriptor(
makeViewController: { profile in
let bookmarks = BookmarksPanel()
bookmarks.profile = profile
let controller = UINavigationController(rootViewController: bookmarks)
controller.setNavigationBarHidden(true, animated: false)
// this re-enables the native swipe to pop gesture on UINavigationController for embedded, navigation bar-less UINavigationControllers
// don't ask me why it works though, I've tried to find an answer but can't.
// found here, along with many other places:
// http://luugiathuy.com/2013/11/ios7-interactivepopgesturerecognizer-for-uinavigationcontroller-with-hidden-navigation-bar/
controller.interactivePopGestureRecognizer?.delegate = nil
return controller
},
imageName: "Bookmarks",
accessibilityLabel: NSLocalizedString("Bookmarks", comment: "Panel accessibility label"),
accessibilityIdentifier: "HomePanels.Bookmarks"),
HomePanelDescriptor(
makeViewController: { profile in
let history = HistoryPanel()
history.profile = profile
let controller = UINavigationController(rootViewController: history)
controller.setNavigationBarHidden(true, animated: false)
controller.interactivePopGestureRecognizer?.delegate = nil
return controller
},
imageName: "History",
accessibilityLabel: NSLocalizedString("History", comment: "Panel accessibility label"),
accessibilityIdentifier: "HomePanels.History"),
HomePanelDescriptor(
makeViewController: { profile in
let controller = ReadingListPanel()
controller.profile = profile
return controller
},
imageName: "ReadingList",
accessibilityLabel: NSLocalizedString("Reading list", comment: "Panel accessibility label"),
accessibilityIdentifier: "HomePanels.ReadingList"),
]
}
| mpl-2.0 | 38c97d65ff8662fbf897e170a1efdabf | 43.897059 | 150 | 0.644284 | 6.118236 | false | false | false | false |
poisonedslo/CGOverloads | CGOverloads.swift | 1 | 3176 | //
// CGOverloads.swift
//
//
//The MIT License (MIT)
//
//Copyright (c) 2014 Nejc Pintar
//
//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.
//CGPoint
func + (left: CGPoint, right: CGPoint) -> CGPoint
{
return CGPointMake(left.x + right.x, left.y + right.y)
}
func += (inout left: CGPoint, right: CGPoint)
{
left = left + right
}
func - (left: CGPoint, right: CGPoint) -> CGPoint
{
return CGPointMake(left.x - right.x, left.y - right.y)
}
func -= (inout left: CGPoint, right: CGPoint)
{
left = left - right
}
func * (left: CGPoint, right: CGFloat) -> CGPoint
{
return CGPointMake(left.x * right, left.y * right)
}
func * (left: CGFloat, right: CGPoint) -> CGPoint
{
return CGPointMake(right.x * left, right.y * left)
}
func *= (inout left: CGPoint, right: CGFloat)
{
left = left * right
}
func == (left: CGPoint, right: CGPoint) -> Bool
{
return CGPointEqualToPoint(left, right)
}
//CGSize
func + (left: CGSize, right: CGSize) -> CGSize
{
return CGSizeMake(left.width + right.width, left.height + right.height)
}
func += (inout left: CGSize, right: CGSize)
{
left = left + right
}
func - (left: CGSize, right: CGSize) -> CGSize
{
return CGSizeMake(left.width - right.width, left.height - right.height)
}
func -= (inout left: CGSize, right: CGSize)
{
left = left - right
}
func * (left: CGSize, right: CGFloat) -> CGSize
{
return CGSizeMake(left.width * right, left.height * right)
}
func * (left: CGFloat, right: CGSize) -> CGSize
{
return CGSizeMake(right.width * left, right.height * left)
}
func *= (inout left: CGSize, right: CGFloat)
{
left = left * right
}
func == (left: CGSize, right: CGSize) -> Bool
{
return CGSizeEqualToSize(left, right)
}
//CGRect
func == (left: CGRect, right: CGRect) -> Bool
{
return CGRectEqualToRect(left, right)
}
func | (left: CGRect, right: CGRect) -> CGRect
{
return CGRectUnion(left, right)
}
func |= (inout left: CGRect, right: CGRect)
{
left = left | right
}
func & (left: CGRect, right: CGRect) -> CGRect
{
return CGRectIntersection(left, right)
}
func &= (inout left: CGRect, right: CGRect)
{
left = left & right
}
| mit | 50e0d58c7d5813f86f525830ee9c4d18 | 22.525926 | 79 | 0.685139 | 3.521064 | false | false | false | false |
Adorkable/StoryboardKit | StoryboardKitTests/ViewInstanceInfoTests.swift | 1 | 3984 | //
// ViewInstanceInfoTests.swift
// StoryboardKit
//
// Created by Ian on 6/30/15.
// Copyright (c) 2015 Adorkable. All rights reserved.
//
import XCTest
import StoryboardKit
class ViewInstanceInfoTests: XCTestCase {
var applicationInfo : ApplicationInfo?
var viewInstanceInfoId = "IKn-pG-61R"
var viewInstanceInfo : ViewInstanceInfo?
override func setUp() {
self.continueAfterFailure = false
super.setUp()
applicationInfo = ApplicationInfo()
do
{
try StoryboardFileParser.parse(applicationInfo!, pathFileName: storyboardPathBuilder()! )
} catch let error as NSError
{
XCTAssertNil(error, "Expected parse to not throw an error: \(error)")
}
self.viewInstanceInfo = applicationInfo?.viewInstanceWithId(self.viewInstanceInfoId)
}
func testClassInfo() {
let className = "UIView"
let classInfo = self.applicationInfo?.viewClassWithClassName(className)
XCTAssertNotNil(self.viewInstanceInfo, "Unable to retrieve ViewInstanceInfo with id \(self.viewInstanceInfoId)")
XCTAssertNotNil(classInfo, "\(self.viewInstanceInfo!)'s classInfo should not be nil")
XCTAssertEqual(self.viewInstanceInfo!.classInfo, classInfo!, "\(self.viewInstanceInfo!)'s classInfo should be equal to \(classInfo!)")
}
func testId() {
XCTAssertNotNil(self.viewInstanceInfo, "Unable to retrieve ViewInstanceInfo with id \(self.viewInstanceInfoId)")
XCTAssertEqual(self.viewInstanceInfo!.id, self.viewInstanceInfoId, "\(self.viewInstanceInfo!)'s id should be equal to \(self.viewInstanceInfo)")
}
func testFrame() {
let equalTo = CGRect(x: 0, y: 0, width: 600, height: 600)
XCTAssertNotNil(self.viewInstanceInfo, "Unable to retrieve ViewInstanceInfo with id \(self.viewInstanceInfoId)")
// XCTAssertNotNil(self.viewInstanceInfo!.frame, "\(self.viewInstanceInfo)'s frame should not be nil")
XCTAssertEqual(self.viewInstanceInfo!.frame!, equalTo, "\(self.viewInstanceInfo!)'s frame should be equal to \(equalTo)")
}
func testAutoResizingMaskWidthSizable() {
let equalTo = true
XCTAssertNotNil(self.viewInstanceInfo, "Unable to retrieve ViewInstanceInfo with id \(self.viewInstanceInfoId)")
XCTAssertEqual(self.viewInstanceInfo!.autoResizingMaskWidthSizable, equalTo, "\(self.viewInstanceInfo!)'s autoResizingMaskWidthSizable should be equal to \(equalTo)")
}
func testAutoResizingMaskHeightSizable() {
let equalTo = true
XCTAssertNotNil(self.viewInstanceInfo, "Unable to retrieve ViewInstanceInfo with id \(self.viewInstanceInfoId)")
XCTAssertEqual(self.viewInstanceInfo!.autoResizingMaskHeightSizable, equalTo, "\(self.viewInstanceInfo!)'s autoResizingMaskHeightSizable should be equal to \(equalTo)")
}
func testSubviews() {
let equalTo = 4
XCTAssertNotNil(self.viewInstanceInfo, "Unable to retrieve ViewInstanceInfo with id \(self.viewInstanceInfoId)")
XCTAssertNotNil(self.viewInstanceInfo!.subviews, "\(self.viewInstanceInfo!)'s subviews should not be nil")
XCTAssertEqual(self.viewInstanceInfo!.subviews!.count, equalTo, "\(self.viewInstanceInfo!)'s subview count should be equal to \(equalTo)")
}
func testBackgroundColor() {
let equalTo = NSColor(calibratedWhite: 0.66666666666666663, alpha: 1.0)
XCTAssertNotNil(self.viewInstanceInfo, "Unable to retrieve ViewInstanceInfo with id \(self.viewInstanceInfoId)")
XCTAssertNotNil(self.viewInstanceInfo!.backgroundColor, "\(self.viewInstanceInfo!)'s background color should not be nil")
XCTAssertEqual(self.viewInstanceInfo!.backgroundColor!, equalTo, "\(self.viewInstanceInfo!)'s background color count should be equal to \(equalTo)")
}
}
| mit | 54f3d40072f9394c87327e774dea7576 | 40.5 | 176 | 0.694026 | 4.870416 | false | true | false | false |
ZXVentures/ZXFoundation | Sources/ZXFoundation/Networking/Attributes/HTTPStatus.swift | 1 | 1379 | //
// HTTPStatus.swift
// ZXFoundation
//
// Created by Wyatt McBain on 8/30/16.
// Copyright © 2016 ZX Ventures. All rights reserved.
//
import Foundation
/**
`HTTPStatus` provides a typed representation of a http status.
*/
public enum HTTPStatus {
/// Informational response.
case info
/// Succesful response.
case success
/// Redirect response.
case redirect
/// Response with client side error.
case clientError
/// Response with server side error.
case serverError
/// No status.
case noStatus
/**
Intialize a status given a status code, even passing in raw status codes.
*/
public init(_ rawValue: Int?) {
let statusCode = rawValue ?? 0 // defasult is out of range
// Ranged cases ftw.
switch statusCode {
case 100...199: self = .info
case 200...299: self = .success
case 300...399: self = .redirect
case 400...499: self = .clientError
case 500...599: self = .serverError
default: self = .noStatus
}
}
}
extension HTTPStatus {
/// Representation as `NetworkError`
public var error: NetworkError {
switch self {
case .clientError: return .client
case .serverError: return .server
default: return .unknown
}
}
}
| mit | 3252fa7ef566d89b166abcf40b046bcc | 22.758621 | 78 | 0.587083 | 4.503268 | false | false | false | false |
sendyhalim/iYomu | Yomu/Screens/Root/YomuNavigationController.swift | 1 | 1811 | //
// YomuRootViewController.swift
// Yomu
//
// Created by Sendy Halim on 6/3/17.
// Copyright © 2017 Sendy Halim. All rights reserved.
//
import UIKit
import RxSwift
enum NavigationTarget {
case searchManga
case chapterCollection(String)
case chapterPageCollection(ChapterViewModel)
}
enum NavigationData {
case searchManga(String)
}
/// Custom UINavigationController for easier customization in the future
class YomuNavigationController: UINavigationController {
static func instance() -> YomuNavigationController? {
let windows = UIApplication.shared.windows
for window in windows {
if let rootViewController = window.rootViewController {
return rootViewController as? YomuNavigationController
}
}
return nil
}
func navigate(to: NavigationTarget) -> Observable<NavigationData?> {
switch to {
case .searchManga:
let searchMangaVC = SearchMangaCollectionViewController(nibName: nil, bundle: nil)
pushViewController(searchMangaVC, animated: true)
return searchMangaVC
.newManga
.asObservable()
.flatMap { $0.apiId.asObservable() }
.map { .searchManga($0) }
case .chapterCollection(let mangaId):
let viewModel = ChapterCollectionViewModel(mangaId: mangaId)
let chapterCollectionVC = ChapterCollectionViewController(viewModel: viewModel)
pushViewController(chapterCollectionVC, animated: true)
return Observable.just(nil)
case .chapterPageCollection(let chapterVM):
let viewModel = ChapterPageCollectionViewModel(chapterViewModel: chapterVM)
let chapterPageCollectionVC = ChapterPageCollectionViewController(viewModel: viewModel)
pushViewController(chapterPageCollectionVC, animated: true)
return Observable.just(nil)
}
}
}
| mit | 7be67ed000cb156a983455cfdaba58b3 | 27.28125 | 93 | 0.734807 | 4.641026 | false | false | false | false |
jwfriese/FrequentFlyer | FrequentFlyer/Logs/LogsStylingParser.swift | 1 | 1240 | import Foundation
class LogsStylingParser {
fileprivate var stylingDescriptorBuilder: StylingDescriptorBuilder
fileprivate var hasOpenStylingElement: Bool = false
init() {
stylingDescriptorBuilder = StylingDescriptorBuilder()
}
func stripStylingCoding(originalString: String) -> String {
var strippedString = ""
for character in originalString {
if stylingDescriptorBuilder.isBuilding {
let didAddCharacter = stylingDescriptorBuilder.add(character)
if didAddCharacter { continue }
let (builtString, isStylingDescriptor) = stylingDescriptorBuilder.finish()
if !isStylingDescriptor {
strippedString.append(builtString)
}
let didStartNewDescriptor = stylingDescriptorBuilder.add(character)
if didStartNewDescriptor { continue }
strippedString.append(character)
} else {
let didStartBuilding = stylingDescriptorBuilder.add(character)
if !didStartBuilding {
strippedString.append(character)
}
}
}
return strippedString
}
}
| apache-2.0 | 89e23731beb6e94fa1cefaf1a6189eba | 33.444444 | 90 | 0.616935 | 6.019417 | false | false | false | false |
gaoleegin/SwiftLianxi | ReactiveSecondLianXi/Pods/ReactiveCocoa/ReactiveCocoa/Swift/Disposable.swift | 33 | 5613 | //
// Disposable.swift
// ReactiveCocoa
//
// Created by Justin Spahr-Summers on 2014-06-02.
// Copyright (c) 2014 GitHub. All rights reserved.
//
/// Represents something that can be “disposed,” usually associated with freeing
/// resources or canceling work.
public protocol Disposable {
/// Whether this disposable has been disposed already.
var disposed: Bool { get }
func dispose()
}
/// A disposable that only flips `disposed` upon disposal, and performs no other
/// work.
public final class SimpleDisposable: Disposable {
private let _disposed = Atomic(false)
public var disposed: Bool {
return _disposed.value
}
public init() {}
public func dispose() {
_disposed.value = true
}
}
/// A disposable that will run an action upon disposal.
public final class ActionDisposable: Disposable {
private let action: Atomic<(() -> ())?>
public var disposed: Bool {
return action.value == nil
}
/// Initializes the disposable to run the given action upon disposal.
public init(action: () -> ()) {
self.action = Atomic(action)
}
public func dispose() {
let oldAction = action.swap(nil)
oldAction?()
}
}
/// A disposable that will dispose of any number of other disposables.
public final class CompositeDisposable: Disposable {
private let disposables: Atomic<Bag<Disposable>?>
/// Represents a handle to a disposable previously added to a
/// CompositeDisposable.
public final class DisposableHandle {
private let bagToken: Atomic<RemovalToken?>
private weak var disposable: CompositeDisposable?
private static let empty = DisposableHandle()
private init() {
self.bagToken = Atomic(nil)
}
private init(bagToken: RemovalToken, disposable: CompositeDisposable) {
self.bagToken = Atomic(bagToken)
self.disposable = disposable
}
/// Removes the pointed-to disposable from its CompositeDisposable.
///
/// This is useful to minimize memory growth, by removing disposables
/// that are no longer needed.
public func remove() {
if let token = bagToken.swap(nil) {
disposable?.disposables.modify { bag in
guard var bag = bag else { return nil }
bag.removeValueForToken(token)
return bag
}
}
}
}
public var disposed: Bool {
return disposables.value == nil
}
/// Initializes a CompositeDisposable containing the given sequence of
/// disposables.
public init<S: SequenceType where S.Generator.Element == Disposable>(_ disposables: S) {
var bag: Bag<Disposable> = Bag()
for disposable in disposables {
bag.insert(disposable)
}
self.disposables = Atomic(bag)
}
/// Initializes an empty CompositeDisposable.
public convenience init() {
self.init([])
}
public func dispose() {
if let ds = disposables.swap(nil) {
for d in ds.reverse() {
d.dispose()
}
}
}
/// Adds the given disposable to the list, then returns a handle which can
/// be used to opaquely remove the disposable later (if desired).
public func addDisposable(d: Disposable?) -> DisposableHandle {
guard let d = d else {
return DisposableHandle.empty
}
var handle: DisposableHandle? = nil
disposables.modify { ds in
guard var ds = ds else { return nil }
let token = ds.insert(d)
handle = DisposableHandle(bagToken: token, disposable: self)
return ds
}
if let handle = handle {
return handle
} else {
d.dispose()
return DisposableHandle.empty
}
}
/// Adds an ActionDisposable to the list.
public func addDisposable(action: () -> ()) -> DisposableHandle {
return addDisposable(ActionDisposable(action: action))
}
}
/// A disposable that, upon deinitialization, will automatically dispose of
/// another disposable.
public final class ScopedDisposable: Disposable {
/// The disposable which will be disposed when the ScopedDisposable
/// deinitializes.
public let innerDisposable: Disposable
public var disposed: Bool {
return innerDisposable.disposed
}
/// Initializes the receiver to dispose of the argument upon
/// deinitialization.
public init(_ disposable: Disposable) {
innerDisposable = disposable
}
deinit {
dispose()
}
public func dispose() {
innerDisposable.dispose()
}
}
/// A disposable that will optionally dispose of another disposable.
public final class SerialDisposable: Disposable {
private struct State {
var innerDisposable: Disposable? = nil
var disposed = false
}
private let state = Atomic(State())
public var disposed: Bool {
return state.value.disposed
}
/// The inner disposable to dispose of.
///
/// Whenever this property is set (even to the same value!), the previous
/// disposable is automatically disposed.
public var innerDisposable: Disposable? {
get {
return state.value.innerDisposable
}
set(d) {
let oldState = state.modify { (var state) in
state.innerDisposable = d
return state
}
oldState.innerDisposable?.dispose()
if oldState.disposed {
d?.dispose()
}
}
}
/// Initializes the receiver to dispose of the argument when the
/// SerialDisposable is disposed.
public init(_ disposable: Disposable? = nil) {
innerDisposable = disposable
}
public func dispose() {
let orig = state.swap(State(innerDisposable: nil, disposed: true))
orig.innerDisposable?.dispose()
}
}
/// Adds the right-hand-side disposable to the left-hand-side
/// `CompositeDisposable`.
///
/// disposable += producer
/// .filter { ... }
/// .map { ... }
/// .start(sink)
///
public func +=(lhs: CompositeDisposable, rhs: Disposable?) -> CompositeDisposable.DisposableHandle {
return lhs.addDisposable(rhs)
}
| apache-2.0 | 60756623a64d563db3aefb2cf0ff442c | 23.072961 | 100 | 0.699412 | 3.889736 | false | false | false | false |
SASAbus/SASAbus-ios | SASAbus/Sync/TripSyncHelper.swift | 1 | 1686 | import Foundation
import RxSwift
import RxCocoa
import SwiftyJSON
import RealmSwift
class TripSyncHelper {
static func upload(trips: [CloudTrip], scheduler: SchedulerType) {
Log.warning("Uploading \(trips.count) trips")
_ = CloudApi.uploadTrips(trips: trips)
.subscribeOn(scheduler)
.observeOn(MainScheduler.instance)
.subscribe(onNext: { json in
Log.error("Got \(json["earned_badges"].arrayValue.count) new badges to display")
Log.info(json)
DispatchQueue(label: "com.app.queue", qos: .background).async {
// TODO
/*for (badge in response.badges) {
Notifications.badge(context, badge)
}*/
}
let realm = try! Realm()
for rejected in json["rejected_trips"].arrayValue {
let trip = realm.objects(Trip.self).filter("hash == '\(rejected)'").first
if trip != nil {
try! realm.write {
realm.delete(trip!)
}
} else {
Log.error("Rejected trip with hash '\(rejected)' not found in database")
}
}
}, onError: { error in
ErrorHelper.log(error, message: "Could not upload trips")
})
}
}
| gpl-3.0 | 1fb9992cd27a975ac2171ec4277891b5 | 36.466667 | 100 | 0.424081 | 6.064748 | false | false | false | false |
grandiere/box | box/Controller/Support/CSettings.swift | 1 | 2366 | import UIKit
class CSettings:CController
{
let model:MSettings
private weak var viewSettings:VSettings!
private let urlMap:[String:String]?
private let kResourceName:String = "ResourceURL"
private let kResourceExtension:String = "plist"
private let kReviewKey:String = "review"
private let kShareKey:String = "share"
override init()
{
model = MSettings()
guard
let resourceUrl:URL = Bundle.main.url(
forResource:kResourceName,
withExtension:kResourceExtension),
let urlDictionary:NSDictionary = NSDictionary(
contentsOf:resourceUrl),
let urlMap:[String:String] = urlDictionary as? [String:String]
else
{
self.urlMap = nil
super.init()
return
}
self.urlMap = urlMap
super.init()
}
required init?(coder:NSCoder)
{
return nil
}
override func loadView()
{
let viewSettings:VSettings = VSettings(controller:self)
self.viewSettings = viewSettings
view = viewSettings
}
//MARK: public
func back()
{
parentController.pop(horizontal:CParent.TransitionHorizontal.fromRight)
}
func review()
{
guard
let urlString:String = urlMap?[kReviewKey],
let url:URL = URL(string:urlString)
else
{
return
}
UIApplication.shared.openURL(url)
}
func share()
{
guard
let urlString:String = urlMap?[kShareKey],
let url:URL = URL(string:urlString)
else
{
return
}
let activity:UIActivityViewController = UIActivityViewController(
activityItems:[url],
applicationActivities:nil)
if let popover:UIPopoverPresentationController = activity.popoverPresentationController
{
popover.sourceView = viewSettings
popover.sourceRect = CGRect.zero
popover.permittedArrowDirections = UIPopoverArrowDirection.up
}
present(activity, animated:true)
}
}
| mit | 3b95928ffd2d24404dfd055f8a939c6f | 23.142857 | 95 | 0.542265 | 5.515152 | false | false | false | false |
acecilia/SugarEdges | Sources/ExpressibleByEdgesDictionaryLiteral.swift | 1 | 1513 | /// A type that can be initialized using a dictionary of Edges, and their associated value
public protocol ExpressibleByEdgesDictionaryLiteral: ExpressibleByDictionaryLiteral {
init(top: CGFloat, left: CGFloat, bottom: CGFloat, right: CGFloat)
}
extension ExpressibleByEdgesDictionaryLiteral {
public init(dictionaryLiteral elements: (Set<Edge>, CGFloat)...) {
var top : CGFloat = 0
var left : CGFloat = 0
var bottom: CGFloat = 0
var right : CGFloat = 0
for (edges, value) in elements {
if edges.contains(.top) { top = value }
if edges.contains(.left) { left = value }
if edges.contains(.bottom) { bottom = value }
if edges.contains(.right) { right = value }
}
self = Self(top: top, left: left, bottom: bottom, right: right)
}
}
extension Set where Element == Edge {
public static var top: Set<Edge> { return [.top] }
public static var left: Set<Edge> { return [.left] }
public static var bottom: Set<Edge> { return [.bottom] }
public static var right: Set<Edge> { return [.right] }
public static var vertical: Set<Edge> { return top + bottom }
public static var horizontal: Set<Edge> { return left + right }
public static var all: Set<Edge> { return top + left + bottom + right }
public static func + (left: Set<Edge>, right: Set<Edge>) -> Set<Edge> {
return left.union(right)
}
}
| mit | e6b698dd5c896a8861438f040d8c98ef | 41.027778 | 90 | 0.608724 | 4.179558 | false | false | false | false |
onevcat/APNGKit | Source/APNGKit/APNGImageView.swift | 1 | 20375 | //
// APNGImageView.swift
//
//
// Created by Wang Wei on 2021/10/12.
//
#if canImport(UIKit) || canImport(AppKit)
import Delegate
import Foundation
import CoreGraphics
/// A view object that displays an `APNGImage` and perform the animation.
///
/// To display an APNG image on the screen, you first create an `APNGImage` object, then use it to initialize an
/// `APNGImageView` by using `init(image:)` or set the ``image`` property.
///
/// Similar to other UI components, it is your responsibility to access the UI related property or method in this class
/// only in the main thread. Otherwise, it may cause unexpected behaviors.
open class APNGImageView: PlatformView {
public typealias PlayedLoopCount = Int
public typealias FrameIndex = Int
/// Whether the animation should be played automatically when a valid `APNGImage` is set to the `image` property
/// of `self`. Default is `true`.
open var autoStartAnimationWhenSetImage = true
/// A delegate called every time when a "play" (a single loop of the animated image) is done. The parameter number
/// is the count of played loops.
///
/// For example, if an animated image is newly set and played, after its whole duration, this delegate will be
/// called with the number `1`. Then if the image contains a `numberOfPlays` more than 1, after its the animation is
/// played for another loop, this delegate is called with `2` again, etc.
public let onOnePlayDone = Delegate<PlayedLoopCount, Void>()
/// A delegate called when the whole image is played for its `numberOfPlays` count. If the `numberOfPlays` of the
/// playing `image` is `nil`, this delegate will never be triggered.
public let onAllPlaysDone = Delegate<(), Void>()
/// A delegate called when a frame decoding misses its requirement. This usually means the CPU resource is not
/// enough to display the animation at its full frame rate and causes a frame drop or latency of animation.
public let onFrameMissed = Delegate<FrameIndex, Void>()
/// A delegate called when the `image` cannot be decoded during the displaying and the default image defined in the
/// APNG image data is displayed as a fallback.
///
/// This delegate method is always called after the `onDecodingFrameError` delegate if in its parameter the
/// `DecodingErrorItem.canFallbackToDefaultImage` is `true`.
public let onFallBackToDefaultImage = Delegate<(), Void>()
/// A delegate called when the `image` cannot be decoded during the displaying and the default image decoding also
/// fails. The parameter error contains the reason why the default image cannot be decoded.
///
/// This delegate method is always called after the `onDecodingFrameError` delegate if in its parameter the
/// `DecodingErrorItem.canFallbackToDefaultImage` is `false`.
public let onFallBackToDefaultImageFailed = Delegate<APNGKitError, Void>()
/// A delegate called when the `image` cannot be decoded. It contains the encountered decoding error in its
/// parameter. After this delegate, either `onFallBackToDefaultImage` or `onFallBackToDefaultImageFailed` will be
/// called.
public let onDecodingFrameError = Delegate<DecodingErrorItem, Void>()
/// The timer type which is used to drive the animation. By default, if `CADisplayLink` is available, a
/// `DisplayTimer` is used. On platforms that `CADisplayLink` is not available, a normal `Foundation.Timer` based
/// one is used.
#if canImport(UIKit)
public var DrivingTimerType: DrivingTimer.Type { NormalTimer.self }
#else
public var DrivingTimerType: DrivingTimer.Type { NormalTimer.self }
#endif
private(set) var renderer: APNGImageRenderer?
// When the current frame was started to be displayed on the screen. It is the base time to calculate the current
// frame duration.
private var displayingFrameStarted: CFTimeInterval?
// The current displaying frame index in its decoder.
private(set) var displayingFrameIndex = 0
// Returns the next frame to be rendered. If the current displaying frame is not the last, return index of the next
// frame. If the current displaying frame is the last one, returns 0 regardless whether there is another play or
// not.
private var nextFrameIndex: Int {
guard let image = _image else {
return 0
}
return displayingFrameIndex + 1 >= image.decoder.framesCount ? 0 : displayingFrameIndex + 1
}
// Whether the next displaying frame missed its target.
private var frameMissed: Bool = false
// Backing timer for updating animation content.
private(set) var drivingTimer: DrivingTimer?
// Backing storage.
private var _image: APNGImage?
// Number of played plays of the animated image.
private var playedCount = 0
/// Creates an APNG image view with the specified animated image.
/// - Parameter image: The initial image to display in the image view.
public convenience init(image: APNGImage?, autoStartAnimating: Bool = true) {
self.init(frame: .zero)
self.autoStartAnimationWhenSetImage = autoStartAnimating
self.image = image
}
/// Creates an APNG image view with the specified normal image.
/// - Parameter image: The initial image to display in the image view.
///
/// This method is provided as a fallback for setting a normal `UIImage`. This does not start the animation or
public convenience init(image: PlatformImage?) {
self.init(frame: .zero)
let contentScale = image?.recommendedLayerContentsScale(screenScale) ?? screenScale
backingLayer.contents = image?.layerContents(forContentsScale:contentScale)
backingLayer.contentsScale = contentScale
}
/// Creates an APNG image view with the specified frame.
/// - Parameter frame: The initial frame that this image view should be placed.
public override init(frame: CGRect) {
super.init(frame: frame)
}
required public init?(coder: NSCoder) {
super.init(coder: coder)
}
/// The natural size for the receiving view, considering only properties of the view itself.
///
/// For an APNGImageView, its intrinsic content size is the `size` property of its set `APNGImage` object.
open override var intrinsicContentSize: CGSize {
_image?.size ?? .zero
}
/// Whether the image view is performing animation.
public var isAnimating: Bool {
if let timer = drivingTimer {
return !timer.isPaused
} else {
return false
}
}
/// The run loop where the animation (or say, the display link) should be run on.
///
/// By default, the animation will run on the `.common` runloop, which means the animation continues when user
/// perform other action such as scrolling. You are only allowed to set it once before the animation started.
/// Otherwise it causes an assertion or has no effect.
open var runLoopMode: RunLoop.Mode? {
didSet {
if oldValue != nil {
assertionFailure("You can only set runloop mode for one time. Setting it for multiple times is not allowed and causes unexpected behaviors.")
}
}
}
/// Set a static image for the image view. This is useful when you need to set some fallback image if the decoding
/// of `APNGImage` results in a failure.
///
/// A regular case is the input data is not a valid APNG image but a plain image, then you should revert to use the
/// normal format, aka, `UIImage` to represent the image. Creating an `APNGImage` with such data throws a
/// `APNGKitError.ImageError.normalImageDataLoaded` error. You can check the error's `normalImage` property and set
/// it to this property as a fallback for wrong APNG images:
///
/// ```swift
/// do {
/// animatedImageView.image = try APNGImage(named: "some_apng_image")
/// } catch {
/// animatedImageView.staticImage = error.apngError?.normalImage
/// print(error)
/// }
/// ```
public var staticImage: PlatformImage? = nil {
didSet {
if staticImage != nil {
self.image = nil
}
let targetScale = staticImage?.recommendedLayerContentsScale(screenScale) ?? screenScale
backingLayer.contentsScale = targetScale
backingLayer.contents = staticImage?.layerContents(forContentsScale: targetScale)
}
}
private func unsetImage() {
stopAnimating()
_image = nil
renderer = nil
backingLayer.contents = nil
playedCount = 0
displayingFrameIndex = 0
}
/// The animated image of this image view.
///
/// Setting this property replaces the current displayed image and "registers" the new image as being held by the
/// image view. By setting a new valid `APNGImage`, the image view will render the first frame or the default image
/// of it. If `autoStartAnimationWhenSetImage` is set to `true`, the animation will start automatically. Otherwise,
/// you can call `startAnimating` explicitly to start the animation.
///
/// Similar to other UI components, it is your responsibility to access this property only in the main thread.
/// Otherwise, it may cause unexpected behaviors.
public var image: APNGImage? {
get { _image }
set {
guard let nextImage = newValue else {
unsetImage()
return
}
if _image === nextImage {
// Nothing to do if the same image is set.
return
}
unsetImage()
do {
renderer = try APNGImageRenderer(decoder: nextImage.decoder)
} catch {
printLog("Error happens while creating renderer for image. \(error)")
defaultDecodingErrored(
frameError: error.apngError ?? .internalError(error),
defaultImageError: .decoderError(.invalidRenderer)
)
return
}
_image = nextImage
// Try to render the first frame. If failed, fallback to the default image defined in the APNG, or set the
// layer content to `nil` if the default image cannot be decoded correctly.
let renderResult = renderCurrentDecoderOutput()
switch renderResult {
case .rendered(let initialImage):
backingLayer.contentsScale = nextImage.scale
backingLayer.contents = initialImage
if autoStartAnimationWhenSetImage {
startAnimating()
}
renderer?.renderNext()
case .fallbackToDefault(let defaultImage, let error):
fallbackTo(defaultImage, referenceScale: nextImage.scale, error: error)
case .defaultDecodingError(let error, let defaultImageError):
defaultDecodingErrored(frameError: error, defaultImageError: defaultImageError)
}
invalidateIntrinsicContentSize()
}
}
private func fallbackTo(_ defaultImage: PlatformImage?, referenceScale: CGFloat, error: APNGKitError) {
let scale = defaultImage?.recommendedLayerContentsScale(referenceScale) ?? screenScale
backingLayer.contentsScale = scale
backingLayer.contents = defaultImage?.layerContents(forContentsScale:scale)
stopAnimating()
onDecodingFrameError(.init(error: error, canFallbackToDefaultImage: true))
onFallBackToDefaultImage()
}
private func defaultDecodingErrored(frameError: APNGKitError, defaultImageError: APNGKitError) {
backingLayer.contents = nil
stopAnimating()
onDecodingFrameError(.init(error: frameError, canFallbackToDefaultImage: false))
onFallBackToDefaultImageFailed(defaultImageError)
}
/// Starts the animation. Calling this method does nothing if the animation is already running.
open func startAnimating() {
guard !isAnimating else {
return
}
guard _image != nil else {
return
}
if drivingTimer == nil {
drivingTimer = DrivingTimerType.init(
mode: runLoopMode,
target: self,
action: { [weak self] timestamp in self?.step(timestamp: timestamp)
})
}
drivingTimer?.isPaused = false
displayingFrameStarted = nil
NotificationCenter.default.addObserver(
self, selector: #selector(appMovedFromBackground), name: .applicationDidBecomeActive, object: nil
)
}
/// Resets the current image play status.
///
/// It is identical to set the current `image` to `nil` and then set it again. If `autoStartAnimationWhenSetImage`
/// is `true`, the animation will be played from the first frame with a clean play status.
open func reset() throws {
guard let currentImage = _image else {
return
}
unsetImage()
image = currentImage
}
/// Stops the animation. Calling this method does nothing if the animation is not started or already stopped.
///
/// When the animation stops, it stays in the last displayed frame. You can call `startAnimating` to start it again.
open func stopAnimating() {
guard isAnimating else {
return
}
drivingTimer?.isPaused = true
NotificationCenter.default.removeObserver(self)
}
private func step(timestamp: TimeInterval) {
guard let image = image else {
assertionFailure("No valid image set in current image view, but the display link is not paused. This should not happen.")
return
}
guard let displayingFrame = image.decoder.frame(at: displayingFrameIndex) else {
assertionFailure("Cannot get correct frame which is being displayed.")
return
}
if displayingFrameStarted == nil { // `step` is called by the first time after an animation.
displayingFrameStarted = timestamp
}
let frameDisplayedDuration = timestamp - displayingFrameStarted!
if frameDisplayedDuration < displayingFrame.frameControl.duration {
// Current displayed frame is not displayed for enough time. Do nothing.
return
}
// The final of last frame in one play.
if displayingFrameIndex == image.decoder.framesCount - 1 {
playedCount = playedCount + 1
onOnePlayDone(playedCount)
}
// Played enough count. Stop animating and stay at the last frame.
if !image.playForever && playedCount >= (image.numberOfPlays ?? 0) {
stopAnimating()
onAllPlaysDone()
return
}
// We should display the next frame!
guard let renderer = renderer, let _ = renderer.output /* the frame image is rendered */ else {
// but unfortunately the decoding missed the target.
// we can just wait for the next `step`.
printLog("Missed frame for image \(image): target index: \(nextFrameIndex), while displaying the current frame index: \(displayingFrameIndex).")
onFrameMissed(nextFrameIndex)
frameMissed = true
return
}
// Have an output! Replace the current displayed one and start to render the next frame.
let frameWasMissed = frameMissed
frameMissed = false
switch renderCurrentDecoderOutput() {
case .rendered(let renderedImage):
// Show the next image.
backingLayer.contentsScale = image.scale
backingLayer.contents = renderedImage
// for a 60 FPS system, we only have a chance of replacing the content per 16.6ms.
// To provide a more accurate animation we need the determine the frame starting
// by the frame def instead of real `timestamp`, unless we failed to display the frame in time.
displayingFrameStarted = frameWasMissed ?
timestamp :
displayingFrameStarted! + displayingFrame.frameControl.duration
displayingFrameIndex = renderer.currentIndex
// Start to render the next frame. This happens in a background thread in decoder.
renderer.renderNext()
case .fallbackToDefault(let defaultImage, let error):
fallbackTo(defaultImage, referenceScale: image.scale, error: error)
case .defaultDecodingError(let error, let defaultImageError):
defaultDecodingErrored(frameError: error, defaultImageError: defaultImageError)
}
}
@objc private func appMovedFromBackground() {
// Reset the current displaying frame when the app is active again.
// This prevents the animation being played faster due to the old timestamp.
displayingFrameStarted = drivingTimer?.timestamp
}
// Invalid and reset the display link.
private func cleanDisplayLink() {
drivingTimer?.invalidate()
drivingTimer = nil
}
private enum RenderResult {
// The next frame is rendered without problem.
case rendered(CGImage?)
// The image is rendered with the default image as a fallback, with an error indicates what is wrong when
// decoding the target (failing) frame.
case fallbackToDefault(PlatformImage?, APNGKitError)
// The frame decoding is failing due to `frameError`, and the fallback default image is also failing,
// due to `defaultDecodingError`.
case defaultDecodingError(frameError: APNGKitError, defaultDecodingError: APNGKitError)
}
private func renderCurrentDecoderOutput() -> RenderResult {
guard let image = _image, let output = renderer?.output else {
return .rendered(nil)
}
switch output {
case .success(let cgImage):
return .rendered(cgImage)
case .failure(let error):
return renderErrorToResult(image: image, error: error)
}
}
private func renderErrorToResult(image: APNGImage, error: Error) -> RenderResult {
do {
printLog("Encountered an error when decoding the next image frame, index: \(nextFrameIndex). Error: \(error). Trying to reverting to the default image.")
let data = try image.decoder.createDefaultImageData()
return .fallbackToDefault(PlatformImage(data: data, scale: image.scale), error.apngError ?? .internalError(error))
} catch let defaultDecodingError {
printLog("Encountered an error when decoding the default image. \(error)")
return .defaultDecodingError(
frameError: error.apngError ?? .internalError(error),
defaultDecodingError: defaultDecodingError.apngError ?? .internalError(defaultDecodingError)
)
}
}
}
extension APNGImageView {
public struct DecodingErrorItem {
public let error: APNGKitError
public let canFallbackToDefaultImage: Bool
}
}
extension APNGKitError {
/// Treat the error as a recoverable one. Try to extract the normal version of image and return it is can be created
/// as a normal image.
///
/// When you get an error while initializing an `APNGImage`, you can try to access this property of the `APNGKitError`
/// to check if it is not an APNG image but a normal images supported on the platform. You can choose to set the
/// returned value to `APNGImageView.staticImage` to let the view displays a static normal image as a fallback.
public var normalImage: PlatformImage? {
guard let (data, scale) = self.normalImageData else {
return nil
}
return PlatformImage(data: data, scale: scale)
}
}
#endif
| mit | c4593bed3297fab653b7ad6640238fc4 | 43.584245 | 165 | 0.65173 | 5.103958 | false | false | false | false |
polischouckserg/tutu-test | RoutePicker/RoutePicker/Sources/View models/ScheduleViewModel.swift | 1 | 1024 | //
// ScheduleViewModel.swift
// RoutePicker
//
// Created by Sergey Polischouck on 04/11/16.
// Copyright © 2016 Sergey Polischouck. All rights reserved.
//
import Foundation
class ScheduleViewModel
{
var pickedStationFrom: Station?
var pickedStationTo: Station?
var pickedDate: Date?
var pickedStationFromTitle: String {
var pickedStationFromTitle = "Chose station"
if let stationTitle = pickedStationFrom?.stationTitle, let cityTitle = pickedStationFrom?.city?.cityTitle
{
pickedStationFromTitle = cityTitle + ", " + stationTitle
}
return pickedStationFromTitle
}
var pickedStationToTitle: String {
var pickedStationToTitle = "Chose station"
if let stationTitle = pickedStationTo?.stationTitle, let cityTitle = pickedStationTo?.city?.cityTitle
{
pickedStationToTitle = cityTitle + ", " + stationTitle
}
return pickedStationToTitle
}
}
| apache-2.0 | 1b5270e08cb42d077f64bf3c4e88a17e | 25.230769 | 113 | 0.648094 | 4.506608 | false | false | false | false |
rayfix/RAFIntMath | RAFIntMath/Rational.swift | 1 | 2809 | //
// Rational.swift
//
// Created by Ray Fix on 6/21/14.
// Copyright (c) 2014 Pelfunc, Inc. All rights reserved.
//
import Foundation
public struct Rational : Printable, Comparable, Hashable
{
public let numerator:Int
public let denominator:Int
public init(_ v:Int)
{
self.init(v,1)
}
public init(_ n:Int, _ d:Int)
{
self.numerator = n
self.denominator = d
}
public var isZero : Bool
{
return !isNaN && numerator == 0
}
public var isNaN : Bool
{
return denominator == 0
}
public var reciprocal: Rational
{
return Rational(denominator, numerator)
}
public var wholePart:Int
{
return numerator / denominator
}
public var remainder:Int
{
return numerator % denominator
}
public var description:String
{
if (isNaN) {
return "NaN"
}
else if (self.denominator == 1) {
return "\(numerator)"
}
else {
return "\(numerator)/\(denominator)"
}
}
static func gcd(var a:Int, var _ b:Int) -> Int
{
var t:Int
while (b != 0) {
t = b
b = a % b
a = t
}
return a
}
public func reduced() -> Rational
{
if (isZero) {
return Rational(0,1)
}
else if (isNaN) {
return Rational(1,0)
}
else if (denominator != 1) {
let x = Rational.gcd(numerator, denominator)
return Rational(numerator/x, denominator/x)
}
return self
}
public var hashValue: Int
{
return Double(self).hashValue
}
}
public func ==(a: Rational, b: Rational) -> Bool
{
let lhs = a.reduced()
let rhs = b.reduced()
return lhs.numerator == rhs.numerator &&
lhs.denominator == rhs.denominator
}
public func <(lhs: Rational, rhs: Rational) -> Bool
{
return Double(lhs) < Double(rhs)
}
public func +(lhs:Rational, rhs:Rational) -> Rational
{
return Rational(lhs.numerator * rhs.denominator +
rhs.numerator * lhs.denominator,
lhs.denominator * rhs.denominator).reduced()
}
public func -(lhs:Rational, rhs:Rational) -> Rational
{
return lhs + (-rhs)
}
public prefix func -(a: Rational) -> Rational {
return Rational(-a.numerator, a.denominator)
}
public func *(a: Rational, b: Rational) -> Rational
{
return Rational(a.numerator*b.numerator,a.denominator*b.denominator)
}
public func /(a: Rational, b: Rational) -> Rational
{
return a * b.reciprocal;
}
public extension Double {
init(_ v:Rational)
{
self = Double(v.numerator) / Double(v.denominator)
}
}
| mit | 1491c387a550cd9b07b1ff7f52df3870 | 18.921986 | 72 | 0.546102 | 3.995733 | false | false | false | false |
ahoppen/swift | benchmark/single-source/ObserverPartiallyAppliedMethod.swift | 10 | 1252 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 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 TestsUtils
public let benchmarks =
BenchmarkInfo(
name: "ObserverPartiallyAppliedMethod",
runFunction: run_ObserverPartiallyAppliedMethod,
tags: [.validation],
legacyFactor: 20)
class Observer {
@inline(never)
func receive(_ value: Int) {
}
}
class Signal {
var observers: [(Int) -> ()] = []
func subscribe(_ observer: @escaping (Int) -> ()) {
observers.append(observer)
}
func send(_ value: Int) {
for observer in observers {
observer(value)
}
}
}
public func run_ObserverPartiallyAppliedMethod(_ iterations: Int) {
let signal = Signal()
let observer = Observer()
for _ in 0 ..< 500 * iterations {
signal.subscribe(observer.receive)
}
signal.send(1)
}
| apache-2.0 | 322b0c58dc3d243b77df3085cdf7d439 | 24.55102 | 80 | 0.595048 | 4.536232 | false | false | false | false |
patrick-sheehan/cwic | Source/User.swift | 1 | 2137 | //
// User.swift
// cwic
//
// Created by Patrick Sheehan on 6/14/17.
// Copyright © 2017 Síocháin Solutions. All rights reserved.
//
import UIKit
class Profile {
var avatar: String
var birthdate: String
var gender: String
var hometown: String
var how_discovered: String
var phone_number: String
var user_type: String
var years_attended: Int
init(json: [String: Any]) {
self.avatar = json["avatar"] as? String ?? ""
self.hometown = json["hometown"] as? String ?? ""
self.years_attended = json["years_attended"] as? Int ?? 0
self.how_discovered = json["how_discovered"] as? String ?? ""
self.phone_number = json["phone_number"] as? String ?? ""
self.birthdate = json["birthdate"] as? String ?? ""
self.gender = json["gender_name"] as? String ?? ""
self.user_type = json["user_type_name"] as? String ?? ""
}
}
class User {
var id: Int
var username: String
var first_name: String
var last_name: String
var profile: Profile
// var avatar: String
// var birthdate: String
// var gender: String
// var hometown: String
// var how_discovered: String
// var phone_number: String
// var user_type: String
// var years_attended: Int
var trophies: [Trophy]
init(json: [String: Any]) {
self.id = json["id"] as? Int ?? 0
self.username = json["username"] as? String ?? ""
self.first_name = json["first_name"] as? String ?? ""
self.last_name = json["last_name"] as? String ?? ""
if let profileJson = json["profile"] as? [String: Any] {
self.profile = Profile(json: profileJson)
} else {
self.profile = Profile(json: [String: Any]())
}
if let trophiesJson = json["trophies"] as? [[String: Any]] {
self.trophies = trophiesJson.map { Trophy(json: $0) }
} else {
self.trophies = []
}
}
}
let UserTypes: [String: String] = [
"Artist": "A",
"Committee Member": "C",
"Judge": "J",
"Team Leader": "L",
"Team Member": "M",
"Sponsor": "S",
"Visitor": "V",
]
let Genders: [String: String] = [
"Male": "M",
"Female": "F",
"Other": "O",
"Unspecifieid": "U"
]
| gpl-3.0 | 590864334059b863cf2def20c98cc255 | 22.711111 | 65 | 0.598875 | 3.156805 | false | false | false | false |
ontouchstart/swift3-playground | playground2book/Deal/Deal.playgroundbook/Contents/Chapters/Deal.playgroundchapter/Pages/Deal.playgroundpage/Contents.swift | 1 | 3884 | import Darwin
public func random (_ seed: Int) -> Int {
return Int(arc4random_uniform(UInt32(seed)))
}
extension MutableCollection where Index == Int, IndexDistance == Int {
mutating func shuffle() {
guard count > 1 else { return }
for i in 0..<count - 1 {
let j = random(count - i) + i
guard i != j else { continue }
swap(&self[i], &self[j])
}
}
}
extension Collection {
func shuffled() -> [Generator.Element] {
var array = Array(self)
array.shuffle()
return array
}
}
public enum Rank : Int {
case two = 2
case three, four, five, six, seven, eight, nine, ten
case jack, queen, king, ace
}
public func <(lhs: Rank, rhs: Rank) -> Bool {
switch (lhs, rhs) {
case (_, _) where lhs == rhs:
return false
case (.ace, _):
return false
default:
return lhs.rawValue < rhs.rawValue
}
}
extension Rank : Comparable {}
extension Rank : CustomStringConvertible {
public var description: String {
switch self {
case .ace: return "A"
case .jack: return "J"
case .queen: return "Q"
case .king: return "K"
default:
return "\(rawValue)"
}
}
}
public enum Suit: String {
case spades, hearts, diamonds, clubs
}
public func <(lhs: Suit, rhs: Suit) -> Bool {
switch (lhs, rhs) {
case (_, _) where lhs == rhs:
return false
case (.spades, _),
(.hearts, .diamonds), (.hearts, .clubs),
(.diamonds, .clubs):
return false
default:
return true
}
}
extension Suit: Comparable {}
extension Suit : CustomStringConvertible {
public var description: String {
switch self {
case .spades: return "♠︎"
case .hearts: return "♡"
case .diamonds: return "♢"
case .clubs: return "♣︎"
}
}
}
public struct PlayingCard {
let rank: Rank
let suit: Suit
public init(rank: Rank, suit: Suit) {
self.rank = rank
self.suit = suit
}
}
public func ==(lhs: PlayingCard, rhs: PlayingCard) -> Bool {
return lhs.rank == rhs.rank && lhs.suit == rhs.suit
}
extension PlayingCard: Equatable {}
public func <(lhs: PlayingCard, rhs: PlayingCard) -> Bool {
return lhs.rank == rhs.rank ? lhs.suit < rhs.suit : lhs.rank < rhs.rank
}
extension PlayingCard: Comparable {}
extension PlayingCard : CustomStringConvertible {
public var description: String {
return "\(suit)\(rank)"
}
}
public struct Deck {
private var cards: [PlayingCard]
public static func standard52CardDeck() -> Deck {
let suits: [Suit] = [.spades, .hearts, .diamonds, .clubs]
let ranks: [Rank] = [.two, .three, .four, .five, .six, .seven, .eight, .nine, .ten, .jack, .queen, .king, .ace]
var cards: [PlayingCard] = []
for rank in ranks {
for suit in suits {
cards.append(PlayingCard(rank: rank, suit: suit))
}
}
return Deck(cards)
}
public init(_ cards: [PlayingCard]) {
self.cards = cards
}
public mutating func shuffle() {
cards.shuffle()
}
public mutating func deal() -> PlayingCard? {
guard !cards.isEmpty else { return nil }
return cards.removeLast()
}
}
extension Deck : ArrayLiteralConvertible {
public init(arrayLiteral elements: PlayingCard...) {
self.init(elements)
}
}
public func ==(lhs: Deck, rhs: Deck) -> Bool {
return lhs.cards == rhs.cards
}
extension Deck : Equatable {}
let numberOfCards = 55
var deck = Deck.standard52CardDeck()
deck.shuffle()
var output: [PlayingCard] = []
for _ in 0..<numberOfCards {
guard let card = deck.deal() else {
print("No More Cards!")
break
}
output.append(card)
}
output
| mit | df5e07c7cd995a3f58692e303fe87074 | 20.752809 | 119 | 0.573605 | 3.837463 | false | false | false | false |
flodolo/firefox-ios | Client/Frontend/Reader/ReaderMode.swift | 1 | 11799 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import Foundation
import Shared
import WebKit
private let log = Logger.browserLogger
let ReaderModeProfileKeyStyle = "readermode.style"
enum ReaderModeMessageType: String {
case stateChange = "ReaderModeStateChange"
case pageEvent = "ReaderPageEvent"
case contentParsed = "ReaderContentParsed"
}
enum ReaderPageEvent: String {
case pageShow = "PageShow"
}
enum ReaderModeState: String {
case available = "Available"
case unavailable = "Unavailable"
case active = "Active"
}
enum ReaderModeTheme: String {
case light = "light"
case dark = "dark"
case sepia = "sepia"
static func preferredTheme(for theme: ReaderModeTheme? = nil) -> ReaderModeTheme {
// If there is no reader theme provided than we default to light theme
let readerTheme = theme ?? .light
// Get current Firefox theme (Dark vs Normal)
// Normal means light theme. This is the overall theme used
// by Firefox iOS app
let appWideTheme = LegacyThemeManager.instance.currentName
// We check for 3 basic themes we have Light / Dark / Sepia
// Theme: Dark - app-wide dark overrides all
if appWideTheme == .dark {
return .dark
// Theme: Sepia - special case for when the theme is sepia.
// For this we only check the them supplied and not the app wide theme
} else if readerTheme == .sepia {
return .sepia
}
// Theme: Light - Default case for when there is no theme supplied i.e. nil and we revert to light
return readerTheme
}
}
private struct FontFamily {
static let serifFamily = [ReaderModeFontType.serif, ReaderModeFontType.serifBold]
static let sansFamily = [ReaderModeFontType.sansSerif, ReaderModeFontType.sansSerifBold]
static let families = [serifFamily, sansFamily]
}
enum ReaderModeFontType: String {
case serif = "serif"
case serifBold = "serif-bold"
case sansSerif = "sans-serif"
case sansSerifBold = "sans-serif-bold"
init(type: String) {
let font = ReaderModeFontType(rawValue: type)
let isBoldFontEnabled = UIAccessibility.isBoldTextEnabled
switch font {
case .serif,
.serifBold:
self = isBoldFontEnabled ? .serifBold : .serif
case .sansSerif,
.sansSerifBold:
self = isBoldFontEnabled ? .sansSerifBold : .sansSerif
case .none:
self = .sansSerif
}
}
func isSameFamily(_ font: ReaderModeFontType) -> Bool {
return FontFamily.families.contains(where: { $0.contains(font) && $0.contains(self) })
}
}
enum ReaderModeFontSize: Int {
case size1 = 1
case size2 = 2
case size3 = 3
case size4 = 4
case size5 = 5
case size6 = 6
case size7 = 7
case size8 = 8
case size9 = 9
case size10 = 10
case size11 = 11
case size12 = 12
case size13 = 13
func isSmallest() -> Bool {
return self == ReaderModeFontSize.size1
}
func smaller() -> ReaderModeFontSize {
if isSmallest() {
return self
} else {
return ReaderModeFontSize(rawValue: self.rawValue - 1)!
}
}
func isLargest() -> Bool {
return self == ReaderModeFontSize.size13
}
static var defaultSize: ReaderModeFontSize {
switch UIApplication.shared.preferredContentSizeCategory {
case .extraSmall:
return .size1
case .small:
return .size2
case .medium:
return .size3
case .large:
return .size5
case .extraLarge:
return .size7
case .extraExtraLarge:
return .size9
case .extraExtraExtraLarge:
return .size12
default:
return .size5
}
}
func bigger() -> ReaderModeFontSize {
if isLargest() {
return self
} else {
return ReaderModeFontSize(rawValue: self.rawValue + 1)!
}
}
}
struct ReaderModeStyle {
var theme: ReaderModeTheme
var fontType: ReaderModeFontType
var fontSize: ReaderModeFontSize
/// Encode the style to a JSON dictionary that can be passed to ReaderMode.js
func encode() -> String {
return encodeAsDictionary().asString ?? ""
}
/// Encode the style to a dictionary that can be stored in the profile
func encodeAsDictionary() -> [String: Any] {
return ["theme": theme.rawValue, "fontType": fontType.rawValue, "fontSize": fontSize.rawValue]
}
init(theme: ReaderModeTheme, fontType: ReaderModeFontType, fontSize: ReaderModeFontSize) {
self.theme = theme
self.fontType = fontType
self.fontSize = fontSize
}
/// Initialize the style from a dictionary, taken from the profile. Returns nil if the object cannot be decoded.
init?(dict: [String: Any]) {
let themeRawValue = dict["theme"] as? String
let fontTypeRawValue = dict["fontType"] as? String
let fontSizeRawValue = dict["fontSize"] as? Int
if themeRawValue == nil || fontTypeRawValue == nil || fontSizeRawValue == nil {
return nil
}
let theme = ReaderModeTheme(rawValue: themeRawValue!)
let fontType = ReaderModeFontType(type: fontTypeRawValue!)
let fontSize = ReaderModeFontSize(rawValue: fontSizeRawValue!)
if theme == nil || fontSize == nil {
return nil
}
self.theme = theme ?? ReaderModeTheme.preferredTheme()
self.fontType = fontType
self.fontSize = fontSize!
}
mutating func ensurePreferredColorThemeIfNeeded() {
self.theme = ReaderModeTheme.preferredTheme(for: self.theme)
}
}
let DefaultReaderModeStyle = ReaderModeStyle(theme: .light, fontType: .sansSerif, fontSize: ReaderModeFontSize.defaultSize)
/// This struct captures the response from the Readability.js code.
struct ReadabilityResult {
var domain = ""
var url = ""
var content = ""
var textContent = ""
var title = ""
var credits = ""
var excerpt = ""
init?(object: AnyObject?) {
if let dict = object as? NSDictionary {
if let uri = dict["uri"] as? NSDictionary {
if let url = uri["spec"] as? String {
self.url = url
}
if let host = uri["host"] as? String {
self.domain = host
}
}
if let content = dict["content"] as? String {
self.content = content
}
if let textContent = dict["textContent"] as? String {
self.textContent = textContent
}
if let excerpt = dict["excerpt"] as? String {
self.excerpt = excerpt
}
if let title = dict["title"] as? String {
self.title = title
}
if let credits = dict["byline"] as? String {
self.credits = credits
}
} else {
return nil
}
}
/// Initialize from a JSON encoded string
init?(string: String) {
guard let data = string.data(using: .utf8),
let object = try? JSONSerialization.jsonObject(with: data, options: .fragmentsAllowed) as? [String: String] else { return nil }
let domain = object["domain"]
let url = object["url"]
let content = object["content"]
let textContent = object["textContent"]
let excerpt = object["excerpt"]
let title = object["title"]
let credits = object["credits"]
if domain == nil || url == nil || content == nil || title == nil || credits == nil {
return nil
}
self.domain = domain!
self.url = url!
self.content = content!
self.title = title!
self.credits = credits!
self.textContent = textContent ?? ""
self.excerpt = excerpt ?? ""
}
/// Encode to a dictionary, which can then for example be json encoded
func encode() -> [String: Any] {
return ["domain": domain, "url": url, "content": content, "title": title, "credits": credits, "textContent": textContent, "excerpt": excerpt]
}
/// Encode to a JSON encoded string
func encode() -> String {
let dict: [String: Any] = self.encode()
return dict.asString!
}
}
/// Delegate that contains callbacks that we have added on top of the built-in WKWebViewDelegate
protocol ReaderModeDelegate: AnyObject {
func readerMode(_ readerMode: ReaderMode, didChangeReaderModeState state: ReaderModeState, forTab tab: Tab)
func readerMode(_ readerMode: ReaderMode, didDisplayReaderizedContentForTab tab: Tab)
func readerMode(_ readerMode: ReaderMode, didParseReadabilityResult readabilityResult: ReadabilityResult, forTab tab: Tab)
}
let ReaderModeNamespace = "window.__firefox__.reader"
class ReaderMode: TabContentScript {
weak var delegate: ReaderModeDelegate?
fileprivate weak var tab: Tab?
var state = ReaderModeState.unavailable
fileprivate var originalURL: URL?
class func name() -> String {
return "ReaderMode"
}
required init(tab: Tab) {
self.tab = tab
}
func scriptMessageHandlerName() -> String? {
return "readerModeMessageHandler"
}
fileprivate func handleReaderPageEvent(_ readerPageEvent: ReaderPageEvent) {
switch readerPageEvent {
case .pageShow:
if let tab = tab {
delegate?.readerMode(self, didDisplayReaderizedContentForTab: tab)
}
}
}
fileprivate func handleReaderModeStateChange(_ state: ReaderModeState) {
self.state = state
guard let tab = tab else { return }
delegate?.readerMode(self, didChangeReaderModeState: state, forTab: tab)
}
fileprivate func handleReaderContentParsed(_ readabilityResult: ReadabilityResult) {
guard let tab = tab else { return }
log.info("ReaderMode: Readability result available!")
tab.readabilityResult = readabilityResult
delegate?.readerMode(self, didParseReadabilityResult: readabilityResult, forTab: tab)
}
func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
guard let msg = message.body as? [String: Any],
let type = msg["Type"] as? String,
let messageType = ReaderModeMessageType(rawValue: type)
else { return }
switch messageType {
case .pageEvent:
if let readerPageEvent = ReaderPageEvent(rawValue: msg["Value"] as? String ?? "Invalid") {
handleReaderPageEvent(readerPageEvent)
}
case .stateChange:
if let readerModeState = ReaderModeState(rawValue: msg["Value"] as? String ?? "Invalid") {
handleReaderModeStateChange(readerModeState)
}
case .contentParsed:
if let readabilityResult = ReadabilityResult(object: msg["Value"] as AnyObject?) {
handleReaderContentParsed(readabilityResult)
}
}
}
var style: ReaderModeStyle = DefaultReaderModeStyle {
didSet {
if state == ReaderModeState.active {
tab?.webView?.evaluateJavascriptInDefaultContentWorld("\(ReaderModeNamespace).setStyle(\(style.encode()))") { object, error in
return
}
}
}
}
}
| mpl-2.0 | 0a254bb53de4f01368ade9fbceed27cd | 32.143258 | 149 | 0.614883 | 4.976381 | false | false | false | false |
tottokotkd/ColorPack | ColorPack/src/iOS/UIColor.swift | 1 | 483 | //
// File.swift
// ColorPack
//
// Created by Shusuke Tokuda on 2016/10/22.
//
//
import UIKit
extension ColorProtocol {
public var toUIColor: UIColor {
let (r, g, b) = toDoubleRGBData
let red = r / percentageMax
let green = g / percentageMax
let blue = b / percentageMax
let newAlpha = alpha / percentageMax
return UIColor(colorLiteralRed: Float(red), green: Float(green), blue: Float(blue), alpha: Float(newAlpha))
}
}
| mit | 3b44225c7c7f303e596cf4691d0d2125 | 23.15 | 115 | 0.627329 | 3.926829 | false | false | false | false |
ufogxl/MySQLTest | Sources/Time.swift | 1 | 3802 | //
// getTime.swift
// GoodStudent
//
// Created by ufogxl on 2016/11/26.
//
//
import Foundation
//用来标示时间的全局变量
var time = Time()
struct Time{
var numberOfWeek:Int!
var numberOfClass:Int!
var presentedTime:String!
var date:Date!
init() {
numberOfWeek = 1
numberOfClass = 1
presentedTime = "2016年9月12日 星期一"
date = getStartTime(date: "2016-09-12 00:00:00")
}
}
func getClassTime(which: Int) -> String{
switch which%5 {
case 1:
return "8:05-9:40"
case 2:
return "10:00-12:25"
case 3:
return "13:30-15:05"
case 4:
return "15:15-16:35"
case 0:
return "18:30-20:00"
default:
return "未知"
}
}
func getStartTime(date:String) -> Date?{
//假设本学期第一周的周一为初始时间
let formatter = DateFormatter()
formatter.dateFormat = "yyy-MM-dd HH:mm:ss"
let START_TIME = formatter.date(from: date)
return Date(timeInterval: TimeInterval(NSTimeZone.system.secondsFromGMT(for: START_TIME!)), since: START_TIME!)
}
func getExamTime(_ examNumber:Int) -> String{
let day = examNumber/3
let interVal = day * 24 * 3600
let examDay = Date(timeInterval: TimeInterval(interVal), since: getStartTime(date: "2017-01-02 00:00:00")!)
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let dayString = formatter.string(from: examDay as Date)
var timeString = ""
switch examNumber%3{
case 0:
timeString = "18:00-20:00"
case 1:
timeString = "9:00-11:00"
case 2:
timeString = "15:00-17:00"
default:
timeString = "未知"
}
return dayString + " " + timeString
}
func getWhichExam() -> Int{
let interval = Int(time.date.timeIntervalSince(getStartTime(date: "2017-01-02 00:00:00")!)) + 8 * 3600
let dayCount = interval / 24 / 3600
let minCount = interval / 60 - dayCount * 24 * 60
let base = dayCount * 3
switch minCount{
case 0..<11 * 60:
return base + 1
case 11 * 60..<17 * 60:
return base + 2
case 17 * 60..<20 * 60:
return base + 3
default:
return base + 4
}
}
func setTime(_ inputDate:String) -> Bool{
let formatter = DateFormatter()
formatter.dateFormat = "yyy-MM-dd HH:mm:ss"
formatter.timeZone = NSTimeZone.system
if let date = formatter.date(from: inputDate){
let interval = Int(date.timeIntervalSince(getStartTime(date: "2016-09-12 00:00:00")!)) + 8 * 3600
//总分钟数
let min = interval/60
//总小时数
let h = min/60
//总天数
let day = h/24
var numberOfClass = 0
let basic = day % 7 * 5
switch day % 7{
case 0...4:
switch h % 24 * 60 + min % 60 {
case 0..<9 * 60 + 40:
numberOfClass = basic + 1
case 9 * 60 + 40..<12 * 60 + 25:
numberOfClass = basic + 2
case 12 * 60 + 25..<15 * 60 + 5:
numberOfClass = basic + 3
case 15 * 60 + 5..<16 * 60 + 45:
numberOfClass = basic + 4
case 16 * 60 + 45..<20 * 60 + 5:
numberOfClass = basic + 5
default:
numberOfClass = 26
}
default:
numberOfClass = 26
}
let description = date.description(with: Locale(identifier: "zh"))
let array = description.components(separatedBy: " ")
time.numberOfWeek = day/7 + 1
time.numberOfClass = numberOfClass
time.presentedTime = array[0] + " " + array[1]
time.date = date
return true
}else{
return false
}
}
| apache-2.0 | 78be08707e58be91c4b551a949464f7d | 24.916084 | 115 | 0.549649 | 3.601555 | false | false | false | false |
instacrate/tapcrate-api | Sources/api/Controllers/DescriptionCollection.swift | 1 | 1959 | //
// DescriptionController.swift
// polymr-api
//
// Created by Hakon Hanesand on 3/19/17.
//
//
import Vapor
import HTTP
import Fluent
import FluentProvider
import Routing
import Node
import JWT
import AuthProvider
import Foundation
fileprivate func handle(upload request: Request, for product: Int) throws -> String {
guard let data = request.formData?.first?.value.part.body else {
throw Abort.custom(status: .badRequest, message: "No file in request")
}
return try save(data: Data(bytes: data), for: product)
}
func save(data: Data, for product: Int) throws -> String {
let descriptionFolder = "Public/descriptions"
let saveURL = URL(fileURLWithPath: drop.config.workDir)
.appendingPathComponent(descriptionFolder, isDirectory: true)
.appendingPathComponent("\(product).json", isDirectory: false)
do {
try data.write(to: saveURL)
} catch {
throw Abort.custom(status: .internalServerError, message: "Unable to write multipart form data to file. Underlying error \(error)")
}
return "https://static.tapcrate.com/descriptions/\(product).json"
}
final class DescriptionCollection: RouteCollection, EmptyInitializable {
init() {
}
func build(_ builder: RouteBuilder) {
builder.grouped("descriptions").get(String.parameter) { request in
let product = try request.parameters.next(String.self)
return "https://static.tapcrate.com/descriptions/\(product)"
}
builder.grouped("descriptions").patch(String.parameter) { request in
let product = try request.parameters.next(String.self)
guard let product_id = Int(product) else {
throw Abort.custom(status: .badRequest, message: "Invalid product id")
}
return try handle(upload: request, for: product_id)
}
}
}
| mit | 01e681932ce450811f188ab96bae33fa | 28.238806 | 139 | 0.646759 | 4.472603 | false | false | false | false |
SusanDoggie/DoggieGP | Sources/OpenCL/clCommandQueue.swift | 1 | 6040 | //
// clCommandQueue.swift
//
// The MIT License
// Copyright (c) 2015 - 2018 Susan Cheng. 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 OpenCL
import Dispatch
extension OpenCL {
public final class CommandQueue : CommandQueueProtocol {
let device: OpenCL.Device
let queue: cl_command_queue
fileprivate var mem_obj: [cl_mem] = []
init(device: OpenCL.Device, queue: cl_command_queue) {
self.device = device
self.queue = queue
}
deinit {
clReleaseCommandQueue(queue)
for mem in mem_obj {
clReleaseMemObject(mem)
}
}
}
public final class CommandContext : CommandContextProtocol {
public typealias Library = OpenCL.Library
let queue: CommandQueue
var last_event: cl_event?
fileprivate init(queue: CommandQueue) {
self.queue = queue
self.last_event = nil
}
}
}
private class clEventNotify {
let notify: () -> Void
init(notify: @escaping () -> Void) {
self.notify = notify
}
}
extension OpenCL.CommandQueue {
private func _commit(body: (OpenCL.CommandContext) throws -> Void) rethrows -> cl_event? {
let buffer = OpenCL.CommandContext(queue: self)
try body(buffer)
clFlush(queue)
return buffer.last_event
}
public func commit(body: (OpenCL.CommandContext) throws -> Void) rethrows {
if let event = try _commit(body: body) {
var event: cl_event? = event
clWaitForEvents(1, &event)
clReleaseEvent(event)
}
}
public func commit(body: (OpenCL.CommandContext) throws -> Void, queue: DispatchQueue = DispatchQueue.main, qos: DispatchQoS = .unspecified, flags: DispatchWorkItemFlags = [], completed: @escaping (OpenCL.CommandQueue) -> Void) rethrows {
if let event = try _commit(body: body) {
let notify = clEventNotify() { queue.async(execute: DispatchWorkItem(qos: qos, flags: flags) { completed(self) }) }
let error = clSetEventCallback(event, CL_COMPLETE, { Unmanaged<clEventNotify>.fromOpaque(UnsafeRawPointer($2)!).takeRetainedValue().notify() }, Unmanaged.passRetained(notify).toOpaque())
guard error == CL_SUCCESS else { fatalError("clSetEventCallback failed: \(error)") }
clReleaseEvent(event)
}
}
}
extension OpenCL.CommandContext {
public func perform(threadgroups: DGPSize, threadsPerThreadgroup: DGPSize, function: OpenCL.Function, _ buffers: BufferProtocol ...) {
precondition(threadgroups.dimension == threadsPerThreadgroup.dimension, "dimensions not same.")
let kernel = function.kernel
for (index, buffer) in buffers.enumerated() {
buffer.withUnsafeBytes { buf in
var error: cl_int = 0
let _buffer = clCreateBuffer(queue.device.platform._context, numericCast(CL_MEM_READ_WRITE | CL_MEM_USE_HOST_PTR), buf.count.align(Int(getpagesize())), UnsafeMutableRawPointer(mutating: buf.baseAddress), &error)
guard error == CL_SUCCESS else { fatalError("clCreateBuffer failed: \(error)") }
guard var buffer = _buffer else { fatalError("clCreateBuffer failed: \(error)") }
error = clSetKernelArg(kernel, cl_uint(index), MemoryLayout<cl_mem>.size, &buffer)
guard error == CL_SUCCESS else { fatalError("clSetKernelArg failed: \(error)") }
queue.mem_obj.append(buffer)
}
}
let _threads_global = [threadgroups.width * threadsPerThreadgroup.width, threadgroups.height * threadsPerThreadgroup.height, threadgroups.depth * threadsPerThreadgroup.depth]
let _threads_local = [threadsPerThreadgroup.width, threadsPerThreadgroup.height, threadsPerThreadgroup.depth]
if let last = last_event {
var last: cl_event? = last
let error = clEnqueueNDRangeKernel(queue.queue, kernel, numericCast(threadgroups.dimension), nil, _threads_global, _threads_local, 1, &last, &last_event)
clReleaseEvent(last)
guard error == CL_SUCCESS else { fatalError("clEnqueueNDRangeKernel failed: \(error)") }
} else {
let error = clEnqueueNDRangeKernel(queue.queue, kernel, numericCast(threadgroups.dimension), nil, _threads_global, _threads_local, 0, nil, &last_event)
guard error == CL_SUCCESS else { fatalError("clEnqueueNDRangeKernel failed: \(error)") }
}
}
}
| mit | 5e73e7ceacbfa17c89cb2c4527987d1e | 37.471338 | 242 | 0.615232 | 4.715066 | false | false | false | false |
monisun/warble | Warble/ComposeTweetViewController.swift | 1 | 7175 | //
// ComposeTweetViewController.swift
// Warble
//
// Created by Monica Sun on 5/22/15.
// Copyright (c) 2015 Monica Sun. All rights reserved.
//
import UIKit
class ComposeTweetViewController: UIViewController, UITextViewDelegate {
var user = User(dict: NSDictionary())
var replyToTweetId: Int?
var tweetTextPrefix: String?
@IBOutlet weak var profileImage: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var screenname: UILabel!
@IBOutlet weak var characterCounterLabel: UILabel!
@IBOutlet weak var tweetTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
tweetTextView.delegate = self
if let userName = user.name as String? {
if userName.isEmpty {
NSLog("Current logged in user was not properly initialized in ComposeTweetViewController! User name is empty.")
} else {
// properly initialized; populate compose view
profileImage.setImageWithURL(NSURL(string: user.profileImageUrl!))
profileImage.contentMode = UIViewContentMode.ScaleAspectFill
profileImage.frame.size.width = 30
profileImage.frame.size.height = 30
profileImage.layer.cornerRadius = 5
nameLabel.text = user.name
screenname.text = "@" + (user.username as String!)
characterCounterLabel.text = "140"
// styling
nameLabel.textAlignment = NSTextAlignment.Left
nameLabel.font = UIFont(name: "HelveticaNeue", size: 14)
nameLabel.numberOfLines = 1
screenname.textAlignment = NSTextAlignment.Left
screenname.font = UIFont(name: "HelveticaNeue", size: 12)
screenname.textColor = UIColor.darkGrayColor()
screenname.numberOfLines = 1
characterCounterLabel.textAlignment = NSTextAlignment.Right
characterCounterLabel.font = UIFont(name: "HelveticaNeue", size: 12)
characterCounterLabel.textColor = UIColor.darkGrayColor()
characterCounterLabel.numberOfLines = 1
}
} else {
NSLog("Current logged in user was not properly initialized in ComposeTweetViewController! User name is nil.")
}
if let prefix = tweetTextPrefix as String? {
tweetTextView.text = prefix
} else {
tweetTextView.text = ""
}
// tweetTextView.clearsOnInsertion = true
tweetTextView.layer.cornerRadius = 10
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// TODO doesn't seem to do anything??
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
view.endEditing(true)
super.touchesBegan(touches as Set<NSObject>, withEvent: event)
}
@IBAction func onTweetButtonClick(sender: AnyObject) {
let emptyTweetAlert = UIAlertController(title: "Empty Tweet", message: "Tweets cannot be empty!", preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)
emptyTweetAlert.addAction(okAction)
// validate tweet
if let tweetText = tweetTextView.text as String? {
if tweetText.isEmpty {
self.presentViewController(emptyTweetAlert, animated: false, completion: nil)
} else {
// TODO further validation? if replyToTweetId is not nil, then tweet text must contain "@username" of referenced tweet.
// save tweet
SVProgressHUD.showProgress(1, status: "Loading...")
TwitterClient.sharedInstance.tweetWithStatus(tweetText, replyToTweetId: replyToTweetId, completion: { (result, error) -> () in
if error != nil {
SVProgressHUD.dismiss()
NSLog("ERROR: TwitterClient.sharedInstance.tweetWithStatus: \(error)")
} else {
NSLog("Successfully posted new tweet.")
SVProgressHUD.showSuccessWithStatus("Success")
if let replyId = self.replyToTweetId as Int? {
// nav back to show tweet VC
self.dismissViewControllerAnimated(true, completion: nil)
} else {
// nav back to home timeline
let tweetViewController = self.presentingViewController as! TweetsViewController!
// TODO reloadData() did not always refresh correctly, as tweets[] was already populated before new tweet got to home timeline (?)
// tweetViewController.tableView.reloadData()
SVProgressHUD.showProgress(1, status: "Loading...")
TwitterClient.sharedInstance.homeTimelineWithParams(nil, maxId: nil, completion: { (tweets, minId, error) -> () in
if error != nil {
SVProgressHUD.dismiss()
NSLog("ERROR: TwitterClient.sharedInstance.homeTimelineWithParams: \(error)")
} else {
tweetViewController.tweets = tweets!
tweetViewController.tableView.reloadData()
tweetViewController.minId = minId
SVProgressHUD.showSuccessWithStatus("Success")
// segue back to main page
self.performSegueWithIdentifier("tweetDoneSegue", sender: self)
}
})
}
}
})
}
} else {
NSLog("UNEXPECTED: tweetText is nil")
}
}
@IBAction func onCancelButtonClicked(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
return count(tweetTextView.text) + (count(text) - range.length) <= 140
}
func textViewDidChange(sender: UITextView) {
if let charCount = count(tweetTextView.text) as Int? {
let remaining = 140 - charCount
characterCounterLabel.text = "\(remaining)"
}
}
// 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?) {
}
}
| mit | 9bfa7099ad3e30dbc92987479054789a | 44.125786 | 158 | 0.567387 | 6.059966 | false | false | false | false |
nathantannar4/NTComponents | NTComponents Demo/MaterialColors.swift | 1 | 16556 | //
// MaterialColors.swift
// NTComponents
//
// Created by Nathan Tannar on 4/15/17.
// Copyright © 2017 Nathan Tannar. All rights reserved.
//
import NTComponents
protocol PropertyLoopable
{
func allProperties() throws -> [String: Any]
}
extension PropertyLoopable
{
func allProperties() throws -> [String: Any] {
var result: [String: Any] = [:]
let mirror = Mirror(reflecting: self)
for (labelMaybe, valueMaybe) in mirror.children {
guard let label = labelMaybe else {
continue
}
result[label] = valueMaybe
}
return result
}
}
struct MaterialColors {
func all() -> [UIColor] {
let all = try! All().allProperties()
var colors = [UIColor]()
for (_, value) in all {
if let subcolors = value as? [String : Any] {
for (_, color) in subcolors {
colors.append(color as! UIColor)
}
} else {
print("fail")
}
}
return colors
}
struct All: PropertyLoopable {
let red = try! Red().allProperties()
let pink = try! Pink().allProperties()
let purple = try! Purple().allProperties()
let deeppurple = try! DeepPurple().allProperties()
let indigo = try! Indigo().allProperties()
let blue = try! Blue().allProperties()
let lightblue = try! LightBlue().allProperties()
let cyan = try! Cyan().allProperties()
let teal = try! Teal().allProperties()
let green = try! Green().allProperties()
let lightgreen = try! LightGreen().allProperties()
let lime = try! Lime().allProperties()
let yellow = try! Yellow().allProperties()
let amber = try! Amber().allProperties()
let orange = try! Orange().allProperties()
let deeporange = try! DeepOrange().allProperties()
let brown = try! Brown().allProperties()
let gray = try! Gray().allProperties()
let bluegray = try! BlueGray().allProperties()
}
public struct Red: PropertyLoopable {
public let P50 = UIColor(rgba: 0xFDE0DCFF)
public let P100 = UIColor(rgba: 0xF9BDBBFF)
public let P200 = UIColor(rgba: 0xF69988FF)
public let P300 = UIColor(rgba: 0xF36C60FF)
public let P400 = UIColor(rgba: 0xE84E40FF)
public let P500 = UIColor(rgba: 0xE51C23FF)
public let P600 = UIColor(rgba: 0xDD191DFF)
public let P700 = UIColor(rgba: 0xD01716FF)
public let P800 = UIColor(rgba: 0xC41411FF)
public let P900 = UIColor(rgba: 0xB0120AFF)
public let A100 = UIColor(rgba: 0xFF7997FF)
public let A200 = UIColor(rgba: 0xFF5177FF)
public let A400 = UIColor(rgba: 0xFF2D6FFF)
public let A700 = UIColor(rgba: 0xE00032FF)
}
public struct Pink: PropertyLoopable {
public let P50 = UIColor(rgba: 0xFCE4ECFF)
public let P100 = UIColor(rgba: 0xF8BBD0FF)
public let P200 = UIColor(rgba: 0xF48FB1FF)
public let P300 = UIColor(rgba: 0xF06292FF)
public let P400 = UIColor(rgba: 0xEC407AFF)
public let P500 = UIColor(rgba: 0xE91E63FF)
public let P600 = UIColor(rgba: 0xD81B60FF)
public let P700 = UIColor(rgba: 0xC2185BFF)
public let P800 = UIColor(rgba: 0xAD1457FF)
public let P900 = UIColor(rgba: 0x880E4FFF)
public let A100 = UIColor(rgba: 0xFF80ABFF)
public let A200 = UIColor(rgba: 0xFF4081FF)
public let A400 = UIColor(rgba: 0xF50057FF)
public let A700 = UIColor(rgba: 0xC51162FF)
}
public struct Purple: PropertyLoopable {
public let P50 = UIColor(rgba: 0xF3E5F5FF)
public let P100 = UIColor(rgba: 0xE1BEE7FF)
public let P200 = UIColor(rgba: 0xCE93D8FF)
public let P300 = UIColor(rgba: 0xBA68C8FF)
public let P400 = UIColor(rgba: 0xAB47BCFF)
public let P500 = UIColor(rgba: 0x9C27B0FF)
public let P600 = UIColor(rgba: 0x8E24AAFF)
public let P700 = UIColor(rgba: 0x7B1FA2FF)
public let P800 = UIColor(rgba: 0x6A1B9AFF)
public let P900 = UIColor(rgba: 0x4A148CFF)
public let A100 = UIColor(rgba: 0xEA80FCFF)
public let A200 = UIColor(rgba: 0xE040FBFF)
public let A400 = UIColor(rgba: 0xD500F9FF)
public let A700 = UIColor(rgba: 0xAA00FFFF)
}
public struct DeepPurple: PropertyLoopable {
public let P50 = UIColor(rgba: 0xEDE7F6FF)
public let P100 = UIColor(rgba: 0xD1C4E9FF)
public let P200 = UIColor(rgba: 0xB39DDBFF)
public let P300 = UIColor(rgba: 0x9575CDFF)
public let P400 = UIColor(rgba: 0x7E57C2FF)
public let P500 = UIColor(rgba: 0x673AB7FF)
public let P600 = UIColor(rgba: 0x5E35B1FF)
public let P700 = UIColor(rgba: 0x512DA8FF)
public let P800 = UIColor(rgba: 0x4527A0FF)
public let P900 = UIColor(rgba: 0x311B92FF)
public let A100 = UIColor(rgba: 0xB388FFFF)
public let A200 = UIColor(rgba: 0x7C4DFFFF)
public let A400 = UIColor(rgba: 0x651FFFFF)
public let A700 = UIColor(rgba: 0x6200EAFF)
}
public struct Indigo: PropertyLoopable {
public let P50 = UIColor(rgba: 0xE8EAF6FF)
public let P100 = UIColor(rgba: 0xC5CAE9FF)
public let P200 = UIColor(rgba: 0x9FA8DAFF)
public let P300 = UIColor(rgba: 0x7986CBFF)
public let P400 = UIColor(rgba: 0x5C6BC0FF)
public let P500 = UIColor(rgba: 0x3F51B5FF)
public let P600 = UIColor(rgba: 0x3949ABFF)
public let P700 = UIColor(rgba: 0x303F9FFF)
public let P800 = UIColor(rgba: 0x283593FF)
public let P900 = UIColor(rgba: 0x1A237EFF)
public let A100 = UIColor(rgba: 0x8C9EFFFF)
public let A200 = UIColor(rgba: 0x536DFEFF)
public let A400 = UIColor(rgba: 0x3D5AFEFF)
public let A700 = UIColor(rgba: 0x304FFEFF)
}
public struct Blue: PropertyLoopable {
public let P50 = UIColor(rgba: 0xE7E9FDFF)
public let P100 = UIColor(rgba: 0xD0D9FFFF)
public let P200 = UIColor(rgba: 0xAFBFFFFF)
public let P300 = UIColor(rgba: 0x91A7FFFF)
public let P400 = UIColor(rgba: 0x738FFEFF)
public let P500 = UIColor(rgba: 0x5677FCFF)
public let P600 = UIColor(rgba: 0x4E6CEFFF)
public let P700 = UIColor(rgba: 0x455EDEFF)
public let P800 = UIColor(rgba: 0x3B50CEFF)
public let P900 = UIColor(rgba: 0x2A36B1FF)
public let A100 = UIColor(rgba: 0xA6BAFFFF)
public let A200 = UIColor(rgba: 0x6889FFFF)
public let A400 = UIColor(rgba: 0x4D73FFFF)
public let A700 = UIColor(rgba: 0x4D69FFFF)
}
public struct LightBlue: PropertyLoopable {
public let P50 = UIColor(rgba: 0xE1F5FEFF)
public let P100 = UIColor(rgba: 0xB3E5FCFF)
public let P200 = UIColor(rgba: 0x81D4FAFF)
public let P300 = UIColor(rgba: 0x4FC3F7FF)
public let P400 = UIColor(rgba: 0x29B6F6FF)
public let P500 = UIColor(rgba: 0x03A9F4FF)
public let P600 = UIColor(rgba: 0x039BE5FF)
public let P700 = UIColor(rgba: 0x0288D1FF)
public let P800 = UIColor(rgba: 0x0277BDFF)
public let P900 = UIColor(rgba: 0x01579BFF)
public let A100 = UIColor(rgba: 0x80D8FFFF)
public let A200 = UIColor(rgba: 0x40C4FFFF)
public let A400 = UIColor(rgba: 0x00B0FFFF)
public let A700 = UIColor(rgba: 0x0091EAFF)
}
public struct Cyan: PropertyLoopable {
public let P50 = UIColor(rgba: 0xE0F7FAFF)
public let P100 = UIColor(rgba: 0xB2EBF2FF)
public let P200 = UIColor(rgba: 0x80DEEAFF)
public let P300 = UIColor(rgba: 0x4DD0E1FF)
public let P400 = UIColor(rgba: 0x26C6DAFF)
public let P500 = UIColor(rgba: 0x00BCD4FF)
public let P600 = UIColor(rgba: 0x00ACC1FF)
public let P700 = UIColor(rgba: 0x0097A7FF)
public let P800 = UIColor(rgba: 0x00838FFF)
public let P900 = UIColor(rgba: 0x006064FF)
public let A100 = UIColor(rgba: 0x84FFFFFF)
public let A200 = UIColor(rgba: 0x18FFFFFF)
public let A400 = UIColor(rgba: 0x00E5FFFF)
public let A700 = UIColor(rgba: 0x00B8D4FF)
}
public struct Teal: PropertyLoopable {
public let P50 = UIColor(rgba: 0xE0F2F1FF)
public let P100 = UIColor(rgba: 0xB2DFDBFF)
public let P200 = UIColor(rgba: 0x80CBC4FF)
public let P300 = UIColor(rgba: 0x4DB6ACFF)
public let P400 = UIColor(rgba: 0x26A69AFF)
public let P500 = UIColor(rgba: 0x009688FF)
public let P600 = UIColor(rgba: 0x00897BFF)
public let P700 = UIColor(rgba: 0x00796BFF)
public let P800 = UIColor(rgba: 0x00695CFF)
public let P900 = UIColor(rgba: 0x004D40FF)
public let A100 = UIColor(rgba: 0xA7FFEBFF)
public let A200 = UIColor(rgba: 0x64FFDAFF)
public let A400 = UIColor(rgba: 0x1DE9B6FF)
public let A700 = UIColor(rgba: 0x00BFA5FF)
}
public struct Green: PropertyLoopable {
public let P50 = UIColor(rgba: 0xD0F8CEFF)
public let P100 = UIColor(rgba: 0xA3E9A4FF)
public let P200 = UIColor(rgba: 0x72D572FF)
public let P300 = UIColor(rgba: 0x42BD41FF)
public let P400 = UIColor(rgba: 0x2BAF2BFF)
public let P500 = UIColor(rgba: 0x259B24FF)
public let P600 = UIColor(rgba: 0x0A8F08FF)
public let P700 = UIColor(rgba: 0x0A7E07FF)
public let P800 = UIColor(rgba: 0x056F00FF)
public let P900 = UIColor(rgba: 0x0D5302FF)
public let A100 = UIColor(rgba: 0xA2F78DFF)
public let A200 = UIColor(rgba: 0x5AF158FF)
public let A400 = UIColor(rgba: 0x14E715FF)
public let A700 = UIColor(rgba: 0x12C700FF)
}
public struct LightGreen: PropertyLoopable {
public let P50 = UIColor(rgba: 0xF1F8E9FF)
public let P100 = UIColor(rgba: 0xDCEDC8FF)
public let P200 = UIColor(rgba: 0xC5E1A5FF)
public let P300 = UIColor(rgba: 0xAED581FF)
public let P400 = UIColor(rgba: 0x9CCC65FF)
public let P500 = UIColor(rgba: 0x8BC34AFF)
public let P600 = UIColor(rgba: 0x7CB342FF)
public let P700 = UIColor(rgba: 0x689F38FF)
public let P800 = UIColor(rgba: 0x558B2FFF)
public let P900 = UIColor(rgba: 0x33691EFF)
public let A100 = UIColor(rgba: 0xCCFF90FF)
public let A200 = UIColor(rgba: 0xB2FF59FF)
public let A400 = UIColor(rgba: 0x76FF03FF)
public let A700 = UIColor(rgba: 0x64DD17FF)
}
public struct Lime: PropertyLoopable {
public let P50 = UIColor(rgba: 0xF9FBE7FF)
public let P100 = UIColor(rgba: 0xF0F4C3FF)
public let P200 = UIColor(rgba: 0xE6EE9CFF)
public let P300 = UIColor(rgba: 0xDCE775FF)
public let P400 = UIColor(rgba: 0xD4E157FF)
public let P500 = UIColor(rgba: 0xCDDC39FF)
public let P600 = UIColor(rgba: 0xC0CA33FF)
public let P700 = UIColor(rgba: 0xAFB42BFF)
public let P800 = UIColor(rgba: 0x9E9D24FF)
public let P900 = UIColor(rgba: 0x827717FF)
public let A100 = UIColor(rgba: 0xF4FF81FF)
public let A200 = UIColor(rgba: 0xEEFF41FF)
public let A400 = UIColor(rgba: 0xC6FF00FF)
public let A700 = UIColor(rgba: 0xAEEA00FF)
}
public struct Yellow: PropertyLoopable {
public let P50 = UIColor(rgba: 0xFFFDE7FF)
public let P100 = UIColor(rgba: 0xFFF9C4FF)
public let P200 = UIColor(rgba: 0xFFF59DFF)
public let P300 = UIColor(rgba: 0xFFF176FF)
public let P400 = UIColor(rgba: 0xFFEE58FF)
public let P500 = UIColor(rgba: 0xFFEB3BFF)
public let P600 = UIColor(rgba: 0xFDD835FF)
public let P700 = UIColor(rgba: 0xFBC02DFF)
public let P800 = UIColor(rgba: 0xF9A825FF)
public let P900 = UIColor(rgba: 0xF57F17FF)
public let A100 = UIColor(rgba: 0xFFFF8DFF)
public let A200 = UIColor(rgba: 0xFFFF00FF)
public let A400 = UIColor(rgba: 0xFFEA00FF)
public let A700 = UIColor(rgba: 0xFFD600FF)
}
public struct Amber: PropertyLoopable {
public let P50 = UIColor(rgba: 0xFFF8E1FF)
public let P100 = UIColor(rgba: 0xFFECB3FF)
public let P200 = UIColor(rgba: 0xFFE082FF)
public let P300 = UIColor(rgba: 0xFFD54FFF)
public let P400 = UIColor(rgba: 0xFFCA28FF)
public let P500 = UIColor(rgba: 0xFFC107FF)
public let P600 = UIColor(rgba: 0xFFB300FF)
public let P700 = UIColor(rgba: 0xFFA000FF)
public let P800 = UIColor(rgba: 0xFF8F00FF)
public let P900 = UIColor(rgba: 0xFF6F00FF)
public let A100 = UIColor(rgba: 0xFFE57FFF)
public let A200 = UIColor(rgba: 0xFFD740FF)
public let A400 = UIColor(rgba: 0xFFC400FF)
public let A700 = UIColor(rgba: 0xFFAB00FF)
}
public struct Orange: PropertyLoopable {
public let P50 = UIColor(rgba: 0xFFF3E0FF)
public let P100 = UIColor(rgba: 0xFFE0B2FF)
public let P200 = UIColor(rgba: 0xFFCC80FF)
public let P300 = UIColor(rgba: 0xFFB74DFF)
public let P400 = UIColor(rgba: 0xFFA726FF)
public let P500 = UIColor(rgba: 0xFF9800FF)
public let P600 = UIColor(rgba: 0xFB8C00FF)
public let P700 = UIColor(rgba: 0xF57C00FF)
public let P800 = UIColor(rgba: 0xEF6C00FF)
public let P900 = UIColor(rgba: 0xE65100FF)
public let A100 = UIColor(rgba: 0xFFD180FF)
public let A200 = UIColor(rgba: 0xFFAB40FF)
public let A400 = UIColor(rgba: 0xFF9100FF)
public let A700 = UIColor(rgba: 0xFF6D00FF)
}
public struct DeepOrange: PropertyLoopable {
public let P50 = UIColor(rgba: 0xFBE9E7FF)
public let P100 = UIColor(rgba: 0xFFCCBCFF)
public let P200 = UIColor(rgba: 0xFFAB91FF)
public let P300 = UIColor(rgba: 0xFF8A65FF)
public let P400 = UIColor(rgba: 0xFF7043FF)
public let P500 = UIColor(rgba: 0xFF5722FF)
public let P600 = UIColor(rgba: 0xF4511EFF)
public let P700 = UIColor(rgba: 0xE64A19FF)
public let P800 = UIColor(rgba: 0xD84315FF)
public let P900 = UIColor(rgba: 0xBF360CFF)
public let A100 = UIColor(rgba: 0xFF9E80FF)
public let A200 = UIColor(rgba: 0xFF6E40FF)
public let A400 = UIColor(rgba: 0xFF3D00FF)
public let A700 = UIColor(rgba: 0xDD2C00FF)
}
public struct Brown: PropertyLoopable {
public let P50 = UIColor(rgba: 0xEFEBE9FF)
public let P100 = UIColor(rgba: 0xD7CCC8FF)
public let P200 = UIColor(rgba: 0xBCAAA4FF)
public let P300 = UIColor(rgba: 0xA1887FFF)
public let P400 = UIColor(rgba: 0x8D6E63FF)
public let P500 = UIColor(rgba: 0x795548FF)
public let P600 = UIColor(rgba: 0x6D4C41FF)
public let P700 = UIColor(rgba: 0x5D4037FF)
public let P800 = UIColor(rgba: 0x4E342EFF)
public let P900 = UIColor(rgba: 0x3E2723FF)
}
public struct Gray: PropertyLoopable {
public let P0 = UIColor(rgba: 0xFFFFFFFF)
public let P50 = UIColor(rgba: 0xFAFAFAFF)
public let P100 = UIColor(rgba: 0xF5F5F5FF)
public let P200 = UIColor(rgba: 0xEEEEEEFF)
public let P300 = UIColor(rgba: 0xE0E0E0FF)
public let P400 = UIColor(rgba: 0xBDBDBDFF)
public let P500 = UIColor(rgba: 0x9E9E9EFF)
public let P600 = UIColor(rgba: 0x757575FF)
public let P700 = UIColor(rgba: 0x616161FF)
public let P800 = UIColor(rgba: 0x424242FF)
public let P900 = UIColor(rgba: 0x212121FF)
public let P1000 = UIColor(rgba: 0x000000FF)
}
public struct BlueGray: PropertyLoopable {
public let P50 = UIColor(rgba: 0xECEFF1FF)
public let P100 = UIColor(rgba: 0xCFD8DCFF)
public let P200 = UIColor(rgba: 0xB0BEC5FF)
public let P300 = UIColor(rgba: 0x90A4AEFF)
public let P400 = UIColor(rgba: 0x78909CFF)
public let P500 = UIColor(rgba: 0x607D8BFF)
public let P600 = UIColor(rgba: 0x546E7AFF)
public let P700 = UIColor(rgba: 0x455A64FF)
public let P800 = UIColor(rgba: 0x37474FFF)
public let P900 = UIColor(rgba: 0x263238FF)
}
}
| mit | 5aff54066dab9596fee95c34a1ee9cb8 | 41.017766 | 58 | 0.635156 | 3.141366 | false | false | false | false |
Nukersson/Swift_iOS_Tutorial | FoodTracker/FoodTracker/MealViewController.swift | 1 | 5449 | //
// MealViewController.swift
// FoodTracker
//
// Created by nuke on 08.05.17.
// Copyright © 2017 nuke. All rights reserved.
//
import UIKit
import os.log
class MealViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate,
UINavigationControllerDelegate {
// MARK: Properties
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var photoImageView: UIImageView!
@IBOutlet weak var ratingControl: RatingControl!
@IBOutlet weak var saveButton: UIBarButtonItem!
/*
This value is either passed by `MealTableViewController` in `prepare(for:sender:)`
or constructed as part of adding a new meal.
*/
var meal: Meal?
// MARK: Overwritten functions
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Handle the text field’s user input through delegate callbacks.
nameTextField.delegate = self
// Set up views if editing an existing Meal.
if let meal = meal {
navigationItem.title = meal.name
nameTextField.text = meal.name
photoImageView.image = meal.photo
ratingControl.rating = meal.rating
}
// Enable the Save button only if the text field has a valid Meal name.
updateSaveButtonState()
}
/*
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
*/
// MARK: Actions
// MARK: UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// Hide the keyboard:
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
// Disable the Save button while editing.
// saveButton.isEnabled = false
updateSaveButtonState()
navigationItem.title = textField.text
}
//MARK: UIImagePickerControllerDelegate
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
// Dismiss the picker if the user canceled.
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : Any]) {
// The info dictionary may contain multiple representations of the image. You want to use the original.
guard let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {
fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
}
// Set photoImageView to display the selected image.
photoImageView.image = selectedImage
// Dismiss the picker.
dismiss(animated: true, completion: nil)
}
@IBAction func selectImageFromPhotoLibrary(_ sender: UITapGestureRecognizer) {
// Recognizes taps from photoImageView
// Hide the keyboard.
nameTextField.resignFirstResponder()
// UIImagePickerController is a view controller that lets a user
// pick media from their photo library.
let imagePickerController = UIImagePickerController()
// Only allow photos to be picked, not taken.
imagePickerController.sourceType = .photoLibrary
// Make sure ViewController is notified when the user picks an image.
imagePickerController.delegate = self
present(imagePickerController, animated: true, completion: nil)
}
// MARK: Navigation
// Cancel button
@IBAction func cancel(_ sender: UIBarButtonItem) {
// Depending on style of presentation (modal or push presentation),
// this view controller needs to be dismissed in two different ways.
let isPresentingInAddMealMode = presentingViewController is UINavigationController
if isPresentingInAddMealMode {
dismiss(animated: true, completion: nil)
}
else if let owningNavigationController = navigationController{
owningNavigationController.popViewController(animated: true)
}
else {
fatalError("The MealViewController is not inside a navigation controller.")
}
}
// This method lets you configure a view controller before it's presented.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
// Configure the destination view controller only when the save button is pressed.
guard let button = sender as? UIBarButtonItem, button === saveButton else {
os_log("The save button was not pressed, cancelling", log: OSLog.default, type: .debug)
return
}
// let name = nameTextField.text ?? ""
// let photo = photoImageView.image
// let rating = ratingControl.rating
// Set the meal to be passed to MealTableViewController after the unwind segue.
meal = Meal(name: nameTextField.text ?? "", photo: photoImageView.image, rating: ratingControl.rating)
}
// MARK: Private Methods
private func updateSaveButtonState() {
// Disable the Save button if the text field is empty.
let text = nameTextField.text ?? ""
saveButton.isEnabled = !text.isEmpty
}
}
| gpl-3.0 | 721b4ed69c48a537cc2d7b0a81a69aa3 | 34.828947 | 111 | 0.667095 | 5.631851 | false | false | false | false |
kwkhaw/SwiftAnyPic | SwiftAnyPic/PAPAccountViewController.swift | 1 | 13775 | import UIKit
import ParseUI
class PAPAccountViewController: PAPPhotoTimelineViewController {
var user: PFUser?
private var headerView: UIView?
// MARK:- Initialization
init(user aUser: PFUser) {
super.init(style: UITableViewStyle.Plain, className: nil)
self.user = aUser
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK:- UIViewController
override func viewDidLoad() {
super.viewDidLoad()
if self.user == nil {
self.user = PFUser.currentUser()!
PFUser.currentUser()!.fetchIfNeeded()
}
self.navigationItem.titleView = UIImageView(image: UIImage(named: "LogoNavigationBar.png"))
self.headerView = UIView(frame: CGRectMake(0.0, 0.0, self.tableView.bounds.size.width, 222.0))
self.headerView!.backgroundColor = UIColor.clearColor() // should be clear, this will be the container for our avatar, photo count, follower count, following count, and so on
let texturedBackgroundView: UIView = UIView(frame: self.view.bounds)
texturedBackgroundView.backgroundColor = UIColor.blackColor()
self.tableView.backgroundView = texturedBackgroundView
let profilePictureBackgroundView = UIView(frame: CGRectMake(94.0, 38.0, 132.0, 132.0))
profilePictureBackgroundView.backgroundColor = UIColor.darkGrayColor()
profilePictureBackgroundView.alpha = 0.0
var layer: CALayer = profilePictureBackgroundView.layer
layer.cornerRadius = 66.0
layer.masksToBounds = true
self.headerView!.addSubview(profilePictureBackgroundView)
let profilePictureImageView: PFImageView = PFImageView(frame: CGRectMake(94.0, 38.0, 132.0, 132.0))
self.headerView!.addSubview(profilePictureImageView)
profilePictureImageView.contentMode = UIViewContentMode.ScaleAspectFill
layer = profilePictureImageView.layer
layer.cornerRadius = 66.0
layer.masksToBounds = true
profilePictureImageView.alpha = 0.0
if PAPUtility.userHasProfilePictures(self.user!) {
let imageFile: PFFile? = self.user!.objectForKey(kPAPUserProfilePicMediumKey) as? PFFile
profilePictureImageView.file = imageFile
profilePictureImageView.loadInBackground { (image, error) in
if error == nil {
UIView.animateWithDuration(0.2, animations: {
profilePictureBackgroundView.alpha = 1.0
profilePictureImageView.alpha = 1.0
})
let backgroundImageView = UIImageView(image: image!.applyDarkEffect())
backgroundImageView.frame = self.tableView.backgroundView!.bounds
backgroundImageView.alpha = 0.0
self.tableView.backgroundView!.addSubview(backgroundImageView)
UIView.animateWithDuration(0.2, animations: {
backgroundImageView.alpha = 1.0
})
}
}
} else {
profilePictureImageView.image = PAPUtility.defaultProfilePicture()!
UIView.animateWithDuration(0.2, animations: {
profilePictureBackgroundView.alpha = 1.0
profilePictureImageView.alpha = 1.0
})
let backgroundImageView = UIImageView(image: PAPUtility.defaultProfilePicture()!.applyDarkEffect())
backgroundImageView.frame = self.tableView.backgroundView!.bounds
backgroundImageView.alpha = 0.0
self.tableView.backgroundView!.addSubview(backgroundImageView)
UIView.animateWithDuration(0.2, animations: {
backgroundImageView.alpha = 1.0
})
}
let photoCountIconImageView: UIImageView = UIImageView(image: nil)
photoCountIconImageView.image = UIImage(named: "IconPics.png")
photoCountIconImageView.frame = CGRectMake(26.0, 50.0, 45.0, 37.0)
self.headerView!.addSubview(photoCountIconImageView)
let photoCountLabel = UILabel(frame: CGRectMake(0.0, 94.0, 92.0, 22.0))
photoCountLabel.textAlignment = NSTextAlignment.Center
photoCountLabel.backgroundColor = UIColor.clearColor()
photoCountLabel.textColor = UIColor.whiteColor()
photoCountLabel.shadowColor = UIColor(white: 0.0, alpha: 0.300)
photoCountLabel.shadowOffset = CGSizeMake(0.0, -1.0)
photoCountLabel.font = UIFont.boldSystemFontOfSize(14.0)
self.headerView!.addSubview(photoCountLabel)
let followersIconImageView = UIImageView(image: nil)
followersIconImageView.image = UIImage(named: "IconFollowers.png")
followersIconImageView.frame = CGRectMake(247.0, 50.0, 52.0, 37.0)
self.headerView!.addSubview(followersIconImageView)
let followerCountLabel = UILabel(frame: CGRectMake(226.0, 94.0, self.headerView!.bounds.size.width - 226.0, 16.0))
followerCountLabel.textAlignment = NSTextAlignment.Center
followerCountLabel.backgroundColor = UIColor.clearColor()
followerCountLabel.textColor = UIColor.whiteColor()
followerCountLabel.shadowColor = UIColor(white: 0.0, alpha: 0.300)
followerCountLabel.shadowOffset = CGSizeMake(0.0, -1.0)
followerCountLabel.font = UIFont.boldSystemFontOfSize(12.0)
self.headerView!.addSubview(followerCountLabel)
let followingCountLabel = UILabel(frame: CGRectMake(226.0, 110.0, self.headerView!.bounds.size.width - 226.0, 16.0))
followingCountLabel.textAlignment = NSTextAlignment.Center
followingCountLabel.backgroundColor = UIColor.clearColor()
followingCountLabel.textColor = UIColor.whiteColor()
followingCountLabel.shadowColor = UIColor(white: 0.0, alpha: 0.300)
followingCountLabel.shadowOffset = CGSizeMake(0.0, -1.0)
followingCountLabel.font = UIFont.boldSystemFontOfSize(12.0)
self.headerView!.addSubview(followingCountLabel)
let userDisplayNameLabel = UILabel(frame: CGRectMake(0, 176.0, self.headerView!.bounds.size.width, 22.0))
userDisplayNameLabel.textAlignment = NSTextAlignment.Center
userDisplayNameLabel.backgroundColor = UIColor.clearColor()
userDisplayNameLabel.textColor = UIColor.whiteColor()
userDisplayNameLabel.shadowColor = UIColor(white: 0.0, alpha: 0.300)
userDisplayNameLabel.shadowOffset = CGSizeMake(0.0, -1.0)
userDisplayNameLabel.text = self.user!.objectForKey("displayName") as? String
userDisplayNameLabel.font = UIFont.boldSystemFontOfSize(18.0)
self.headerView!.addSubview(userDisplayNameLabel)
photoCountLabel.text = "0 photos"
let queryPhotoCount = PFQuery(className: "Photo")
queryPhotoCount.whereKey(kPAPPhotoUserKey, equalTo: self.user!)
queryPhotoCount.cachePolicy = PFCachePolicy.CacheThenNetwork
queryPhotoCount.countObjectsInBackgroundWithBlock { (number, error) in
if error == nil {
let appendS = (number == 1) ? "" : "s"
photoCountLabel.text = "\(number) photo\(appendS)"
PAPCache.sharedCache.setPhotoCount(Int(number), user: self.user!)
}
}
followerCountLabel.text = "0 followers"
let queryFollowerCount = PFQuery(className: kPAPActivityClassKey)
queryFollowerCount.whereKey(kPAPActivityTypeKey, equalTo: kPAPActivityTypeFollow)
queryFollowerCount.whereKey(kPAPActivityToUserKey, equalTo: self.user!)
queryFollowerCount.cachePolicy = PFCachePolicy.CacheThenNetwork
queryFollowerCount.countObjectsInBackgroundWithBlock { (number, error) in
if error == nil {
let appendS = (number == 1) ? "" : "s"
followerCountLabel.text = "\(number) follower\(appendS)"
}
}
let followingDictionary: [NSObject: AnyObject]? = PFUser.currentUser()!.objectForKey("following") as! [NSObject: AnyObject]?
followingCountLabel.text = "0 following"
if followingDictionary != nil {
followingCountLabel.text = "\(followingDictionary!.count) following"
}
let queryFollowingCount = PFQuery(className: kPAPActivityClassKey)
queryFollowingCount.whereKey(kPAPActivityTypeKey, equalTo: kPAPActivityTypeFollow)
queryFollowingCount.whereKey(kPAPActivityFromUserKey, equalTo: self.user!)
queryFollowingCount.cachePolicy = PFCachePolicy.CacheThenNetwork
queryFollowingCount.countObjectsInBackgroundWithBlock { (number, error) in
if error == nil {
followingCountLabel.text = "\(number) following"
}
}
if self.user!.objectId != PFUser.currentUser()!.objectId {
let loadingActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White)
loadingActivityIndicatorView.startAnimating()
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: loadingActivityIndicatorView)
// check if the currentUser is following this user
let queryIsFollowing = PFQuery(className: kPAPActivityClassKey)
queryIsFollowing.whereKey(kPAPActivityTypeKey, equalTo: kPAPActivityTypeFollow)
queryIsFollowing.whereKey(kPAPActivityToUserKey, equalTo: self.user!)
queryIsFollowing.whereKey(kPAPActivityFromUserKey, equalTo: PFUser.currentUser()!)
queryIsFollowing.cachePolicy = PFCachePolicy.CacheThenNetwork
queryIsFollowing.countObjectsInBackgroundWithBlock { (number, error) in
if error != nil && error!.code != PFErrorCode.ErrorCacheMiss.rawValue {
print("Couldn't determine follow relationship: \(error)")
self.navigationItem.rightBarButtonItem = nil
} else {
if number == 0 {
self.configureFollowButton()
} else {
self.configureUnfollowButton()
}
}
}
}
}
// MARK:- PFQueryTableViewController
override func objectsDidLoad(error: NSError?) {
super.objectsDidLoad(error)
self.tableView.tableHeaderView = headerView!
}
override func queryForTable() -> PFQuery {
if self.user == nil {
let query = PFQuery(className: self.parseClassName!)
query.limit = 0
return query
}
let query = PFQuery(className: self.parseClassName!)
query.cachePolicy = PFCachePolicy.NetworkOnly
if self.objects!.count == 0 {
query.cachePolicy = PFCachePolicy.CacheThenNetwork
}
query.whereKey(kPAPPhotoUserKey, equalTo: self.user!)
query.orderByDescending("createdAt")
query.includeKey(kPAPPhotoUserKey)
return query
}
override func tableView(tableView: UITableView, cellForNextPageAtIndexPath indexPath: NSIndexPath) -> PFTableViewCell? {
let LoadMoreCellIdentifier = "LoadMoreCell"
var cell: PAPLoadMoreCell? = tableView.dequeueReusableCellWithIdentifier(LoadMoreCellIdentifier) as? PAPLoadMoreCell
if cell == nil {
cell = PAPLoadMoreCell(style: UITableViewCellStyle.Default, reuseIdentifier: LoadMoreCellIdentifier)
cell!.selectionStyle = UITableViewCellSelectionStyle.None
cell!.separatorImageTop!.image = UIImage(named: "SeparatorTimelineDark.png")
cell!.hideSeparatorBottom = true
cell!.mainView!.backgroundColor = UIColor.clearColor()
}
return cell
}
// MARK:- ()
func followButtonAction(sender: AnyObject) {
let loadingActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White)
loadingActivityIndicatorView.startAnimating()
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: loadingActivityIndicatorView)
self.configureUnfollowButton()
PAPUtility.followUserEventually(self.user!, block: { (succeeded, error) in
if error != nil {
self.configureFollowButton()
}
})
}
func unfollowButtonAction(sender: AnyObject) {
let loadingActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White)
loadingActivityIndicatorView.startAnimating()
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: loadingActivityIndicatorView)
self.configureFollowButton()
PAPUtility.unfollowUserEventually(self.user!)
}
func backButtonAction(sender: AnyObject) {
self.navigationController!.popViewControllerAnimated(true)
}
func configureFollowButton() {
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Follow", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(PAPAccountViewController.followButtonAction(_:)))
PAPCache.sharedCache.setFollowStatus(false, user: self.user!)
}
func configureUnfollowButton() {
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Unfollow", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(PAPAccountViewController.unfollowButtonAction(_:)))
PAPCache.sharedCache.setFollowStatus(true, user: self.user!)
}
}
| cc0-1.0 | d3f11ea96354c215d0e613dacaaf9af9 | 46.829861 | 202 | 0.667151 | 5.287908 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker | Pods/HXPHPicker/Sources/HXPHPicker/Picker/View/Cell/PhotoPickerWeChatViewCell.swift | 1 | 1070 | //
// PhotoPickerWeChatViewCell.swift
// HXPHPicker
//
// Created by Slience on 2021/10/25.
//
import UIKit
open class PhotoPickerWeChatViewCell: PhotoPickerSelectableViewCell {
lazy var titleLb: UILabel = {
let titleLb = UILabel()
titleLb.textAlignment = .center
titleLb.textColor = .white
titleLb.font = .semiboldPingFang(ofSize: 15)
titleLb.isHidden = true
return titleLb
}()
open override func initView() {
super.initView()
contentView.insertSubview(titleLb, belowSubview: selectControl)
}
open override func updateSelectedState(isSelected: Bool, animated: Bool) {
super.updateSelectedState(isSelected: isSelected, animated: animated)
titleLb.isHidden = !isSelected
titleLb.text = "\(photoAsset.selectIndex + 1)"
titleLb.height = 18
titleLb.width = titleLb.textWidth
titleLb.centerY = selectControl.centerY
}
open override func layoutView() {
super.layoutView()
titleLb.x = 10
}
}
| mit | 78f0de5e206d4c2c4cac21aa6f3b22c3 | 26.435897 | 78 | 0.646729 | 4.798206 | false | false | false | false |
mcrollin/safecaster | safecaster/SCRLogParser.swift | 1 | 5824 | //
// SCRParser.swift
// safecaster
//
// Created by Marc Rollin on 3/23/15.
// Copyright (c) 2015 safecast. All rights reserved.
//
import Foundation
class SCRLogParser {
/* We recieve two types of messages: one begins with BNRDD, the other one with BNXSTS.
BNRDD contains radiation data, and BNXSTS contains temperature, humidity, CO and NOX data
The format is as follow:
**BNRDD**
$BNRDD,0210,2013-04-11T05:40:51Z,35,0,736,A,3516.1459,N,13614.9700,E,73.50,A,125,0*64
0 - Header : $BNRDD
1 - Device ID : Device serial number. 0210
2 - Date : Date formatted according to iso-8601 standard. Usually uses GMT. 2013-04-11T05:40:51Z
3 - Radiation 1 minute : number of pulses given by the Geiger tube in the last minute. 35 (cpm)
4 - Radiation 5 seconds : number of pulses given by the Geiger tube in the last 5 seconds. 0
5 - Radiation total count : total number of pulses recorded since startup. 736
6 - Radiation count validity flag : 'A' indicates the counter has been running for more than one minute and the 1 minute count is not zero. Otherwise, the flag is 'V' (void). A
7 - Latitude : As given by GPS. The format is ddmm.mmmm where dd is in degrees and mm.mmmm is decimal minute. 3516.1459
8 - Hemisphere : 'N' (north), or 'S' (south). N
9 - Longitude : As given by GPS. The format is dddmm.mmmm where ddd is in degrees and mm.mmmm is decimal minute. 13614.9700
10- East/West : 'W' (west) or 'E' (east) from Greenwich. E
11- Altitude : Above sea level as given by GPS in meters. 73.50
12- GPS validity : 'A' ok, 'V' invalid. A
13- HDOP : Horizontal Dilution of Precision (HDOP), relative accuracy of horizontal position. 125
14- Checksum: 0*64
**BNXSTS**
$BNXSTS,0210,23,45,12,0.304
0 - Header: $BNXSTS (together with Checksum of first part)
1 - ID: the ID of device
2 - Temperature: unit is Celsius (°C)
3 - Humidity: unit is percentage
4 - CO: range from 1 ~ 1000, unit is ppm
5 - NOX: range from 0.05 ~ 5, unit is ppm
*/
class func parse(dataString: String) -> Dictionary<String, AnyObject>? {
if dataString.hasPrefix("$BNRDD") {
return parseBNRDDString(dataString)
}
// else if dataString.hasPrefix("$BNXSTS") {
// return parseBNXSTSString(dataString)
// }
return nil
}
class func parseBNRDDString(dataString: String) -> Dictionary<String, AnyObject>? {
let dataArray = dataString.componentsSeparatedByString(",")
// Incomplete data
if (dataArray.count != 15) {
return nil
}
var dataDictionary: Dictionary<String, AnyObject> = Dictionary()
dataDictionary["data"] = dataString
dataDictionary["date"] = dateFromUTCString(dataArray[2])
dataDictionary["deviceId"] = dataArray[1]
dataDictionary["CPM"] = Int(dataArray[3])!
dataDictionary["dataValidity"] = dataArray[6] == "A"
dataDictionary["latitude"] = adjustToDecimalLatitude(dataArray[7], latitudeHemisphere: dataArray[8])
dataDictionary["longitude"] = adjustToDecimalLongitude(dataArray[9], longitudeHemisphere: dataArray[10])
dataDictionary["altitude"] = (dataArray[11] as NSString).doubleValue
dataDictionary["GPSValidity"] = dataArray[12] == "A"
dataDictionary["HDOP"] = Int(dataArray[13])!
return dataDictionary
}
// class func parseBNXSTSString(dataString: String) -> Dictionary<String, AnyObject>? {
// let dataArray = dataString.componentsSeparatedByString(",")
//
// // Incomplete data
// if (dataArray.count != 6) {
// return nil
// }
//
// var dataDictionary: Dictionary<String, AnyObject> = Dictionary()
//
// dataDictionary["data"] = dataString
// dataDictionary["deviceId"] = dataArray[1]
// dataDictionary["temperature"] = dataArray[2].toInt()!
// dataDictionary["humidity"] = dataArray[3].toInt()!
// dataDictionary["CO"] = dataArray[3].toInt()!
// dataDictionary["NOX"] = (dataArray[3] as NSString).doubleValue
//
// return dataDictionary
// }
/* Adjust degree and minutes format latitude format to decimal */
class func adjustToDecimalLatitude(latitudeString: NSString, latitudeHemisphere: String) -> Double {
let degree = (latitudeString.substringToIndex(2) as NSString).doubleValue
let minutes = (latitudeString.substringFromIndex(2) as NSString).doubleValue
let latitude = Double(degree + minutes / 60)
return latitudeHemisphere == "S" ? -latitude : latitude
}
/* Adjust degree and minutes format latitude format to decimal */
class func adjustToDecimalLongitude(longitudeString: NSString, longitudeHemisphere: String) -> Double {
let degree = (longitudeString.substringToIndex(3) as NSString).doubleValue
let minutes = (longitudeString.substringFromIndex(3) as NSString).doubleValue
let longitude = Double(degree + minutes / 60)
return longitudeHemisphere == "W" ? -longitude : longitude
}
class func dateFromUTCString(dateString: String) -> NSDate {
let dateStringFormatter = NSDateFormatter()
dateStringFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
dateStringFormatter.timeZone = NSTimeZone(name: "UTC")
if let date = dateStringFormatter.dateFromString(dateString) {
return date
}
return NSDate()
}
} | cc0-1.0 | c2d11eb1523a4e058a38cb6e035db61f | 43.458015 | 180 | 0.625794 | 4.225689 | false | false | false | false |
noppoMan/aws-sdk-swift | Sources/Soto/Services/WorkMail/WorkMail_Paginator.swift | 1 | 24532 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
// MARK: Paginators
extension WorkMail {
/// Creates a paginated call to list the aliases associated with a given entity.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listAliasesPaginator<Result>(
_ input: ListAliasesRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListAliasesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listAliases,
tokenKey: \ListAliasesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listAliasesPaginator(
_ input: ListAliasesRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListAliasesResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listAliases,
tokenKey: \ListAliasesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Returns an overview of the members of a group. Users and groups can be members of a group.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listGroupMembersPaginator<Result>(
_ input: ListGroupMembersRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListGroupMembersResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listGroupMembers,
tokenKey: \ListGroupMembersResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listGroupMembersPaginator(
_ input: ListGroupMembersRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListGroupMembersResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listGroupMembers,
tokenKey: \ListGroupMembersResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Returns summaries of the organization's groups.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listGroupsPaginator<Result>(
_ input: ListGroupsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListGroupsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listGroups,
tokenKey: \ListGroupsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listGroupsPaginator(
_ input: ListGroupsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListGroupsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listGroups,
tokenKey: \ListGroupsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Lists the mailbox export jobs started for the specified organization within the last seven days.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listMailboxExportJobsPaginator<Result>(
_ input: ListMailboxExportJobsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListMailboxExportJobsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listMailboxExportJobs,
tokenKey: \ListMailboxExportJobsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listMailboxExportJobsPaginator(
_ input: ListMailboxExportJobsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListMailboxExportJobsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listMailboxExportJobs,
tokenKey: \ListMailboxExportJobsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Lists the mailbox permissions associated with a user, group, or resource mailbox.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listMailboxPermissionsPaginator<Result>(
_ input: ListMailboxPermissionsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListMailboxPermissionsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listMailboxPermissions,
tokenKey: \ListMailboxPermissionsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listMailboxPermissionsPaginator(
_ input: ListMailboxPermissionsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListMailboxPermissionsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listMailboxPermissions,
tokenKey: \ListMailboxPermissionsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Returns summaries of the customer's organizations.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listOrganizationsPaginator<Result>(
_ input: ListOrganizationsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListOrganizationsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listOrganizations,
tokenKey: \ListOrganizationsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listOrganizationsPaginator(
_ input: ListOrganizationsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListOrganizationsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listOrganizations,
tokenKey: \ListOrganizationsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Lists the delegates associated with a resource. Users and groups can be resource delegates and answer requests on behalf of the resource.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listResourceDelegatesPaginator<Result>(
_ input: ListResourceDelegatesRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListResourceDelegatesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listResourceDelegates,
tokenKey: \ListResourceDelegatesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listResourceDelegatesPaginator(
_ input: ListResourceDelegatesRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListResourceDelegatesResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listResourceDelegates,
tokenKey: \ListResourceDelegatesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Returns summaries of the organization's resources.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listResourcesPaginator<Result>(
_ input: ListResourcesRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListResourcesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listResources,
tokenKey: \ListResourcesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listResourcesPaginator(
_ input: ListResourcesRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListResourcesResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listResources,
tokenKey: \ListResourcesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Returns summaries of the organization's users.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listUsersPaginator<Result>(
_ input: ListUsersRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListUsersResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listUsers,
tokenKey: \ListUsersResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listUsersPaginator(
_ input: ListUsersRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListUsersResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listUsers,
tokenKey: \ListUsersResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
}
extension WorkMail.ListAliasesRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> WorkMail.ListAliasesRequest {
return .init(
entityId: self.entityId,
maxResults: self.maxResults,
nextToken: token,
organizationId: self.organizationId
)
}
}
extension WorkMail.ListGroupMembersRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> WorkMail.ListGroupMembersRequest {
return .init(
groupId: self.groupId,
maxResults: self.maxResults,
nextToken: token,
organizationId: self.organizationId
)
}
}
extension WorkMail.ListGroupsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> WorkMail.ListGroupsRequest {
return .init(
maxResults: self.maxResults,
nextToken: token,
organizationId: self.organizationId
)
}
}
extension WorkMail.ListMailboxExportJobsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> WorkMail.ListMailboxExportJobsRequest {
return .init(
maxResults: self.maxResults,
nextToken: token,
organizationId: self.organizationId
)
}
}
extension WorkMail.ListMailboxPermissionsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> WorkMail.ListMailboxPermissionsRequest {
return .init(
entityId: self.entityId,
maxResults: self.maxResults,
nextToken: token,
organizationId: self.organizationId
)
}
}
extension WorkMail.ListOrganizationsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> WorkMail.ListOrganizationsRequest {
return .init(
maxResults: self.maxResults,
nextToken: token
)
}
}
extension WorkMail.ListResourceDelegatesRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> WorkMail.ListResourceDelegatesRequest {
return .init(
maxResults: self.maxResults,
nextToken: token,
organizationId: self.organizationId,
resourceId: self.resourceId
)
}
}
extension WorkMail.ListResourcesRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> WorkMail.ListResourcesRequest {
return .init(
maxResults: self.maxResults,
nextToken: token,
organizationId: self.organizationId
)
}
}
extension WorkMail.ListUsersRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> WorkMail.ListUsersRequest {
return .init(
maxResults: self.maxResults,
nextToken: token,
organizationId: self.organizationId
)
}
}
| apache-2.0 | a2d23057c16fe268492e8b170256c705 | 41.813264 | 168 | 0.642222 | 5.107641 | false | false | false | false |
Finb/V2ex-Swift | View/LogoutTableViewCell.swift | 1 | 1274 | //
// LogoutTableViewCell.swift
// V2ex-Swift
//
// Created by huangfeng on 2/12/16.
// Copyright © 2016 Fin. All rights reserved.
//
import UIKit
class LogoutTableViewCell: UITableViewCell {
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier);
self.setup();
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup()->Void{
self.textLabel!.text = NSLocalizedString("logOut")
self.textLabel!.textAlignment = .center
let separator = UIImageView()
self.contentView.addSubview(separator)
separator.snp.makeConstraints{ (make) -> Void in
make.left.equalTo(self.contentView)
make.right.bottom.equalTo(self.contentView)
make.height.equalTo(SEPARATOR_HEIGHT)
}
self.themeChangedHandler = {[weak self] _ in
self?.backgroundColor = V2EXColor.colors.v2_CellWhiteBackgroundColor
self?.textLabel!.textColor = V2EXColor.colors.v2_NoticePointColor
separator.image = createImageWithColor(V2EXColor.colors.v2_SeparatorColor)
}
}
}
| mit | 2493c32cebd28a98e377389447480998 | 30.825 | 86 | 0.64729 | 4.530249 | false | false | false | false |
Eliothu/WordPress-iOS | WordPress/WordPressTodayWidget/TodayViewController.swift | 6 | 5119 | import UIKit
import NotificationCenter
class TodayViewController: UIViewController, NCWidgetProviding {
@IBOutlet var siteNameLabel: UILabel!
@IBOutlet var visitorsCountLabel: UILabel!
@IBOutlet var visitorsLabel: UILabel!
@IBOutlet var viewsCountLabel: UILabel!
@IBOutlet var viewsLabel: UILabel!
var siteName: String = ""
var visitorCount: String = ""
var viewCount: String = ""
var siteId: NSNumber?
override func viewDidLoad() {
super.viewDidLoad()
let sharedDefaults = NSUserDefaults(suiteName: WPAppGroupName)!
self.siteId = sharedDefaults.objectForKey(WPStatsTodayWidgetUserDefaultsSiteIdKey) as! NSNumber?
visitorsLabel?.text = NSLocalizedString("Visitors", comment: "Stats Visitors Label")
viewsLabel?.text = NSLocalizedString("Views", comment: "Stats Views Label")
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
// Manual state restoration
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject(self.siteName, forKey: WPStatsTodayWidgetUserDefaultsSiteNameKey)
userDefaults.setObject(self.visitorCount, forKey: WPStatsTodayWidgetUserDefaultsVisitorCountKey)
userDefaults.setObject(self.viewCount, forKey: WPStatsTodayWidgetUserDefaultsViewCountKey)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// Manual state restoration
let sharedDefaults = NSUserDefaults(suiteName: WPAppGroupName)!
self.siteName = sharedDefaults.stringForKey(WPStatsTodayWidgetUserDefaultsSiteNameKey) ?? ""
let userDefaults = NSUserDefaults.standardUserDefaults()
self.visitorCount = userDefaults.stringForKey(WPStatsTodayWidgetUserDefaultsVisitorCountKey) ?? "0"
self.viewCount = userDefaults.stringForKey(WPStatsTodayWidgetUserDefaultsViewCountKey) ?? "0"
self.siteNameLabel?.text = self.siteName
self.visitorsCountLabel?.text = self.visitorCount
self.viewsCountLabel?.text = self.viewCount
}
@IBAction func launchContainingApp() {
self.extensionContext!.openURL(NSURL(string: "\(WPCOM_SCHEME)://viewstats?siteId=\(siteId!)")!, completionHandler: nil)
}
func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)) {
// Perform any setup necessary in order to update the view.
// If an error is encoutered, use NCUpdateResult.Failed
// If there's no update required, use NCUpdateResult.NoData
// If there's an update, use NCUpdateResult.NewData
let sharedDefaults = NSUserDefaults(suiteName: WPAppGroupName)!
let siteId = sharedDefaults.objectForKey(WPStatsTodayWidgetUserDefaultsSiteIdKey) as! NSNumber?
self.siteName = sharedDefaults.stringForKey(WPStatsTodayWidgetUserDefaultsSiteNameKey) ?? ""
let timeZoneName = sharedDefaults.stringForKey(WPStatsTodayWidgetUserDefaultsSiteTimeZoneKey)
let oauth2Token = self.getOAuth2Token()
if siteId == nil || timeZoneName == nil || oauth2Token == nil {
WPDDLogWrapper.logError("Missing site ID, timeZone or oauth2Token")
let bundle = NSBundle(forClass: TodayViewController.classForCoder())
NCWidgetController.widgetController().setHasContent(false, forWidgetWithBundleIdentifier: bundle.bundleIdentifier!)
completionHandler(NCUpdateResult.Failed)
return
}
let timeZone = NSTimeZone(name: timeZoneName!)
let statsService: WPStatsService = WPStatsService(siteId: siteId, siteTimeZone: timeZone, oauth2Token: oauth2Token, andCacheExpirationInterval:0)
statsService.retrieveTodayStatsWithCompletionHandler({ (wpStatsSummary: StatsSummary!, error: NSError!) -> Void in
WPDDLogWrapper.logInfo("Downloaded data in the Today widget")
self.visitorCount = wpStatsSummary.visitors
self.viewCount = wpStatsSummary.views
self.siteNameLabel?.text = self.siteName
self.visitorsCountLabel?.text = self.visitorCount
self.viewsCountLabel?.text = self.viewCount
completionHandler(NCUpdateResult.NewData)
}, failureHandler: { (error) -> Void in
WPDDLogWrapper.logError("\(error)")
completionHandler(NCUpdateResult.Failed)
})
}
func getOAuth2Token() -> String? {
var oauth2Token:NSString? = nil
do {
try oauth2Token = SFHFKeychainUtils.getPasswordForUsername(WPStatsTodayWidgetOAuth2TokenKeychainUsername, andServiceName: WPStatsTodayWidgetOAuth2TokenKeychainServiceName, accessGroup: WPStatsTodayWidgetOAuth2TokenKeychainAccessGroup)
} catch {
WPDDLogWrapper.logError("No OAuth2 token available - error: \(error)")
}
return oauth2Token as String?
}
} | gpl-2.0 | 4181b785c5387d58e326049e15592ba1 | 45.126126 | 246 | 0.692518 | 5.637665 | false | false | false | false |
bradhilton/SwiftCollection | SwiftCollection/Collection/MultiCollection/MultiCollection.swift | 1 | 4663 | //
// MultiCollection.swift
// SwiftCollection
//
// Created by Bradley Hilton on 5/13/16.
// Copyright © 2016 Brad Hilton. All rights reserved.
//
import AssociatedValues
import OrderedObjectSet
public protocol MultiCollection : CollectionSource, ParentInterface {
var collections: OrderedObjectSet<CollectionSource> { get set }
}
extension MultiCollection {
public var collections: OrderedObjectSet<CollectionSource> {
get {
return getAssociatedValue(key: "collections", object: self, initialValue: OrderedObjectSet())
}
set {
collections.subtracting(newValue).forEach { $0.parent = nil }
newValue.subtracting(collections).forEach { $0.parent = self }
set(associatedValue: newValue, key: "collections", object: self)
}
}
func collectionForSection(_ section: Int) -> CollectionSource? {
return collectionForIndex(section) { $0 + $1.numberOfSections }
}
func collectionForIndex(_ index: Int, combine: (Int, CollectionSource) -> Int) -> CollectionSource? {
for i in collections.indices {
if index < collections[0...i].reduce(0, combine) {
return self.collections[i]
}
}
return nil
}
func sectionOffsetForCollection(_ collection: CollectionSource) -> Int {
if let i = collections.index(where: { $0 === collection }) {
return collections[0..<i].reduce(0) { $0 + $1.numberOfSections }
}
return 0
}
func indexSetFromCollection(_ collection: CollectionSource, indexSet: IndexSet) -> IndexSet {
return indexSet.reduce(IndexSet()) {
var copy = $0
copy.insert(sectionFromCollection(collection, section: $1))
return copy
}
}
func indexPathsForCollection(_ collection: CollectionSource, indexPaths: [IndexPath]?) -> [IndexPath]? {
guard let indexPaths = indexPaths else { return nil }
return indexPaths.filter { collectionForSection($0.section) === collection }.map { indexPathForCollection(collection, indexPath: $0) }
}
func indexPathsFromCollection(_ collection: CollectionSource, indexPaths: [IndexPath]) -> [IndexPath] {
return indexPaths.map { indexPathFromCollection(collection, indexPath: $0) }
}
func optionalIndexPathForCollection(_ collection: CollectionSource, indexPath: IndexPath?) -> IndexPath? {
guard let indexPath = indexPath, collectionForSection(indexPath.section) === collection else { return nil }
return indexPathForCollection(collection, indexPath: indexPath)
}
func indexPathForCollection(_ collection: CollectionSource, indexPath: IndexPath) -> IndexPath {
return IndexPath(item: indexPath.item, section: sectionForCollection(collection, section: indexPath.section))
}
func optionalIndexPathFromCollection(_ collection: CollectionSource, indexPath: IndexPath?) -> IndexPath? {
guard let indexPath = indexPath else { return nil }
return indexPathFromCollection(collection, indexPath: indexPath)
}
func indexPathFromCollection(_ collection: CollectionSource, indexPath: IndexPath) -> IndexPath {
return IndexPath(item: indexPath.item, section: sectionFromCollection(collection, section: indexPath.section))
}
func sectionForCollection(_ collection: CollectionSource, section: Int) -> Int {
return section - sectionOffsetForCollection(collection)
}
func sectionFromCollection(_ collection: CollectionSource, section: Int) -> Int {
return section + sectionOffsetForCollection(collection)
}
func delegate<T>(_ indexPath: IndexPath, handler: (CollectionSource, IndexPath) -> T?) -> T? {
guard let collection = collectionForSection(indexPath.section) else { return nil }
return handler(collection, indexPathForCollection(collection, indexPath: indexPath))
}
func delegate<T>(_ section: Int, handler: (CollectionSource, Int) -> T?) -> T? {
guard let collection = collectionForSection(section) else { return nil }
return handler(collection, sectionForCollection(collection, section: section))
}
func respond<T>(_ collection: CollectionSource, indexPath: IndexPath, handler: (IndexPath) -> T?) -> T? {
return handler(indexPathFromCollection(collection, indexPath: indexPath))
}
func respond<T>(_ collection: CollectionSource, section: Int, handler: (Int) -> T?) -> T? {
return handler(sectionFromCollection(collection, section: section))
}
}
| mit | 6ab44be55a41a2cb25001f83c5440e8a | 40.625 | 142 | 0.672244 | 4.986096 | false | false | false | false |
rstoner19/iOSStockProject | StockApp/Store.swift | 1 | 721 | //
// Store.swift
// StockApp
//
// Created by Rick on 7/4/16.
// Copyright © 2016 Rick . All rights reserved.
//
import Foundation
class Store: StoreProtocol {
static let shared = Store()
var symbols = Set<String>()
private init() {
if let storedItems = NSKeyedUnarchiver.unarchiveObjectWithFile(Store.ArchiveURL.path!) as? Set<String> {
self.symbols = storedItems
} else {
self.symbols = Set<String>()
}
}
static let DocumentsDirectory = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
static let ArchiveURL = DocumentsDirectory.URLByAppendingPathComponent("symbols")
} | mit | a3b3f788ad1bcefec0ae2ca602a1eb54 | 23.862069 | 123 | 0.644444 | 4.705882 | false | false | false | false |
jacobwhite/firefox-ios | Shared/AppConstants.swift | 2 | 6510 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
public enum AppBuildChannel: String {
case release = "release"
case beta = "beta"
case developer = "developer"
}
public enum KVOConstants: String {
case loading = "loading"
case estimatedProgress = "estimatedProgress"
case URL = "URL"
case title = "title"
case canGoBack = "canGoBack"
case canGoForward = "canGoForward"
case contentSize = "contentSize"
}
public struct AppConstants {
public static let IsRunningTest = NSClassFromString("XCTestCase") != nil || ProcessInfo.processInfo.arguments.contains(LaunchArguments.Test)
public static let FxAiOSClientId = "1b1a3e44c54fbb58"
/// Build Channel.
public static let BuildChannel: AppBuildChannel = {
#if MOZ_CHANNEL_RELEASE
return AppBuildChannel.release
#elseif MOZ_CHANNEL_BETA
return AppBuildChannel.beta
#elseif MOZ_CHANNEL_FENNEC
return AppBuildChannel.developer
#endif
}()
public static let scheme: String = {
guard let identifier = Bundle.main.bundleIdentifier else {
return "unknown"
}
let scheme = identifier.replacingOccurrences(of: "org.mozilla.ios.", with: "")
if scheme == "FirefoxNightly.enterprise" {
return "FirefoxNightly"
}
return scheme
}()
public static let PrefSendUsageData = "settings.sendUsageData"
/// Whether we just mirror (false) or actively do a full bookmark merge and upload (true).
public static var shouldMergeBookmarks = false
/// Should we try to sync (no merging) the Mobile Folder (if shouldMergeBookmarks is false).
public static let MOZ_SIMPLE_BOOKMARKS_SYNCING: Bool = {
#if MOZ_CHANNEL_RELEASE
return true
#elseif MOZ_CHANNEL_BETA
return true
#elseif MOZ_CHANNEL_FENNEC
return true
#else
return true
#endif
}()
/// Should we send a repair request to other clients when the bookmarks buffer validation fails.
public static let MOZ_BOOKMARKS_REPAIR_REQUEST: Bool = {
#if MOZ_CHANNEL_RELEASE
return false
#elseif MOZ_CHANNEL_BETA
return true
#elseif MOZ_CHANNEL_FENNEC
return true
#else
return true
#endif
}()
/// Enables support for International Domain Names (IDN)
/// Disabled because of https://bugzilla.mozilla.org/show_bug.cgi?id=1312294
public static let MOZ_PUNYCODE: Bool = {
#if MOZ_CHANNEL_RELEASE
return false
#elseif MOZ_CHANNEL_BETA
return false
#elseif MOZ_CHANNEL_FENNEC
return true
#else
return true
#endif
}()
/// Enables/disables deep linking form fill for FxA
public static let MOZ_FXA_DEEP_LINK_FORM_FILL: Bool = {
#if MOZ_CHANNEL_RELEASE
return true
#elseif MOZ_CHANNEL_BETA
return true
#elseif MOZ_CHANNEL_FENNEC
return true
#else
return true
#endif
}()
/// Toggles the ability to add a custom search engine
public static let MOZ_CUSTOM_SEARCH_ENGINE: Bool = {
#if MOZ_CHANNEL_RELEASE
return true
#elseif MOZ_CHANNEL_BETA
return true
#elseif MOZ_CHANNEL_FENNEC
return true
#else
return true
#endif
}()
/// Enables/disables push notificatuibs for FxA
public static let MOZ_FXA_PUSH: Bool = {
#if MOZ_CHANNEL_RELEASE
return true
#elseif MOZ_CHANNEL_BETA
return true
#elseif MOZ_CHANNEL_FENNEC
return true
#else
return true
#endif
}()
/// Toggle the feature that shows the blue 'Open copied link' banner
public static let MOZ_CLIPBOARD_BAR: Bool = {
#if MOZ_CHANNEL_RELEASE
return true
#elseif MOZ_CHANNEL_BETA
return true
#elseif MOZ_CHANNEL_FENNEC
return true
#else
return true
#endif
}()
/// Toggle pocket stories feature
public static let MOZ_POCKET_STORIES: Bool = {
#if MOZ_CHANNEL_RELEASE
return true
#elseif MOZ_CHANNEL_BETA
return true
#elseif MOZ_CHANNEL_FENNEC
return true
#else
return true
#endif
}()
/// Toggle the use of Leanplum.
public static let MOZ_ENABLE_LEANPLUM: Bool = {
#if MOZ_CHANNEL_RELEASE
return true
#elseif MOZ_CHANNEL_BETA
return true
#elseif MOZ_CHANNEL_FENNEC
return true
#else
return false
#endif
}()
/// Toggle configuring Intro slides via LP
public static let MOZ_LP_INTRO: Bool = {
#if MOZ_CHANNEL_RELEASE
return true
#elseif MOZ_CHANNEL_BETA
return true
#elseif MOZ_CHANNEL_FENNEC
return true
#else
return true
#endif
}()
/// Toggle the feature that shows updated FxA preferences cell
public static let MOZ_SHOW_FXA_AVATAR: Bool = {
#if MOZ_CHANNEL_RELEASE
return true
#elseif MOZ_CHANNEL_BETA
return true
#elseif MOZ_CHANNEL_FENNEC
return true
#else
return true
#endif
}()
/// The maximum length of a URL stored by Firefox. Shared with Places on desktop.
public static let DB_URL_LENGTH_MAX = 65536
/// The maximum length of a page title stored by Firefox. Shared with Places on desktop.
public static let DB_TITLE_LENGTH_MAX = 4096
/// The maximum length of a bookmark description stored by Firefox. Shared with Places on desktop.
public static let DB_DESCRIPTION_LENGTH_MAX = 1024
/// Toggle FxA Leanplum A/B test for prompting push permissions
public static let MOZ_FXA_LEANPLUM_AB_PUSH_TEST: Bool = {
#if MOZ_CHANNEL_RELEASE
return true
#elseif MOZ_CHANNEL_BETA
return true
#elseif MOZ_CHANNEL_FENNEC
return true
#else
return false
#endif
}()
}
| mpl-2.0 | ec29ddb4383741867b94f8f86de99a94 | 28.457014 | 144 | 0.593856 | 4.562018 | false | false | false | false |
lhc70000/iina | iina/AssrtSubtitle.swift | 2 | 8576 | //
// AssrtSubtitle.swift
// iina
//
// Created by Collider LI on 26/2/2018.
// Copyright © 2018 lhc. All rights reserved.
//
import Foundation
import Just
import PromiseKit
fileprivate let subsystem = Logger.Subsystem(rawValue: "assrt")
final class AssrtSubtitle: OnlineSubtitle {
struct File {
var url: URL
var filename: String
}
@objc var id: Int
@objc var nativeName: String
@objc var uploadTime: String
@objc var subType: String
@objc var subLang: String?
@objc var title: String?
@objc var filename: String?
@objc var size: String?
@objc var url: URL?
var fileList: [File]?
init(index: Int, id: Int, nativeName: String, uploadTime: String, subType: String?, subLang: String?) {
self.id = id
self.nativeName = nativeName
if self.nativeName.isEmpty {
self.nativeName = "[No title]"
}
self.uploadTime = uploadTime
if let subType = subType {
self.subType = subType
} else {
self.subType = "Unknown"
}
self.subLang = subLang
super.init(index: index)
}
override func download(callback: @escaping DownloadCallback) {
if let fileList = fileList {
// download from file list
when(fulfilled: fileList.map { file -> Promise<URL> in
Promise { resolver in
Just.get(file.url) { response in
guard response.ok, let data = response.content else {
resolver.reject(AssrtSupport.AssrtError.networkError)
return
}
let subFilename = "[\(self.index)]\(file.filename)"
if let url = data.saveToFolder(Utility.tempDirURL, filename: subFilename) {
resolver.fulfill(url)
}
}
}
}).map { urls in
callback(.ok(urls))
}.catch { err in
callback(.failed)
}
} else if let url = url, let filename = filename {
// download from url
Just.get(url) { response in
guard response.ok, let data = response.content else {
callback(.failed)
return
}
let subFilename = "[\(self.index)]\(filename)"
if let url = data.saveToFolder(Utility.tempDirURL, filename: subFilename) {
callback(.ok([url]))
}
}
} else {
callback(.failed)
return
}
}
}
class AssrtSupport {
typealias Subtitle = AssrtSubtitle
enum AssrtError: Int, Error {
case noSuchUser = 1
case queryTooShort = 101
case missingArg = 20000
case invalidToken = 20001
case endPointNotFound = 20400
case subNotFound = 20900
case serverError = 30000
case databaseError = 30001
case searchEngineError = 30002
case tempUnavailable = 30300
case exceedLimit = 30900
case userCanceled = 80000
// lower level error
case wrongResponseFormat = 90000
case networkError = 90001
}
private let searchApi = "https://api.assrt.net/v1/sub/search"
private let detailApi = "https://api.assrt.net/v1/sub/detail"
var token: String
var usesUserToken = false
private let subChooseViewController = SubChooseViewController(source: .assrt)
static let shared = AssrtSupport()
init() {
let userToken = Preference.string(for: .assrtToken)
if let token = userToken, token.count == 32 {
self.token = token
usesUserToken = true
} else {
self.token = "5IzWrb2J099vmA96ECQXwdRSe9xdoBUv"
}
}
func checkToken() -> Bool {
if usesUserToken {
return true
}
// show alert for unregistered users
let alert = NSAlert()
alert.messageText = NSLocalizedString("alert.title_warning", comment: "Warning")
alert.informativeText = String(format: NSLocalizedString("alert.assrt_register", comment: "alert.assrt_register"))
alert.alertStyle = .warning
alert.addButton(withTitle: NSLocalizedString("alert.assrt_register.register", comment: "alert.assrt_register.register"))
alert.addButton(withTitle: NSLocalizedString("alert.assrt_register.try", comment: "alert.assrt_register.try"))
let result = alert.runModal()
if result == .alertFirstButtonReturn {
// if user chose register
NSWorkspace.shared.open(URL(string: AppData.assrtRegisterLink)!)
var newToken = ""
if Utility.quickPromptPanel("assrt_token_prompt", callback: { newToken = $0 }) {
if newToken.count == 32 {
Preference.set(newToken, for: .assrtToken)
self.token = newToken
return true
} else {
Utility.showAlert("assrt_token_invalid")
}
}
return false
}
return true
}
func search(_ query: String) -> Promise<[AssrtSubtitle]> {
return Promise { resolver in
Just.post(searchApi, params: ["q": query], headers: header) { result in
guard let json = result.json as? [String: Any] else {
resolver.reject(AssrtError.networkError)
return
}
guard let status = json["status"] as? Int else {
resolver.reject(AssrtError.wrongResponseFormat)
return
}
if let error = AssrtError(rawValue: status) {
resolver.reject(error)
return
}
// handle result
guard let subDict = json["sub"] as? [String: Any] else {
resolver.reject(AssrtError.wrongResponseFormat)
return
}
// assrt will return `sub: {}` when no result
if let _ = subDict["subs"] as? [String: Any] {
resolver.fulfill([])
return
}
guard let subArray = subDict["subs"] as? [[String: Any]] else {
resolver.reject(AssrtError.wrongResponseFormat)
return
}
var subtitles: [AssrtSubtitle] = []
var index = 0
for sub in subArray {
var subLang: String? = nil
if let lang = sub["lang"] as? [String: Any], let desc = lang["desc"] as? String {
subLang = desc
}
subtitles.append(AssrtSubtitle(index: index,
id: sub["id"] as! Int,
nativeName: sub["native_name"] as! String,
uploadTime: sub["upload_time"] as! String,
subType: sub["subtype"] as? String,
subLang: subLang))
index += 1
}
resolver.fulfill(subtitles)
}
}
}
func showSubSelectWindow(with subs: [AssrtSubtitle]) -> Promise<[AssrtSubtitle]> {
return Promise { resolver in
// return when found 0 or 1 sub
if subs.count <= 1 {
resolver.fulfill(subs)
return
}
subChooseViewController.subtitles = subs
subChooseViewController.userDoneAction = { subs in
resolver.fulfill(subs as! [AssrtSubtitle])
}
subChooseViewController.userCanceledAction = {
resolver.reject(AssrtError.userCanceled)
}
PlayerCore.active.sendOSD(.foundSub(subs.count), autoHide: false, accessoryView: subChooseViewController.view)
subChooseViewController.tableView.reloadData()
}
}
func loadDetails(forSub sub: AssrtSubtitle) -> Promise<AssrtSubtitle> {
return Promise { resolver in
Just.post(detailApi, params: ["id": sub.id], headers: header) { result in
guard let json = result.jsonIgnoringError as? [String: Any] else {
resolver.reject(AssrtError.networkError)
return
}
guard let status = json["status"] as? Int else {
resolver.reject(AssrtError.wrongResponseFormat)
return
}
if let error = AssrtError(rawValue: status) {
resolver.reject(error)
return
}
guard let subDict = json["sub"] as? [String: Any] else {
resolver.reject(AssrtError.wrongResponseFormat)
return
}
guard let subArray = subDict["subs"] as? [[String: Any]], subArray.count == 1 else {
resolver.reject(AssrtError.wrongResponseFormat)
return
}
sub.url = URL(string: subArray[0]["url"] as! String)
sub.filename = subArray[0]["filename"] as? String
if let fileList = subArray[0]["filelist"] as? [[String: String]] {
sub.fileList = fileList.map { info in
AssrtSubtitle.File(url: URL(string: info["url"]!)!,
filename: info["f"]!)
}
}
resolver.fulfill(sub)
}
}
}
private var header: [String: String] {
return ["Authorization": "Bearer \(token)"]
}
}
| gpl-3.0 | a6fb5c43914c4d4723ba183a34d2ad52 | 30.068841 | 124 | 0.599067 | 4.201372 | false | false | false | false |
proversity-org/edx-app-ios | Source/BulkDownloadHelper.swift | 2 | 3187 | //
// BulkDownloadHelper.swift
// edX
//
// Created by Muhammad Zeeshan Arif on 18/01/2018.
// Copyright © 2018 edX. All rights reserved.
//
import Foundation
enum BulkDownloadState {
case new
case downloading
case partial
case downloaded
case none // if course has no `downloadable` videos.
}
class BulkDownloadHelper {
private(set) var course: OEXCourse
private(set) var state: BulkDownloadState = .new
var videos: [OEXHelperVideoDownload] {
didSet {
refreshState()
}
}
var newVideosCount: Int {
return (videos.filter { $0.downloadState == .new }).count
}
var partialAndNewVideosCount: Int {
return (videos.filter { $0.downloadState == .partial || $0.downloadState == .new }).count
}
var totalSize: Double {
return videos.reduce(into: 0.0) {
(sum, video) in
sum = sum + Double(truncating: video.summary?.size ?? 0)
}
}
var downloadedSize: Double {
switch state {
case .downloaded:
return totalSize
case .downloading:
return videos.reduce(into: 0.0) {
(sum, video) in
sum = sum + ((video.downloadProgress * Double(truncating: video.summary?.size ?? 0.0)) / 100.0)
}
case .partial:
let fullyDownloadedVideos = videos.filter { $0.downloadState == .complete }
return fullyDownloadedVideos.reduce(into: 0.0) {
(sum, video) in
sum = sum + Double(truncating: video.summary?.size ?? 0)
}
default:
return 0.0
}
}
var progress: Float {
return totalSize == 0 ? 0.0 : Float(downloadedSize / totalSize)
}
init(with course: OEXCourse, videos: [OEXHelperVideoDownload]) {
self.course = course
self.videos = videos
refreshState()
}
func refreshState() {
state = bulkDownloadState()
}
private func bulkDownloadState() -> BulkDownloadState {
if videos.count <= 0 {
return .none
}
let allNew = videos.reduce(true) {(acc, video) in
return acc && video.downloadState == .new
}
if allNew {
return .new
}
let allCompleted = videos.reduce(true) {(acc, video) in
return acc && video.downloadState == .complete
}
if allCompleted {
return .downloaded
}
let allPartialyOrFullyDownloaded = videos.reduce(true) {(acc, video) in
return acc && video.downloadState != .new
}
if allPartialyOrFullyDownloaded {
return .downloading
}
return .partial
}
}
extension Double {
// Bytes to MB Conversion
private var mb: Double {
return self / 1024 / 1024
}
private func roundTo(places:Int) -> Double {
let divisor = pow(10.0, Double(places))
return (self * divisor).rounded() / divisor
}
var roundedMB: Double {
return mb.roundTo(places: 2)
}
}
| apache-2.0 | 8424cdba23731151840dfa31546e0292 | 25.114754 | 112 | 0.549278 | 4.462185 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/Models/Blog+Media.swift | 1 | 1377 | import Foundation
extension Blog {
/// Get the number of items in a blog media library that are of a certain type.
///
/// - Parameter mediaTypes: set of media type values to be considered in the counting.
/// - Returns: Number of media assets matching the criteria.
@objc(mediaLibraryCountForTypes:)
func mediaLibraryCount(types mediaTypes: NSSet) -> Int {
guard let context = managedObjectContext else {
return 0
}
var count = 0
context.performAndWait {
var predicate = NSPredicate(format: "blog == %@", self)
if mediaTypes.count > 0 {
let types = mediaTypes
.map { obj in
guard let rawValue = (obj as? NSNumber)?.uintValue,
let type = MediaType(rawValue: rawValue) else {
fatalError("Can't convert \(obj) to MediaType")
}
return Media.string(from: type)
}
let filterPredicate = NSPredicate(format: "mediaTypeString IN %@", types)
predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate, filterPredicate])
}
count = context.countObjects(ofType: Media.self, matching: predicate)
}
return count
}
}
| gpl-2.0 | 47d1103ead4b56ad1ca88651e03c1da5 | 36.216216 | 108 | 0.557734 | 5.643443 | false | false | false | false |
pabloroca/PR2StudioSwift | Source/Networking/HTTPMethod.swift | 1 | 441 | //
// HTTPMethod.swift
// PR2StudioSwift
//
// Created by Pablo Roca on 07/02/2019.
// Copyright © 2019 PR2Studio. All rights reserved.
//
import Foundation
public enum HTTPMethod: String {
case connect = "CONNECT"
case delete = "DELETE"
case get = "GET"
case head = "HEAD"
case options = "OPTIONS"
case patch = "PATCH"
case post = "POST"
case put = "PUT"
case trace = "TRACE"
}
| mit | fba3fdb7f2ce447a5a4aaabe92b16733 | 19.952381 | 52 | 0.595455 | 3.333333 | false | false | false | false |
realm/SwiftLint | Tests/SwiftLintFrameworkTests/TrailingWhitespaceRuleTests.swift | 1 | 1604 | @testable import SwiftLintFramework
import XCTest
class TrailingWhitespaceRuleTests: XCTestCase {
func testWithIgnoresEmptyLinesEnabled() {
// Perform additional tests with the ignores_empty_lines setting enabled.
// The set of non-triggering examples is extended by a whitespace-indented empty line
let baseDescription = TrailingWhitespaceRule.description
let nonTriggeringExamples = baseDescription.nonTriggeringExamples + [Example(" \n")]
let description = baseDescription.with(nonTriggeringExamples: nonTriggeringExamples)
verifyRule(description,
ruleConfiguration: ["ignores_empty_lines": true, "ignores_comments": true])
}
func testWithIgnoresCommentsDisabled() {
// Perform additional tests with the ignores_comments settings disabled.
let baseDescription = TrailingWhitespaceRule.description
let triggeringComments = [
Example("// \n"),
Example("let name: String // \n")
]
let nonTriggeringExamples = baseDescription.nonTriggeringExamples
.filter { !triggeringComments.contains($0) }
let triggeringExamples = baseDescription.triggeringExamples + triggeringComments
let description = baseDescription.with(nonTriggeringExamples: nonTriggeringExamples)
.with(triggeringExamples: triggeringExamples)
verifyRule(description,
ruleConfiguration: ["ignores_empty_lines": false, "ignores_comments": false],
commentDoesntViolate: false)
}
}
| mit | 115548a8d02d1c710c3f1e06cd65c200 | 49.125 | 96 | 0.688279 | 6.098859 | false | true | false | false |
narner/AudioKit | Examples/iOS/AnalogSynthX/AnalogSynthX/AudioSystem/GeneratorBank.swift | 1 | 6151 | //
// GeneratorBank.swift
// AnalogSynthX
//
// Created by Aurelius Prochazka on 6/25/16.
// Copyright © 2016 AudioKit. All rights reserved.
//
import AudioKit
class GeneratorBank: AKPolyphonicNode {
func updateWaveform1() {
vco1.index = (0...3).clamp(waveform1 + morph)
}
func updateWaveform2() {
vco2.index = (0...3).clamp(waveform2 + morph)
}
var waveform1 = 0.0 { didSet { updateWaveform1() } }
var waveform2 = 0.0 { didSet { updateWaveform2() } }
var globalbend: Double = 1.0 {
didSet {
vco1.pitchBend = globalbend
vco2.pitchBend = globalbend
subOsc.pitchBend = globalbend
fmOsc.pitchBend = globalbend
}
}
var offset1 = 0 {
willSet {
for noteNumber in onNotes {
vco1.stop(noteNumber: MIDINoteNumber(Int(noteNumber) + offset1))
vco1.play(noteNumber: MIDINoteNumber(Int(noteNumber) + newValue), velocity: 127)
}
}
}
var offset2 = 0 {
willSet {
for noteNumber in onNotes {
vco2.stop(noteNumber: MIDINoteNumber(Int(noteNumber) + offset2))
vco2.play(noteNumber: MIDINoteNumber(Int(noteNumber) + newValue), velocity: 127)
}
}
}
var morph: Double = 0.0 {
didSet {
updateWaveform1()
updateWaveform2()
}
}
/// Attack time
var attackDuration: Double = 0.1 {
didSet {
if attackDuration < 0.02 { attackDuration = 0.02 }
vco1.attackDuration = attackDuration
vco2.attackDuration = attackDuration
subOsc.attackDuration = attackDuration
fmOsc.attackDuration = attackDuration
noiseADSR.attackDuration = attackDuration
}
}
/// Decay time
var decayDuration: Double = 0.1 {
didSet {
if decayDuration < 0.02 { decayDuration = 0.02 }
vco1.decayDuration = decayDuration
vco2.decayDuration = decayDuration
subOsc.decayDuration = decayDuration
fmOsc.decayDuration = decayDuration
noiseADSR.decayDuration = decayDuration
}
}
/// Sustain Level
var sustainLevel: Double = 0.66 {
didSet {
vco1.sustainLevel = sustainLevel
vco2.sustainLevel = sustainLevel
subOsc.sustainLevel = sustainLevel
fmOsc.sustainLevel = sustainLevel
noiseADSR.sustainLevel = sustainLevel
}
}
/// Release time
var releaseDuration: Double = 0.5 {
didSet {
if releaseDuration < 0.02 { releaseDuration = 0.02 }
vco1.releaseDuration = releaseDuration
vco2.releaseDuration = releaseDuration
subOsc.releaseDuration = releaseDuration
fmOsc.releaseDuration = releaseDuration
noiseADSR.releaseDuration = releaseDuration
}
}
var vco1On = true {
didSet {
vco1Mixer.volume = vco1On ? 1.0 : 0.0
}
}
var vco2On = true {
didSet {
vco2Mixer.volume = vco2On ? 1.0 : 0.0
}
}
var vco1: AKMorphingOscillatorBank
var vco2: AKMorphingOscillatorBank
var subOsc = AKOscillatorBank()
var fmOsc = AKFMOscillatorBank()
var noise = AKWhiteNoise()
var noiseADSR: AKAmplitudeEnvelope
// We'll be using these simply to control volume independent of velocity
var vco1Mixer: AKMixer
var vco2Mixer: AKMixer
var subOscMixer: AKMixer
var fmOscMixer: AKMixer
var noiseMixer: AKMixer
var vcoBalancer: AKDryWetMixer
var sourceMixer: AKMixer
var onNotes = Set<MIDINoteNumber>()
override init() {
let triangle = AKTable(.triangle)
let square = AKTable(.square)
let sawtooth = AKTable(.sawtooth)
let squareWithHighPWM = AKTable()
let count = squareWithHighPWM.count
for i in squareWithHighPWM.indices {
if i < count / 8 {
squareWithHighPWM[i] = -1.0
} else {
squareWithHighPWM[i] = 1.0
}
}
vco1 = AKMorphingOscillatorBank(waveformArray: [triangle, square, squareWithHighPWM, sawtooth])
vco2 = AKMorphingOscillatorBank(waveformArray: [triangle, square, squareWithHighPWM, sawtooth])
noiseADSR = AKAmplitudeEnvelope(noise)
vco1Mixer = AKMixer(vco1)
vco2Mixer = AKMixer(vco2)
subOscMixer = AKMixer(subOsc)
fmOscMixer = AKMixer(fmOsc)
noiseMixer = AKMixer(noiseADSR)
// Default non-VCO's off
subOscMixer.volume = 0
fmOscMixer.volume = 0
noiseMixer.volume = 0
vcoBalancer = AKDryWetMixer(vco1Mixer, vco2Mixer, balance: 0.5)
sourceMixer = AKMixer(vcoBalancer, fmOscMixer, subOscMixer, noiseMixer)
super.init()
avAudioNode = sourceMixer.avAudioNode
}
/// Function to start, play, or activate the node, all do the same thing
override func play(noteNumber: MIDINoteNumber, velocity: MIDIVelocity) {
vco1.play(noteNumber: MIDINoteNumber(Int(noteNumber) + offset1), velocity: velocity)
vco2.play(noteNumber: MIDINoteNumber(Int(noteNumber) + offset2), velocity: velocity)
if noteNumber >= 12 {
subOsc.play(noteNumber: noteNumber - 12, velocity: velocity)
}
fmOsc.play(noteNumber: noteNumber, velocity: velocity)
if onNotes.isEmpty {
noise.start()
noiseADSR.start()
}
onNotes.insert(noteNumber)
}
/// Function to stop or bypass the node, both are equivalent
override func stop(noteNumber: MIDINoteNumber) {
vco1.stop(noteNumber: MIDINoteNumber(Int(noteNumber) + offset1))
vco2.stop(noteNumber: MIDINoteNumber(Int(noteNumber) + offset2))
if noteNumber >= 12 {
subOsc.stop(noteNumber: noteNumber - 12)
}
fmOsc.stop(noteNumber: noteNumber)
onNotes.remove(noteNumber)
if onNotes.isEmpty {
noiseADSR.stop()
}
}
}
| mit | 0bc111134b305046e7031d8999eb6c0d | 28.854369 | 103 | 0.601789 | 4.450072 | false | false | false | false |
openHPI/xikolo-ios | iOS/SceneDelegate.swift | 1 | 3612 | //
// Created for xikolo-ios under GPL-3.0 license.
// Copyright © HPI. All rights reserved.
//
import Common
import UIKit
@available(iOS 13.0, *)
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
private lazy var tabBarController: UITabBarController = {
let tabBarController = XikoloTabBarController.make()
tabBarController.delegate = self
#if DEBUG
if ProcessInfo.processInfo.arguments.contains("-forceDarkMode") {
tabBarController.overrideUserInterfaceStyle = .dark
}
#endif
return tabBarController
}()
private var themeObservation: NSKeyValueObservation?
lazy var appNavigator = AppNavigator(tabBarController: self.tabBarController)
var window: UIWindow?
private var shortcutItemToProcess: UIApplicationShortcutItem?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
if let windowScene = scene as? UIWindowScene {
self.window = UIWindow(windowScene: windowScene)
self.window?.rootViewController = self.tabBarController
self.window?.tintColor = Brand.default.colors.window
self.window?.makeKeyAndVisible()
}
shortcutItemToProcess = connectionOptions.shortcutItem
// Select initial tab
let tabToSelect: XikoloTabBarController.Tabs = UserProfileHelper.shared.isLoggedIn ? .dashboard : .courses
self.tabBarController.selectedIndex = tabToSelect.index
self.themeObservation = UserDefaults.standard.observe(\UserDefaults.theme, options: [.initial, .new]) { [weak self] _, _ in
self?.window?.overrideUserInterfaceStyle = UserDefaults.standard.theme.userInterfaceStyle
}
}
func windowScene(_ windowScene: UIWindowScene, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
self.appNavigator.handle(shortcutItem: shortcutItem)
}
func sceneDidBecomeActive(_ scene: UIScene) {
if let shortcutItem = self.shortcutItemToProcess {
self.appNavigator.handle(shortcutItem: shortcutItem)
}
shortcutItemToProcess = nil
AutomatedDownloadsManager.processPendingDownloadsAndDeletions(triggeredBy: .appLaunch)
}
func sceneWillResignActive(_ scene: UIScene) {
QuickActionHelper.setHomescreenQuickActions()
}
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
self.appNavigator.handle(userActivity: userActivity)
}
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
guard let url = URLContexts.first?.url else { return }
self.appNavigator.handle(url: url)
}
func stateRestorationActivity(for scene: UIScene) -> NSUserActivity? {
return scene.userActivity
}
}
@available(iOS 13.0, *)
extension SceneDelegate: UITabBarControllerDelegate {
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
guard !UserProfileHelper.shared.isLoggedIn else {
return true
}
guard let navigationController = viewController as? UINavigationController else {
logger.info("Navigation controller not found")
return true
}
guard navigationController.viewControllers.first is DashboardViewController else {
return true
}
self.appNavigator.presentDashboardLoginViewController()
return false
}
}
| gpl-3.0 | 3a9efb0b2365eb26336c1952c21e54cf | 33.066038 | 155 | 0.702852 | 5.572531 | false | false | false | false |
hughbe/swift | test/IDE/print_ast_tc_decls.swift | 8 | 52796 | // RUN: %empty-directory(%t)
//
// Build swift modules this test depends on.
// RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/foo_swift_module.swift
//
// FIXME: BEGIN -enable-source-import hackaround
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/ObjectiveC.swift
// FIXME: END -enable-source-import hackaround
//
// This file should not have any syntax or type checker errors.
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -swift-version 4 -typecheck -verify %s -F %S/Inputs/mock-sdk -disable-objc-attr-requires-foundation-module
//
// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -swift-version 4 -skip-deinit=false -print-ast-typechecked -source-filename %s -F %S/Inputs/mock-sdk -function-definitions=false -prefer-type-repr=false -print-implicit-attrs=true -disable-objc-attr-requires-foundation-module > %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_COMMON -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_PRINT_AST -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_RW_PROP_GET_SET -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_2200 -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_2500 -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_ONE_LINE -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_ONE_LINE_TYPE -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PREFER_TYPE_PRINTING -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_QUAL_UNQUAL -strict-whitespace < %t.printed.txt
//
// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -swift-version 4 -skip-deinit=false -print-ast-typechecked -source-filename %s -F %S/Inputs/mock-sdk -function-definitions=false -prefer-type-repr=true -print-implicit-attrs=true -disable-objc-attr-requires-foundation-module > %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_COMMON -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_PRINT_AST -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_RW_PROP_GET_SET -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_2200 -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_2500 -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_ONE_LINE -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_ONE_LINE_TYPEREPR -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PREFER_TYPE_REPR_PRINTING -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_QUAL_UNQUAL -strict-whitespace < %t.printed.txt
//
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -swift-version 4 -emit-module -o %t -F %S/Inputs/mock-sdk -disable-objc-attr-requires-foundation-module %s
// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -swift-version 4 -skip-deinit=false -print-module -source-filename %s -F %S/Inputs/mock-sdk -module-to-print=print_ast_tc_decls -print-implicit-attrs=true -disable-objc-attr-requires-foundation-module > %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_COMMON -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_PRINT_MODULE_INTERFACE -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_RW_PROP_NO_GET_SET -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_2200_DESERIALIZED -strict-whitespace < %t.printed.txt
// FIXME: rdar://15167697
// FIXME: %FileCheck %s -check-prefix=PASS_2500 -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_ONE_LINE -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PREFER_TYPE_REPR_PRINTING -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_QUAL_UNQUAL -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_EXPLODE_PATTERN -strict-whitespace < %t.printed.txt
//
// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -skip-deinit=false -print-module -source-filename %s -F %S/Inputs/mock-sdk -I %t -module-to-print=print_ast_tc_decls -synthesize-sugar-on-types=true -print-implicit-attrs=true -disable-objc-attr-requires-foundation-module > %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_PRINT_MODULE_INTERFACE -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_QUAL_UNQUAL -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=SYNTHESIZE_SUGAR_ON_TYPES -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_EXPLODE_PATTERN -strict-whitespace < %t.printed.txt
// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -skip-deinit=false -print-module -source-filename %s -F %S/Inputs/mock-sdk -I %t -module-to-print=print_ast_tc_decls -synthesize-sugar-on-types=true -fully-qualified-types-if-ambiguous=true -print-implicit-attrs=true -disable-objc-attr-requires-foundation-module > %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_PRINT_MODULE_INTERFACE -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=PASS_QUAL_IF_AMBIGUOUS -strict-whitespace < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=SYNTHESIZE_SUGAR_ON_TYPES -strict-whitespace < %t.printed.txt
// FIXME: %FileCheck %s -check-prefix=PASS_EXPLODE_PATTERN -strict-whitespace < %t.printed.txt
// FIXME: rdar://problem/19648117 Needs splitting objc parts out
// XFAIL: linux
import Bar
import ObjectiveC
import class Foo.FooClassBase
import struct Foo.FooStruct1
import func Foo.fooFunc1
@_exported import FooHelper
import foo_swift_module
// FIXME: enum tests
//import enum FooClangModule.FooEnum1
// PASS_COMMON: {{^}}import Bar{{$}}
// PASS_COMMON: {{^}}import class Foo.FooClassBase{{$}}
// PASS_COMMON: {{^}}import struct Foo.FooStruct1{{$}}
// PASS_COMMON: {{^}}import func Foo.fooFunc1{{$}}
// PASS_COMMON: {{^}}@_exported import FooHelper{{$}}
// PASS_COMMON: {{^}}import foo_swift_module{{$}}
//===---
//===--- Helper types.
//===---
struct FooStruct {}
class FooClass {}
class BarClass {}
protocol FooProtocol {}
protocol BarProtocol {}
protocol BazProtocol { func baz() }
protocol QuxProtocol {
associatedtype Qux
}
protocol SubFooProtocol : FooProtocol { }
class FooProtocolImpl : FooProtocol {}
class FooBarProtocolImpl : FooProtocol, BarProtocol {}
class BazProtocolImpl : BazProtocol { func baz() {} }
//===---
//===--- Basic smoketest.
//===---
struct d0100_FooStruct {
// PASS_COMMON-LABEL: {{^}}struct d0100_FooStruct {{{$}}
var instanceVar1: Int = 0
// PASS_COMMON-NEXT: {{^}} var instanceVar1: Int{{$}}
var computedProp1: Int {
get {
return 42
}
}
// PASS_COMMON-NEXT: {{^}} var computedProp1: Int { get }{{$}}
func instanceFunc0() {}
// PASS_COMMON-NEXT: {{^}} func instanceFunc0(){{$}}
func instanceFunc1(a: Int) {}
// PASS_COMMON-NEXT: {{^}} func instanceFunc1(a: Int){{$}}
func instanceFunc2(a: Int, b: inout Double) {}
// PASS_COMMON-NEXT: {{^}} func instanceFunc2(a: Int, b: inout Double){{$}}
func instanceFunc3(a: Int, b: Double) { var a = a; a = 1; _ = a }
// PASS_COMMON-NEXT: {{^}} func instanceFunc3(a: Int, b: Double){{$}}
func instanceFuncWithDefaultArg1(a: Int = 0) {}
// PASS_COMMON-NEXT: {{^}} func instanceFuncWithDefaultArg1(a: Int = default){{$}}
func instanceFuncWithDefaultArg2(a: Int = 0, b: Double = 0) {}
// PASS_COMMON-NEXT: {{^}} func instanceFuncWithDefaultArg2(a: Int = default, b: Double = default){{$}}
func varargInstanceFunc0(v: Int...) {}
// PASS_COMMON-NEXT: {{^}} func varargInstanceFunc0(v: Int...){{$}}
func varargInstanceFunc1(a: Float, v: Int...) {}
// PASS_COMMON-NEXT: {{^}} func varargInstanceFunc1(a: Float, v: Int...){{$}}
func varargInstanceFunc2(a: Float, b: Double, v: Int...) {}
// PASS_COMMON-NEXT: {{^}} func varargInstanceFunc2(a: Float, b: Double, v: Int...){{$}}
func overloadedInstanceFunc1() -> Int { return 0; }
// PASS_COMMON-NEXT: {{^}} func overloadedInstanceFunc1() -> Int{{$}}
func overloadedInstanceFunc1() -> Double { return 0.0; }
// PASS_COMMON-NEXT: {{^}} func overloadedInstanceFunc1() -> Double{{$}}
func overloadedInstanceFunc2(x: Int) -> Int { return 0; }
// PASS_COMMON-NEXT: {{^}} func overloadedInstanceFunc2(x: Int) -> Int{{$}}
func overloadedInstanceFunc2(x: Double) -> Int { return 0; }
// PASS_COMMON-NEXT: {{^}} func overloadedInstanceFunc2(x: Double) -> Int{{$}}
func builderFunc1(a: Int) -> d0100_FooStruct { return d0100_FooStruct(); }
// PASS_COMMON-NEXT: {{^}} func builderFunc1(a: Int) -> d0100_FooStruct{{$}}
subscript(i: Int) -> Double {
get {
return Double(i)
}
}
// PASS_COMMON-NEXT: {{^}} subscript(i: Int) -> Double { get }{{$}}
subscript(i: Int, j: Int) -> Double {
get {
return Double(i + j)
}
}
// PASS_COMMON-NEXT: {{^}} subscript(i: Int, j: Int) -> Double { get }{{$}}
func bodyNameVoidFunc1(a: Int, b x: Float) {}
// PASS_COMMON-NEXT: {{^}} func bodyNameVoidFunc1(a: Int, b x: Float){{$}}
func bodyNameVoidFunc2(a: Int, b x: Float, c y: Double) {}
// PASS_COMMON-NEXT: {{^}} func bodyNameVoidFunc2(a: Int, b x: Float, c y: Double){{$}}
func bodyNameStringFunc1(a: Int, b x: Float) -> String { return "" }
// PASS_COMMON-NEXT: {{^}} func bodyNameStringFunc1(a: Int, b x: Float) -> String{{$}}
func bodyNameStringFunc2(a: Int, b x: Float, c y: Double) -> String { return "" }
// PASS_COMMON-NEXT: {{^}} func bodyNameStringFunc2(a: Int, b x: Float, c y: Double) -> String{{$}}
struct NestedStruct {}
// PASS_COMMON-NEXT: {{^}} struct NestedStruct {{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
class NestedClass {}
// PASS_COMMON-NEXT: {{^}} class NestedClass {{{$}}
// PASS_COMMON-NEXT: {{^}} @objc deinit{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
enum NestedEnum {}
// PASS_COMMON-NEXT: {{^}} enum NestedEnum {{{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
// Cannot declare a nested protocol.
// protocol NestedProtocol {}
typealias NestedTypealias = Int
// PASS_COMMON-NEXT: {{^}} typealias NestedTypealias = Int{{$}}
static var staticVar1: Int = 42
// PASS_COMMON-NEXT: {{^}} static var staticVar1: Int{{$}}
static var computedStaticProp1: Int {
get {
return 42
}
}
// PASS_COMMON-NEXT: {{^}} static var computedStaticProp1: Int { get }{{$}}
static func staticFunc0() {}
// PASS_COMMON-NEXT: {{^}} static func staticFunc0(){{$}}
static func staticFunc1(a: Int) {}
// PASS_COMMON-NEXT: {{^}} static func staticFunc1(a: Int){{$}}
static func overloadedStaticFunc1() -> Int { return 0 }
// PASS_COMMON-NEXT: {{^}} static func overloadedStaticFunc1() -> Int{{$}}
static func overloadedStaticFunc1() -> Double { return 0.0 }
// PASS_COMMON-NEXT: {{^}} static func overloadedStaticFunc1() -> Double{{$}}
static func overloadedStaticFunc2(x: Int) -> Int { return 0 }
// PASS_COMMON-NEXT: {{^}} static func overloadedStaticFunc2(x: Int) -> Int{{$}}
static func overloadedStaticFunc2(x: Double) -> Int { return 0 }
// PASS_COMMON-NEXT: {{^}} static func overloadedStaticFunc2(x: Double) -> Int{{$}}
}
// PASS_COMMON-NEXT: {{^}} init(instanceVar1: Int){{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}}}{{$}}
extension d0100_FooStruct {
// PASS_COMMON-LABEL: {{^}}extension d0100_FooStruct {{{$}}
var extProp: Int {
get {
return 42
}
}
// PASS_COMMON-NEXT: {{^}} var extProp: Int { get }{{$}}
func extFunc0() {}
// PASS_COMMON-NEXT: {{^}} func extFunc0(){{$}}
static var extStaticProp: Int {
get {
return 42
}
}
// PASS_COMMON-NEXT: {{^}} static var extStaticProp: Int { get }{{$}}
static func extStaticFunc0() {}
// PASS_COMMON-NEXT: {{^}} static func extStaticFunc0(){{$}}
struct ExtNestedStruct {}
// PASS_COMMON-NEXT: {{^}} struct ExtNestedStruct {{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
class ExtNestedClass {}
// PASS_COMMON-NEXT: {{^}} class ExtNestedClass {{{$}}
// PASS_COMMON-NEXT: {{^}} @objc deinit{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
enum ExtNestedEnum {
case ExtEnumX(Int)
}
// PASS_COMMON-NEXT: {{^}} enum ExtNestedEnum {{{$}}
// PASS_COMMON-NEXT: {{^}} case ExtEnumX(Int){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
typealias ExtNestedTypealias = Int
// PASS_COMMON-NEXT: {{^}} typealias ExtNestedTypealias = Int{{$}}
}
// PASS_COMMON-NEXT: {{^}}}{{$}}
extension d0100_FooStruct.NestedStruct {
// PASS_COMMON-LABEL: {{^}}extension d0100_FooStruct.NestedStruct {{{$}}
struct ExtNestedStruct2 {}
// PASS_COMMON-NEXT: {{^}} struct ExtNestedStruct2 {{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
}
extension d0100_FooStruct.ExtNestedStruct {
// PASS_COMMON-LABEL: {{^}}extension d0100_FooStruct.ExtNestedStruct {{{$}}
struct ExtNestedStruct3 {}
// PASS_COMMON-NEXT: {{^}} struct ExtNestedStruct3 {{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
}
// PASS_COMMON-NEXT: {{^}}}{{$}}
var fooObject: d0100_FooStruct = d0100_FooStruct()
// PASS_ONE_LINE-DAG: {{^}}var fooObject: d0100_FooStruct{{$}}
struct d0110_ReadWriteProperties {
// PASS_RW_PROP_GET_SET-LABEL: {{^}}struct d0110_ReadWriteProperties {{{$}}
// PASS_RW_PROP_NO_GET_SET-LABEL: {{^}}struct d0110_ReadWriteProperties {{{$}}
var computedProp1: Int {
get {
return 42
}
set {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} var computedProp1: Int { get set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var computedProp1: Int{{$}}
subscript(i: Int) -> Int {
get {
return 42
}
set {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} subscript(i: Int) -> Int { get set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} subscript(i: Int) -> Int{{$}}
static var computedStaticProp1: Int {
get {
return 42
}
set {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} static var computedStaticProp1: Int { get set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} static var computedStaticProp1: Int{{$}}
var computedProp2: Int {
mutating get {
return 42
}
set {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} var computedProp2: Int { mutating get set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var computedProp2: Int { mutating get set }{{$}}
var computedProp3: Int {
get {
return 42
}
nonmutating set {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} var computedProp3: Int { get nonmutating set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var computedProp3: Int { get nonmutating set }{{$}}
var computedProp4: Int {
mutating get {
return 42
}
nonmutating set {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} var computedProp4: Int { mutating get nonmutating set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var computedProp4: Int { mutating get nonmutating set }{{$}}
subscript(i: Float) -> Int {
get {
return 42
}
nonmutating set {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} subscript(i: Float) -> Int { get nonmutating set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} subscript(i: Float) -> Int { get nonmutating set }{{$}}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} init(){{$}}
// PASS_RW_PROP_GET_SET-NEXT: {{^}}}{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} init(){{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}}}{{$}}
extension d0110_ReadWriteProperties {
// PASS_RW_PROP_GET_SET-LABEL: {{^}}extension d0110_ReadWriteProperties {{{$}}
// PASS_RW_PROP_NO_GET_SET-LABEL: {{^}}extension d0110_ReadWriteProperties {{{$}}
var extProp: Int {
get {
return 42
}
set(v) {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} var extProp: Int { get set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var extProp: Int{{$}}
static var extStaticProp: Int {
get {
return 42
}
set(v) {}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}} static var extStaticProp: Int { get set }{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} static var extStaticProp: Int{{$}}
}
// PASS_RW_PROP_GET_SET-NEXT: {{^}}}{{$}}
// PASS_RW_PROP_NO_GET_SET-NEXT: {{^}}}{{$}}
class d0120_TestClassBase {
// PASS_COMMON-LABEL: {{^}}class d0120_TestClassBase {{{$}}
required init() {}
// PASS_COMMON-NEXT: {{^}} required init(){{$}}
// FIXME: Add these once we can SILGen them reasonable.
// init?(fail: String) { }
// init!(iuoFail: String) { }
final func baseFunc1() {}
// PASS_COMMON-NEXT: {{^}} final func baseFunc1(){{$}}
func baseFunc2() {}
// PASS_COMMON-NEXT: {{^}} func baseFunc2(){{$}}
subscript(i: Int) -> Int {
return 0
}
// PASS_COMMON-NEXT: {{^}} subscript(i: Int) -> Int { get }{{$}}
class var baseClassVar1: Int { return 0 }
// PASS_COMMON-NEXT: {{^}} class var baseClassVar1: Int { get }{{$}}
// FIXME: final class var not allowed to have storage, but static is?
// final class var baseClassVar2: Int = 0
final class var baseClassVar3: Int { return 0 }
// PASS_COMMON-NEXT: {{^}} final class var baseClassVar3: Int { get }{{$}}
static var baseClassVar4: Int = 0
// PASS_COMMON-NEXT: {{^}} static var baseClassVar4: Int{{$}}
static var baseClassVar5: Int { return 0 }
// PASS_COMMON-NEXT: {{^}} static var baseClassVar5: Int { get }{{$}}
class func baseClassFunc1() {}
// PASS_COMMON-NEXT: {{^}} class func baseClassFunc1(){{$}}
final class func baseClassFunc2() {}
// PASS_COMMON-NEXT: {{^}} final class func baseClassFunc2(){{$}}
static func baseClassFunc3() {}
// PASS_COMMON-NEXT: {{^}} static func baseClassFunc3(){{$}}
}
class d0121_TestClassDerived : d0120_TestClassBase {
// PASS_COMMON-LABEL: {{^}}class d0121_TestClassDerived : d0120_TestClassBase {{{$}}
required init() { super.init() }
// PASS_COMMON-NEXT: {{^}} required init(){{$}}
final override func baseFunc2() {}
// PASS_COMMON-NEXT: {{^}} {{(override |final )+}}func baseFunc2(){{$}}
override final subscript(i: Int) -> Int {
return 0
}
// PASS_COMMON-NEXT: {{^}} override final subscript(i: Int) -> Int { get }{{$}}
}
protocol d0130_TestProtocol {
// PASS_COMMON-LABEL: {{^}}protocol d0130_TestProtocol {{{$}}
associatedtype NestedTypealias
// PASS_COMMON-NEXT: {{^}} associatedtype NestedTypealias{{$}}
var property1: Int { get }
// PASS_COMMON-NEXT: {{^}} var property1: Int { get }{{$}}
var property2: Int { get set }
// PASS_COMMON-NEXT: {{^}} var property2: Int { get set }{{$}}
func protocolFunc1()
// PASS_COMMON-NEXT: {{^}} func protocolFunc1(){{$}}
}
@objc protocol d0140_TestObjCProtocol {
// PASS_COMMON-LABEL: {{^}}@objc protocol d0140_TestObjCProtocol {{{$}}
@objc optional var property1: Int { get }
// PASS_COMMON-NEXT: {{^}} @objc optional var property1: Int { get }{{$}}
@objc optional func protocolFunc1()
// PASS_COMMON-NEXT: {{^}} @objc optional func protocolFunc1(){{$}}
}
protocol d0150_TestClassProtocol : class {}
// PASS_COMMON-LABEL: {{^}}protocol d0150_TestClassProtocol : class {{{$}}
@objc protocol d0151_TestClassProtocol {}
// PASS_COMMON-LABEL: {{^}}@objc protocol d0151_TestClassProtocol {{{$}}
class d0170_TestAvailability {
// PASS_COMMON-LABEL: {{^}}class d0170_TestAvailability {{{$}}
@available(*, unavailable)
func f1() {}
// PASS_COMMON-NEXT: {{^}} @available(*, unavailable){{$}}
// PASS_COMMON-NEXT: {{^}} func f1(){{$}}
@available(*, unavailable, message: "aaa \"bbb\" ccc\nddd\0eee")
func f2() {}
// PASS_COMMON-NEXT: {{^}} @available(*, unavailable, message: "aaa \"bbb\" ccc\nddd\0eee"){{$}}
// PASS_COMMON-NEXT: {{^}} func f2(){{$}}
@available(iOS, unavailable)
@available(OSX, unavailable)
func f3() {}
// PASS_COMMON-NEXT: {{^}} @available(iOS, unavailable){{$}}
// PASS_COMMON-NEXT: {{^}} @available(OSX, unavailable){{$}}
// PASS_COMMON-NEXT: {{^}} func f3(){{$}}
@available(iOS 8.0, OSX 10.10, *)
func f4() {}
// PASS_COMMON-NEXT: {{^}} @available(iOS 8.0, OSX 10.10, *){{$}}
// PASS_COMMON-NEXT: {{^}} func f4(){{$}}
// Convert long-form @available() to short form when possible.
@available(iOS, introduced: 8.0)
@available(OSX, introduced: 10.10)
func f5() {}
// PASS_COMMON-NEXT: {{^}} @available(iOS 8.0, OSX 10.10, *){{$}}
// PASS_COMMON-NEXT: {{^}} func f5(){{$}}
}
@objc class d0180_TestIBAttrs {
// PASS_COMMON-LABEL: {{^}}@objc class d0180_TestIBAttrs {{{$}}
@IBAction func anAction(_: AnyObject) {}
// PASS_COMMON-NEXT: {{^}} @IBAction @objc func anAction(_: AnyObject){{$}}
@IBDesignable
class ADesignableClass {}
// PASS_COMMON-NEXT: {{^}} @IBDesignable class ADesignableClass {{{$}}
}
@objc class d0181_TestIBAttrs {
// PASS_EXPLODE_PATTERN-LABEL: {{^}}@objc class d0181_TestIBAttrs {{{$}}
@IBOutlet weak var anOutlet: d0181_TestIBAttrs!
// PASS_EXPLODE_PATTERN-NEXT: {{^}} @IBOutlet @objc weak var anOutlet: @sil_weak d0181_TestIBAttrs!{{$}}
@IBInspectable var inspectableProp: Int = 0
// PASS_EXPLODE_PATTERN-NEXT: {{^}} @IBInspectable @objc var inspectableProp: Int{{$}}
@GKInspectable var inspectableProp2: Int = 0
// PASS_EXPLODE_PATTERN-NEXT: {{^}} @GKInspectable @objc var inspectableProp2: Int{{$}}
}
struct d0190_LetVarDecls {
// PASS_PRINT_AST-LABEL: {{^}}struct d0190_LetVarDecls {{{$}}
// PASS_PRINT_MODULE_INTERFACE-LABEL: {{^}}struct d0190_LetVarDecls {{{$}}
let instanceVar1: Int = 0
// PASS_PRINT_AST-NEXT: {{^}} let instanceVar1: Int{{$}}
// PASS_PRINT_MODULE_INTERFACE-NEXT: {{^}} let instanceVar1: Int{{$}}
let instanceVar2 = 0
// PASS_PRINT_AST-NEXT: {{^}} let instanceVar2: Int{{$}}
// PASS_PRINT_MODULE_INTERFACE-NEXT: {{^}} let instanceVar2: Int{{$}}
static let staticVar1: Int = 42
// PASS_PRINT_AST-NEXT: {{^}} static let staticVar1: Int{{$}}
// PASS_PRINT_MODULE_INTERFACE-NEXT: {{^}} static let staticVar1: Int{{$}}
static let staticVar2 = 42
// FIXME: PRINTED_WITHOUT_TYPE
// PASS_PRINT_AST-NEXT: {{^}} static let staticVar2: Int{{$}}
// PASS_PRINT_MODULE_INTERFACE-NEXT: {{^}} static let staticVar2: Int{{$}}
}
struct d0200_EscapedIdentifiers {
// PASS_COMMON-LABEL: {{^}}struct d0200_EscapedIdentifiers {{{$}}
struct `struct` {}
// PASS_COMMON-NEXT: {{^}} struct `struct` {{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
enum `enum` {
case `case`
}
// PASS_COMMON-NEXT: {{^}} enum `enum` {{{$}}
// PASS_COMMON-NEXT: {{^}} case `case`{{$}}
// PASS_COMMON-NEXT: {{^}} {{.*}}static func __derived_enum_equals(_ a: d0200_EscapedIdentifiers.`enum`, _ b: d0200_EscapedIdentifiers.`enum`) -> Bool
// PASS_COMMON-NEXT: {{^}} var hashValue: Int { get }{{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
class `class` {}
// PASS_COMMON-NEXT: {{^}} class `class` {{{$}}
// PASS_COMMON-NEXT: {{^}} @objc deinit{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
typealias `protocol` = `class`
// PASS_ONE_LINE_TYPE-DAG: {{^}} typealias `protocol` = d0200_EscapedIdentifiers.`class`{{$}}
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}} typealias `protocol` = `class`{{$}}
class `extension` : `class` {}
// PASS_ONE_LINE_TYPE-DAG: {{^}} class `extension` : d0200_EscapedIdentifiers.`class` {{{$}}
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}} class `extension` : `class` {{{$}}
// PASS_COMMON: {{^}} @objc deinit{{$}}
// PASS_COMMON-NEXT: {{^}} {{(override )?}}init(){{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
func `func`<`let`: `protocol`, `where`>(
class: Int, struct: `protocol`, foo: `let`, bar: `where`) where `where` : `protocol` {}
// PASS_COMMON-NEXT: {{^}} func `func`<`let`, `where`>(class: Int, struct: {{(d0200_EscapedIdentifiers.)?}}`protocol`, foo: `let`, bar: `where`) where `let` : {{(d0200_EscapedIdentifiers.)?}}`protocol`, `where` : {{(d0200_EscapedIdentifiers.)?}}`protocol`{{$}}
var `var`: `struct` = `struct`()
// PASS_COMMON-NEXT: {{^}} var `var`: {{(d0200_EscapedIdentifiers.)?}}`struct`{{$}}
var tupleType: (`var`: Int, `let`: `struct`)
// PASS_COMMON-NEXT: {{^}} var tupleType: (`var`: Int, `let`: {{(d0200_EscapedIdentifiers.)?}}`struct`){{$}}
var accessors1: Int {
get { return 0 }
set(`let`) {}
}
// PASS_COMMON-NEXT: {{^}} var accessors1: Int{{( { get set })?}}{{$}}
static func `static`(protocol: Int) {}
// PASS_COMMON-NEXT: {{^}} static func `static`(protocol: Int){{$}}
// PASS_COMMON-NEXT: {{^}} init(`var`: {{(d0200_EscapedIdentifiers.)?}}`struct`, tupleType: (`var`: Int, `let`: {{(d0200_EscapedIdentifiers.)?}}`struct`)){{$}}
// PASS_COMMON-NEXT: {{^}}}{{$}}
}
struct d0210_Qualifications {
// PASS_QUAL_UNQUAL: {{^}}struct d0210_Qualifications {{{$}}
// PASS_QUAL_IF_AMBIGUOUS: {{^}}struct d0210_Qualifications {{{$}}
var propFromStdlib1: Int = 0
// PASS_QUAL_UNQUAL-NEXT: {{^}} var propFromStdlib1: Int{{$}}
// PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} var propFromStdlib1: Int{{$}}
var propFromSwift1: FooSwiftStruct = FooSwiftStruct()
// PASS_QUAL_UNQUAL-NEXT: {{^}} var propFromSwift1: FooSwiftStruct{{$}}
// PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} var propFromSwift1: foo_swift_module.FooSwiftStruct{{$}}
var propFromClang1: FooStruct1 = FooStruct1(x: 0, y: 0.0)
// PASS_QUAL_UNQUAL-NEXT: {{^}} var propFromClang1: FooStruct1{{$}}
// PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} var propFromClang1: FooStruct1{{$}}
func instanceFuncFromStdlib1(a: Int) -> Float {
return 0.0
}
// PASS_QUAL_UNQUAL-NEXT: {{^}} func instanceFuncFromStdlib1(a: Int) -> Float{{$}}
// PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} func instanceFuncFromStdlib1(a: Int) -> Float{{$}}
func instanceFuncFromStdlib2(a: ObjCBool) {}
// PASS_QUAL_UNQUAL-NEXT: {{^}} func instanceFuncFromStdlib2(a: ObjCBool){{$}}
// PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} func instanceFuncFromStdlib2(a: ObjCBool){{$}}
func instanceFuncFromSwift1(a: FooSwiftStruct) -> FooSwiftStruct {
return FooSwiftStruct()
}
// PASS_QUAL_UNQUAL-NEXT: {{^}} func instanceFuncFromSwift1(a: FooSwiftStruct) -> FooSwiftStruct{{$}}
// PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} func instanceFuncFromSwift1(a: foo_swift_module.FooSwiftStruct) -> foo_swift_module.FooSwiftStruct{{$}}
func instanceFuncFromClang1(a: FooStruct1) -> FooStruct1 {
return FooStruct1(x: 0, y: 0.0)
}
// PASS_QUAL_UNQUAL-NEXT: {{^}} func instanceFuncFromClang1(a: FooStruct1) -> FooStruct1{{$}}
// PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} func instanceFuncFromClang1(a: FooStruct1) -> FooStruct1{{$}}
}
// FIXME: this should be printed reasonably in case we use
// -prefer-type-repr=true. Either we should print the types we inferred, or we
// should print the initializers.
class d0250_ExplodePattern {
// PASS_EXPLODE_PATTERN-LABEL: {{^}}class d0250_ExplodePattern {{{$}}
var instanceVar1 = 0
var instanceVar2 = 0.0
var instanceVar3 = ""
// PASS_EXPLODE_PATTERN: {{^}} var instanceVar1: Int{{$}}
// PASS_EXPLODE_PATTERN: {{^}} var instanceVar2: Double{{$}}
// PASS_EXPLODE_PATTERN: {{^}} var instanceVar3: String{{$}}
var instanceVar4 = FooStruct()
var (instanceVar5, instanceVar6) = (FooStruct(), FooStruct())
var (instanceVar7, instanceVar8) = (FooStruct(), FooStruct())
var (instanceVar9, instanceVar10) : (FooStruct, FooStruct) = (FooStruct(), FooStruct())
final var (instanceVar11, instanceVar12) = (FooStruct(), FooStruct())
// PASS_EXPLODE_PATTERN: {{^}} var instanceVar4: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} var instanceVar5: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} var instanceVar6: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} var instanceVar7: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} var instanceVar8: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} var instanceVar9: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} var instanceVar10: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} final var instanceVar11: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} final var instanceVar12: FooStruct{{$}}
let instanceLet1 = 0
let instanceLet2 = 0.0
let instanceLet3 = ""
// PASS_EXPLODE_PATTERN: {{^}} final let instanceLet1: Int{{$}}
// PASS_EXPLODE_PATTERN: {{^}} final let instanceLet2: Double{{$}}
// PASS_EXPLODE_PATTERN: {{^}} final let instanceLet3: String{{$}}
let instanceLet4 = FooStruct()
let (instanceLet5, instanceLet6) = (FooStruct(), FooStruct())
let (instanceLet7, instanceLet8) = (FooStruct(), FooStruct())
let (instanceLet9, instanceLet10) : (FooStruct, FooStruct) = (FooStruct(), FooStruct())
// PASS_EXPLODE_PATTERN: {{^}} final let instanceLet4: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} final let instanceLet5: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} final let instanceLet6: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} final let instanceLet7: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} final let instanceLet8: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} final let instanceLet9: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} final let instanceLet10: FooStruct{{$}}
}
class d0260_ExplodePattern_TestClassBase {
// PASS_EXPLODE_PATTERN-LABEL: {{^}}class d0260_ExplodePattern_TestClassBase {{{$}}
init() {
baseProp1 = 0
}
// PASS_EXPLODE_PATTERN-NEXT: {{^}} init(){{$}}
final var baseProp1: Int
// PASS_EXPLODE_PATTERN-NEXT: {{^}} final var baseProp1: Int{{$}}
var baseProp2: Int {
get {
return 0
}
set {}
}
// PASS_EXPLODE_PATTERN-NEXT: {{^}} var baseProp2: Int{{$}}
}
class d0261_ExplodePattern_TestClassDerived : d0260_ExplodePattern_TestClassBase {
// PASS_EXPLODE_PATTERN-LABEL: {{^}}class d0261_ExplodePattern_TestClassDerived : d0260_ExplodePattern_TestClassBase {{{$}}
override final var baseProp2: Int {
get {
return 0
}
set {}
}
// PASS_EXPLODE_PATTERN-NEXT: {{^}} override final var baseProp2: Int{{$}}
}
//===---
//===--- Inheritance list in structs.
//===---
struct StructWithoutInheritance1 {}
// PASS_ONE_LINE-DAG: {{^}}struct StructWithoutInheritance1 {{{$}}
struct StructWithInheritance1 : FooProtocol {}
// PASS_ONE_LINE-DAG: {{^}}struct StructWithInheritance1 : FooProtocol {{{$}}
struct StructWithInheritance2 : FooProtocol, BarProtocol {}
// PASS_ONE_LINE-DAG: {{^}}struct StructWithInheritance2 : FooProtocol, BarProtocol {{{$}}
struct StructWithInheritance3 : QuxProtocol, SubFooProtocol {
typealias Qux = Int
}
// PASS_ONE_LINE-DAG: {{^}}struct StructWithInheritance3 : QuxProtocol, SubFooProtocol {{{$}}
//===---
//===--- Inheritance list in classes.
//===---
class ClassWithoutInheritance1 {}
// PASS_ONE_LINE-DAG: {{^}}class ClassWithoutInheritance1 {{{$}}
class ClassWithInheritance1 : FooProtocol {}
// PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance1 : FooProtocol {{{$}}
class ClassWithInheritance2 : FooProtocol, BarProtocol {}
// PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance2 : FooProtocol, BarProtocol {{{$}}
class ClassWithInheritance3 : FooClass {}
// PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance3 : FooClass {{{$}}
class ClassWithInheritance4 : FooClass, FooProtocol {}
// PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance4 : FooClass, FooProtocol {{{$}}
class ClassWithInheritance5 : FooClass, FooProtocol, BarProtocol {}
// PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance5 : FooClass, FooProtocol, BarProtocol {{{$}}
class ClassWithInheritance6 : QuxProtocol, SubFooProtocol {
typealias Qux = Int
}
// PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance6 : QuxProtocol, SubFooProtocol {{{$}}
//===---
//===--- Inheritance list in enums.
//===---
enum EnumWithoutInheritance1 {}
// PASS_ONE_LINE-DAG: {{^}}enum EnumWithoutInheritance1 {{{$}}
enum EnumWithInheritance1 : FooProtocol {}
// PASS_ONE_LINE-DAG: {{^}}enum EnumWithInheritance1 : FooProtocol {{{$}}
enum EnumWithInheritance2 : FooProtocol, BarProtocol {}
// PASS_ONE_LINE-DAG: {{^}}enum EnumWithInheritance2 : FooProtocol, BarProtocol {{{$}}
enum EnumDeclWithUnderlyingType1 : Int { case X }
// PASS_ONE_LINE-DAG: {{^}}enum EnumDeclWithUnderlyingType1 : Int {{{$}}
enum EnumDeclWithUnderlyingType2 : Int, FooProtocol { case X }
// PASS_ONE_LINE-DAG: {{^}}enum EnumDeclWithUnderlyingType2 : Int, FooProtocol {{{$}}
enum EnumWithInheritance3 : QuxProtocol, SubFooProtocol {
typealias Qux = Int
}
// PASS_ONE_LINE-DAG: {{^}}enum EnumWithInheritance3 : QuxProtocol, SubFooProtocol {{{$}}
//===---
//===--- Inheritance list in protocols.
//===---
protocol ProtocolWithoutInheritance1 {}
// PASS_ONE_LINE-DAG: {{^}}protocol ProtocolWithoutInheritance1 {{{$}}
protocol ProtocolWithInheritance1 : FooProtocol {}
// PASS_ONE_LINE-DAG: {{^}}protocol ProtocolWithInheritance1 : FooProtocol {{{$}}
protocol ProtocolWithInheritance2 : FooProtocol, BarProtocol { }
// PASS_ONE_LINE-DAG: {{^}}protocol ProtocolWithInheritance2 : FooProtocol, BarProtocol {{{$}}
protocol ProtocolWithInheritance3 : QuxProtocol, SubFooProtocol {
}
// PASS_ONE_LINE-DAG: {{^}}protocol ProtocolWithInheritance3 : QuxProtocol, SubFooProtocol {{{$}}
//===---
//===--- Inheritance list in extensions
//===---
struct StructInherited { }
// PASS_ONE_LINE-DAG: {{.*}}extension StructInherited : QuxProtocol, SubFooProtocol {{{$}}
extension StructInherited : QuxProtocol, SubFooProtocol {
typealias Qux = Int
}
//===---
//===--- Typealias printing.
//===---
// Normal typealiases.
typealias SimpleTypealias1 = FooProtocol
// PASS_ONE_LINE-DAG: {{^}}typealias SimpleTypealias1 = FooProtocol{{$}}
// Associated types.
protocol AssociatedType1 {
associatedtype AssociatedTypeDecl1 = Int
// PASS_ONE_LINE-DAG: {{^}} associatedtype AssociatedTypeDecl1 = Int{{$}}
associatedtype AssociatedTypeDecl2 : FooProtocol
// PASS_ONE_LINE-DAG: {{^}} associatedtype AssociatedTypeDecl2 : FooProtocol{{$}}
associatedtype AssociatedTypeDecl3 : FooProtocol, BarProtocol
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}} associatedtype AssociatedTypeDecl3 : FooProtocol, BarProtocol{{$}}
associatedtype AssociatedTypeDecl4 where AssociatedTypeDecl4 : QuxProtocol, AssociatedTypeDecl4.Qux == Int
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}} associatedtype AssociatedTypeDecl4 where Self.AssociatedTypeDecl4 : QuxProtocol, Self.AssociatedTypeDecl4.Qux == Int{{$}}
}
//===---
//===--- Variable declaration printing.
//===---
var d0300_topLevelVar1: Int = 42
// PASS_COMMON: {{^}}var d0300_topLevelVar1: Int{{$}}
// PASS_COMMON-NOT: d0300_topLevelVar1
var d0400_topLevelVar2: Int = 42
// PASS_COMMON: {{^}}var d0400_topLevelVar2: Int{{$}}
// PASS_COMMON-NOT: d0400_topLevelVar2
var d0500_topLevelVar2: Int {
get {
return 42
}
}
// PASS_COMMON: {{^}}var d0500_topLevelVar2: Int { get }{{$}}
// PASS_COMMON-NOT: d0500_topLevelVar2
class d0600_InClassVar1 {
// PASS_O600-LABEL: d0600_InClassVar1
var instanceVar1: Int
// PASS_COMMON: {{^}} var instanceVar1: Int{{$}}
// PASS_COMMON-NOT: instanceVar1
var instanceVar2: Int = 42
// PASS_COMMON: {{^}} var instanceVar2: Int{{$}}
// PASS_COMMON-NOT: instanceVar2
// FIXME: this is sometimes printed without a type, see PASS_EXPLODE_PATTERN.
// FIXME: PRINTED_WITHOUT_TYPE
var instanceVar3 = 42
// PASS_COMMON: {{^}} var instanceVar3
// PASS_COMMON-NOT: instanceVar3
var instanceVar4: Int {
get {
return 42
}
}
// PASS_COMMON: {{^}} var instanceVar4: Int { get }{{$}}
// PASS_COMMON-NOT: instanceVar4
// FIXME: uncomment when we have static vars.
// static var staticVar1: Int
init() {
instanceVar1 = 10
}
}
//===---
//===--- Subscript declaration printing.
//===---
class d0700_InClassSubscript1 {
// PASS_COMMON-LABEL: d0700_InClassSubscript1
subscript(i: Int) -> Int {
get {
return 42
}
}
subscript(index i: Float) -> Int { return 42 }
class `class` {}
subscript(x: Float) -> `class` { return `class`() }
// PASS_COMMON: {{^}} subscript(i: Int) -> Int { get }{{$}}
// PASS_COMMON: {{^}} subscript(index i: Float) -> Int { get }{{$}}
// PASS_COMMON: {{^}} subscript(x: Float) -> {{.*}} { get }{{$}}
// PASS_COMMON-NOT: subscript
// PASS_ONE_LINE_TYPE: {{^}} subscript(x: Float) -> d0700_InClassSubscript1.`class` { get }{{$}}
// PASS_ONE_LINE_TYPEREPR: {{^}} subscript(x: Float) -> `class` { get }{{$}}
}
// PASS_COMMON: {{^}}}{{$}}
//===---
//===--- Constructor declaration printing.
//===---
struct d0800_ExplicitConstructors1 {
// PASS_COMMON-LABEL: d0800_ExplicitConstructors1
init() {}
// PASS_COMMON: {{^}} init(){{$}}
init(a: Int) {}
// PASS_COMMON: {{^}} init(a: Int){{$}}
}
struct d0900_ExplicitConstructorsSelector1 {
// PASS_COMMON-LABEL: d0900_ExplicitConstructorsSelector1
init(int a: Int) {}
// PASS_COMMON: {{^}} init(int a: Int){{$}}
init(int a: Int, andFloat b: Float) {}
// PASS_COMMON: {{^}} init(int a: Int, andFloat b: Float){{$}}
}
struct d1000_ExplicitConstructorsSelector2 {
// PASS_COMMON-LABEL: d1000_ExplicitConstructorsSelector2
init(noArgs _: ()) {}
// PASS_COMMON: {{^}} init(noArgs _: ()){{$}}
init(_ a: Int) {}
// PASS_COMMON: {{^}} init(_ a: Int){{$}}
init(_ a: Int, withFloat b: Float) {}
// PASS_COMMON: {{^}} init(_ a: Int, withFloat b: Float){{$}}
init(int a: Int, _ b: Float) {}
// PASS_COMMON: {{^}} init(int a: Int, _ b: Float){{$}}
}
//===---
//===--- Destructor declaration printing.
//===---
class d1100_ExplicitDestructor1 {
// PASS_COMMON-LABEL: d1100_ExplicitDestructor1
deinit {}
// PASS_COMMON: {{^}} @objc deinit{{$}}
}
//===---
//===--- Enum declaration printing.
//===---
enum d2000_EnumDecl1 {
case ED1_First
case ED1_Second
}
// PASS_COMMON: {{^}}enum d2000_EnumDecl1 {{{$}}
// PASS_COMMON-NEXT: {{^}} case ED1_First{{$}}
// PASS_COMMON-NEXT: {{^}} case ED1_Second{{$}}
// PASS_COMMON-NEXT: {{^}} {{.*}}static func __derived_enum_equals(_ a: d2000_EnumDecl1, _ b: d2000_EnumDecl1) -> Bool
// PASS_COMMON-NEXT: {{^}} var hashValue: Int { get }{{$}}
// PASS_COMMON-NEXT: {{^}}}{{$}}
enum d2100_EnumDecl2 {
case ED2_A(Int)
case ED2_B(Float)
case ED2_C(Int, Float)
case ED2_D(x: Int, y: Float)
case ED2_E(x: Int, y: (Float, Double))
case ED2_F(x: Int, (y: Float, z: Double))
}
// PASS_COMMON: {{^}}enum d2100_EnumDecl2 {{{$}}
// PASS_COMMON-NEXT: {{^}} case ED2_A(Int){{$}}
// PASS_COMMON-NEXT: {{^}} case ED2_B(Float){{$}}
// PASS_COMMON-NEXT: {{^}} case ED2_C(Int, Float){{$}}
// PASS_COMMON-NEXT: {{^}} case ED2_D(x: Int, y: Float){{$}}
// PASS_COMMON-NEXT: {{^}} case ED2_E(x: Int, y: (Float, Double)){{$}}
// PASS_COMMON-NEXT: {{^}} case ED2_F(x: Int, (y: Float, z: Double)){{$}}
// PASS_COMMON-NEXT: {{^}}}{{$}}
enum d2200_EnumDecl3 {
case ED3_A, ED3_B
case ED3_C(Int), ED3_D
case ED3_E, ED3_F(Int)
case ED3_G(Int), ED3_H(Int)
case ED3_I(Int), ED3_J(Int), ED3_K
}
// PASS_2200: {{^}}enum d2200_EnumDecl3 {{{$}}
// PASS_2200-NEXT: {{^}} case ED3_A, ED3_B{{$}}
// PASS_2200-NEXT: {{^}} case ED3_C(Int), ED3_D{{$}}
// PASS_2200-NEXT: {{^}} case ED3_E, ED3_F(Int){{$}}
// PASS_2200-NEXT: {{^}} case ED3_G(Int), ED3_H(Int){{$}}
// PASS_2200-NEXT: {{^}} case ED3_I(Int), ED3_J(Int), ED3_K{{$}}
// PASS_2200-NEXT: {{^}}}{{$}}
// PASS_2200_DESERIALIZED: {{^}}enum d2200_EnumDecl3 {{{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_A{{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_B{{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_C(Int){{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_D{{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_E{{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_F(Int){{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_G(Int){{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_H(Int){{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_I(Int){{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_J(Int){{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_K{{$}}
// PASS_2200_DESERIALIZED-NEXT: {{^}}}{{$}}
enum d2300_EnumDeclWithValues1 : Int {
case EDV2_First = 10
case EDV2_Second
}
// PASS_COMMON: {{^}}enum d2300_EnumDeclWithValues1 : Int {{{$}}
// PASS_COMMON-NEXT: {{^}} case EDV2_First{{$}}
// PASS_COMMON-NEXT: {{^}} case EDV2_Second{{$}}
// PASS_COMMON-NEXT: {{^}} typealias RawValue = Int
// PASS_COMMON-NEXT: {{^}} var hashValue: Int { get }{{$}}
// PASS_COMMON-NEXT: {{^}} init?(rawValue: Int){{$}}
// PASS_COMMON-NEXT: {{^}} var rawValue: Int { get }{{$}}
// PASS_COMMON-NEXT: {{^}}}{{$}}
enum d2400_EnumDeclWithValues2 : Double {
case EDV3_First = 10
case EDV3_Second
}
// PASS_COMMON: {{^}}enum d2400_EnumDeclWithValues2 : Double {{{$}}
// PASS_COMMON-NEXT: {{^}} case EDV3_First{{$}}
// PASS_COMMON-NEXT: {{^}} case EDV3_Second{{$}}
// PASS_COMMON-NEXT: {{^}} typealias RawValue = Double
// PASS_COMMON-NEXT: {{^}} var hashValue: Int { get }{{$}}
// PASS_COMMON-NEXT: {{^}} init?(rawValue: Double){{$}}
// PASS_COMMON-NEXT: {{^}} var rawValue: Double { get }{{$}}
// PASS_COMMON-NEXT: {{^}}}{{$}}
//===---
//===--- Custom operator printing.
//===---
postfix operator <*>
// PASS_2500-LABEL: {{^}}postfix operator <*>{{$}}
protocol d2600_ProtocolWithOperator1 {
static postfix func <*>(_: Self)
}
// PASS_2500: {{^}}protocol d2600_ProtocolWithOperator1 {{{$}}
// PASS_2500-NEXT: {{^}} postfix static func <*>(_: Self){{$}}
// PASS_2500-NEXT: {{^}}}{{$}}
struct d2601_TestAssignment {}
infix operator %%%
func %%%(lhs: inout d2601_TestAssignment, rhs: d2601_TestAssignment) -> Int {
return 0
}
// PASS_2500-LABEL: {{^}}infix operator %%%{{$}}
// PASS_2500: {{^}}func %%%(lhs: inout d2601_TestAssignment, rhs: d2601_TestAssignment) -> Int{{$}}
precedencegroup BoringPrecedence {
// PASS_2500-LABEL: {{^}}precedencegroup BoringPrecedence {{{$}}
associativity: left
// PASS_2500-NEXT: {{^}} associativity: left{{$}}
higherThan: AssignmentPrecedence
// PASS_2500-NEXT: {{^}} higherThan: AssignmentPrecedence{{$}}
// PASS_2500-NOT: assignment
// PASS_2500-NOT: lowerThan
}
precedencegroup ReallyBoringPrecedence {
// PASS_2500-LABEL: {{^}}precedencegroup ReallyBoringPrecedence {{{$}}
associativity: right
// PASS_2500-NEXT: {{^}} associativity: right{{$}}
// PASS_2500-NOT: higherThan
// PASS_2500-NOT: lowerThan
// PASS_2500-NOT: assignment
}
precedencegroup BoringAssignmentPrecedence {
// PASS_2500-LABEL: {{^}}precedencegroup BoringAssignmentPrecedence {{{$}}
lowerThan: AssignmentPrecedence
assignment: true
// PASS_2500-NEXT: {{^}} assignment: true{{$}}
// PASS_2500-NEXT: {{^}} lowerThan: AssignmentPrecedence{{$}}
// PASS_2500-NOT: associativity
// PASS_2500-NOT: higherThan
}
// PASS_2500: {{^}}}{{$}}
//===---
//===--- Printing of deduced associated types.
//===---
protocol d2700_ProtocolWithAssociatedType1 {
associatedtype TA1
func returnsTA1() -> TA1
}
// PREFER_TYPE_PRINTING: {{^}}protocol d2700_ProtocolWithAssociatedType1 {{{$}}
// PREFER_TYPE_PRINTING-NEXT: {{^}} associatedtype TA1{{$}}
// PREFER_TYPE_PRINTING-NEXT: {{^}} func returnsTA1() -> Self.TA1{{$}}
// PREFER_TYPE_PRINTING-NEXT: {{^}}}{{$}}
// PREFER_TYPEREPR_PRINTING: {{^}}protocol d2700_ProtocolWithAssociatedType1 {{{$}}
// PREFER_TYPEREPR_PRINTING-NEXT: {{^}} associatedtype TA1{{$}}
// PREFER_TYPEREPR_PRINTING-NEXT: {{^}} func returnsTA1() -> TA1{{$}}
// PREFER_TYPEREPR_PRINTING-NEXT: {{^}}}{{$}}
struct d2800_ProtocolWithAssociatedType1Impl : d2700_ProtocolWithAssociatedType1 {
func returnsTA1() -> Int {
return 42
}
}
// PASS_COMMON: {{^}}struct d2800_ProtocolWithAssociatedType1Impl : d2700_ProtocolWithAssociatedType1 {{{$}}
// PASS_COMMON-NEXT: {{^}} func returnsTA1() -> Int{{$}}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}} typealias TA1 = Int
// PASS_COMMON-NEXT: {{^}}}{{$}}
//===---
//===--- Generic parameter list printing.
//===---
struct GenericParams1<
StructGenericFoo : FooProtocol,
StructGenericFooX : FooClass,
StructGenericBar : FooProtocol & BarProtocol,
StructGenericBaz> {
// PASS_ONE_LINE_TYPE-DAG: {{^}}struct GenericParams1<StructGenericFoo, StructGenericFooX, StructGenericBar, StructGenericBaz> where StructGenericFoo : FooProtocol, StructGenericFooX : FooClass, StructGenericBar : BarProtocol, StructGenericBar : FooProtocol {{{$}}
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}}struct GenericParams1<StructGenericFoo, StructGenericFooX, StructGenericBar, StructGenericBaz> where StructGenericFoo : FooProtocol, StructGenericFooX : FooClass, StructGenericBar : BarProtocol, StructGenericBar : FooProtocol {{{$}}
init<
GenericFoo : FooProtocol,
GenericFooX : FooClass,
GenericBar : FooProtocol & BarProtocol,
GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz,
d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz)
{}
// PASS_ONE_LINE_TYPE-DAG: {{^}} init<GenericFoo, GenericFooX, GenericBar, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz) where GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : BarProtocol, GenericBar : FooProtocol{{$}}
// FIXME: in protocol compositions protocols are listed in reverse order.
//
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}} init<GenericFoo, GenericFooX, GenericBar, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz) where GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : BarProtocol, GenericBar : FooProtocol{{$}}
func genericParams1<
GenericFoo : FooProtocol,
GenericFooX : FooClass,
GenericBar : FooProtocol & BarProtocol,
GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz,
d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz)
{}
// PASS_ONE_LINE_TYPE-DAG: {{^}} func genericParams1<GenericFoo, GenericFooX, GenericBar, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz) where GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : BarProtocol, GenericBar : FooProtocol{{$}}
// FIXME: in protocol compositions protocols are listed in reverse order.
//
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}} func genericParams1<GenericFoo, GenericFooX, GenericBar, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz) where GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : BarProtocol, GenericBar : FooProtocol{{$}}
}
struct GenericParams2<T : FooProtocol> where T : BarProtocol {}
// PASS_ONE_LINE-DAG: {{^}}struct GenericParams2<T> where T : BarProtocol, T : FooProtocol {{{$}}
struct GenericParams3<T : FooProtocol> where T : BarProtocol, T : QuxProtocol {}
// PASS_ONE_LINE-DAG: {{^}}struct GenericParams3<T> where T : BarProtocol, T : FooProtocol, T : QuxProtocol {{{$}}
struct GenericParams4<T : QuxProtocol> where T.Qux : FooProtocol {}
// PASS_ONE_LINE-DAG: {{^}}struct GenericParams4<T> where T : QuxProtocol, T.Qux : FooProtocol {{{$}}
struct GenericParams5<T : QuxProtocol> where T.Qux : FooProtocol & BarProtocol {}
// PREFER_TYPE_PRINTING: {{^}}struct GenericParams5<T> where T : QuxProtocol, T.Qux : BarProtocol, T.Qux : FooProtocol {{{$}}
// PREFER_TYPE_REPR_PRINTING: {{^}}struct GenericParams5<T> where T : QuxProtocol, T.Qux : BarProtocol, T.Qux : FooProtocol {{{$}}
struct GenericParams6<T : QuxProtocol, U : QuxProtocol> where T.Qux == U.Qux {}
// PREFER_TYPE_PRINTING: {{^}}struct GenericParams6<T, U> where T : QuxProtocol, U : QuxProtocol, T.Qux == U.Qux {{{$}}
// PREFER_TYPE_REPR_PRINTING: {{^}}struct GenericParams6<T, U> where T : QuxProtocol, U : QuxProtocol, T.Qux == U.Qux {{{$}}
struct GenericParams7<T : QuxProtocol, U : QuxProtocol> where T.Qux : QuxProtocol, U.Qux : QuxProtocol, T.Qux.Qux == U.Qux.Qux {}
// PREFER_TYPE_PRINTING: {{^}}struct GenericParams7<T, U> where T : QuxProtocol, U : QuxProtocol, T.Qux : QuxProtocol, U.Qux : QuxProtocol, T.Qux.Qux == U.Qux.Qux {{{$}}
// PREFER_TYPE_REPR_PRINTING: {{^}}struct GenericParams7<T, U> where T : QuxProtocol, U : QuxProtocol, T.Qux : QuxProtocol, U.Qux : QuxProtocol, T.Qux.Qux == U.Qux.Qux {{{$}}
//===---
//===--- Tupe sugar for library types.
//===---
struct d2900_TypeSugar1 {
// PASS_COMMON-LABEL: {{^}}struct d2900_TypeSugar1 {{{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-LABEL: {{^}}struct d2900_TypeSugar1 {{{$}}
func f1(x: [Int]) {}
// PASS_COMMON-NEXT: {{^}} func f1(x: [Int]){{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f1(x: [Int]){{$}}
func f2(x: Array<Int>) {}
// PASS_COMMON-NEXT: {{^}} func f2(x: Array<Int>){{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f2(x: [Int]){{$}}
func f3(x: Int?) {}
// PASS_COMMON-NEXT: {{^}} func f3(x: Int?){{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f3(x: Int?){{$}}
func f4(x: Optional<Int>) {}
// PASS_COMMON-NEXT: {{^}} func f4(x: Optional<Int>){{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f4(x: Int?){{$}}
func f5(x: [Int]...) {}
// PASS_COMMON-NEXT: {{^}} func f5(x: [Int]...){{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f5(x: [Int]...){{$}}
func f6(x: Array<Int>...) {}
// PASS_COMMON-NEXT: {{^}} func f6(x: Array<Int>...){{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f6(x: [Int]...){{$}}
func f7(x: [Int : Int]...) {}
// PASS_COMMON-NEXT: {{^}} func f7(x: [Int : Int]...){{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f7(x: [Int : Int]...){{$}}
func f8(x: Dictionary<String, Int>...) {}
// PASS_COMMON-NEXT: {{^}} func f8(x: Dictionary<String, Int>...){{$}}
// SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f8(x: [String : Int]...){{$}}
}
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}}}{{$}}
// @discardableResult attribute
public struct DiscardableThingy {
// PASS_PRINT_AST: @discardableResult
// PASS_PRINT_AST-NEXT: public init()
@discardableResult
public init() {}
// PASS_PRINT_AST: @discardableResult
// PASS_PRINT_AST-NEXT: public func useless() -> Int
@discardableResult
public func useless() -> Int { return 0 }
}
// Parameter Attributes.
// <rdar://problem/19775868> Swift 1.2b1: Header gen puts @autoclosure in the wrong place
// PASS_PRINT_AST: public func ParamAttrs1(a: @autoclosure () -> ())
public func ParamAttrs1(a : @autoclosure () -> ()) {
a()
}
// PASS_PRINT_AST: public func ParamAttrs2(a: @autoclosure @escaping () -> ())
public func ParamAttrs2(a : @autoclosure @escaping () -> ()) {
a()
}
// PASS_PRINT_AST: public func ParamAttrs3(a: () -> ())
public func ParamAttrs3(a : () -> ()) {
a()
}
// PASS_PRINT_AST: public func ParamAttrs4(a: @escaping () -> ())
public func ParamAttrs4(a : @escaping () -> ()) {
a()
}
// Setter
// PASS_PRINT_AST: class FooClassComputed {
class FooClassComputed {
// PASS_PRINT_AST: var stored: (((Int) -> Int) -> Int)?
var stored : (((Int) -> Int) -> Int)? = nil
// PASS_PRINT_AST: var computed: ((Int) -> Int) -> Int { get set }
var computed : ((Int) -> Int) -> Int {
get { return stored! }
set { stored = newValue }
}
// PASS_PRINT_AST: }
}
// Protocol extensions
protocol ProtocolToExtend {
associatedtype Assoc
}
extension ProtocolToExtend where Self.Assoc == Int {}
// PREFER_TYPE_REPR_PRINTING: extension ProtocolToExtend where Self.Assoc == Int {
// Protocol with where clauses
protocol ProtocolWithWhereClause : QuxProtocol where Qux == Int, Self : FooProtocol {}
// PREFER_TYPE_REPR_PRINTING: protocol ProtocolWithWhereClause : QuxProtocol where Self : FooProtocol, Self.Qux == Int {
protocol ProtocolWithWhereClauseAndAssoc : QuxProtocol where Qux == Int, Self : FooProtocol {
// PREFER_TYPE_REPR_PRINTING-DAG: protocol ProtocolWithWhereClauseAndAssoc : QuxProtocol where Self : FooProtocol, Self.Qux == Int {
associatedtype A1 : QuxProtocol where A1 : FooProtocol, A1.Qux : QuxProtocol, Int == A1.Qux.Qux
// PREFER_TYPE_REPR_PRINTING-DAG: {{^}} associatedtype A1 : QuxProtocol where Self.A1 : FooProtocol, Self.A1.Qux : QuxProtocol, Self.A1.Qux.Qux == Int{{$}}
// FIXME: this same type requirement with Self should be printed here
associatedtype A2 : QuxProtocol where A2.Qux == Self
// PREFER_TYPE_REPR_PRINTING-DAG: {{^}} associatedtype A2 : QuxProtocol where Self.A2.Qux == Self{{$}}
}
#if true
#elseif false
#else
#endif
// PASS_PRINT_AST: #if
// PASS_PRINT_AST: #elseif
// PASS_PRINT_AST: #else
// PASS_PRINT_AST: #endif
public struct MyPair<A, B> { var a: A, b: B }
public typealias MyPairI<B> = MyPair<Int, B>
// PASS_PRINT_AST: public typealias MyPairI<B> = MyPair<Int, B>
public typealias MyPairAlias<T, U> = MyPair<T, U>
// PASS_PRINT_AST: public typealias MyPairAlias<T, U> = MyPair<T, U>
| apache-2.0 | 2813f80dba145be72c9ff39847ac23b6 | 37.706745 | 364 | 0.645863 | 3.654967 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.