repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cdmx/MiniMancera | miniMancera/Model/Option/WhistlesVsZombies/Strategy/MOptionWhistlesVsZombiesStrategyDefeated.swift | 1 | 1418 | import Foundation
class MOptionWhistlesVsZombiesStrategyDefeated:MGameStrategyMain<MOptionWhistlesVsZombies>
{
private var startingTime:TimeInterval?
private let kWait:TimeInterval = 3.5
init(model:MOptionWhistlesVsZombies)
{
let updateItems:[MGameUpdate<MOptionWhistlesVsZombies>] = [
model.player,
model.sonicBoom,
model.zombie,
model.points,
model.hud]
super.init(
model:model,
updateItems:updateItems)
}
override func update(
elapsedTime:TimeInterval,
scene:ViewGameScene<MOptionWhistlesVsZombies>)
{
super.update(elapsedTime:elapsedTime, scene:scene)
if let startingTime:TimeInterval = self.startingTime
{
let deltaTime:TimeInterval = elapsedTime - startingTime
if deltaTime > kWait
{
timeOut(scene:scene)
}
}
else
{
startingTime = elapsedTime
}
}
//MARK: private
private func timeOut(scene:ViewGameScene<MOptionWhistlesVsZombies>)
{
guard
let controller:COptionWhistlesVsZombies = scene.controller as? COptionWhistlesVsZombies
else
{
return
}
controller.showGameOver()
}
}
| mit | ecf81804564af8fc9cefc68e5a32b4f0 | 23.448276 | 99 | 0.569111 | 5.649402 | false | false | false | false |
codescv/DQuery | DQuery/DQuery.swift | 1 | 18297 | //
// Copyright 2016 DQuery
//
// 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.
//
// DQuery.swift
//
// Created by Chi Zhang on 1/9/16.
//
import Foundation
import CoreData
// singleton API caller
public let DQ = DQAPI()
// supported store types
public enum StoreType: Int {
case SQLite
case InMemory
}
var monitorHandle: UInt8 = 0
// public APIs
public class DQAPI {
public init() {}
public enum OptionKey {
case ModelName
case StoreType
case ModelFileBundle
case StoreCoordinator
}
let dq = DQImpl()
var isConfigured = false
public func config(options: [OptionKey: Any]) {
assert(!isConfigured, "DQAPIs should only be configured once!")
let dqContext = DQContext()
for (key, val) in options {
switch key {
case .ModelName:
dqContext.modelName = val as! String
case .StoreType:
dqContext.storeType = val as! StoreType
case .ModelFileBundle:
dqContext.bundle = val as! NSBundle
case .StoreCoordinator:
dqContext.persistentStoreCoordinator = val as! NSPersistentStoreCoordinator
}
}
dq.dqContext = dqContext
isConfigured = true
}
public func objectWithID<T: NSManagedObject>(id: NSManagedObjectID) -> T {
return self.dq.dqContext.defaultContext.objectWithID(id) as! T
}
public func objectsWithIDs<T: NSManagedObject>(ids: [NSManagedObjectID]) -> [T] {
return ids.map { self.objectWithID($0) }
}
public func query<T:NSManagedObject>(entity: T.Type) -> DQQuery<T> {
assert(isConfigured, "calling query when context is not configured")
return dq.query(entity)
}
public func query<T:NSManagedObject>(entity: T.Type, context: NSManagedObjectContext) -> DQQuery<T> {
assert(isConfigured, "calling query when context is not configured")
return dq.query(entity, context: context)
}
public func insertObject<T:NSManagedObject>(entity: T.Type, block:(NSManagedObjectContext, T)->Void, sync: Bool = false, completion: ((NSManagedObjectID)->())?) {
assert(isConfigured, "calling insertObject when context is not configured")
return dq.insertObject(entity, block: block, sync: sync, completion: completion)
}
public func write(block: (NSManagedObjectContext)->Void, sync: Bool = false, completion: (()->Void)? = nil) {
assert(isConfigured, "calling write when context is not configured")
return dq.write(block, sync: sync, completion: completion)
}
public func monitor(object: AnyObject, block: ([NSObject: AnyObject])->()) {
let monitor = DQMonitor(block: block, context: dq.dqContext.defaultContext)
objc_setAssociatedObject(object, &monitorHandle, monitor, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
// wraps Core Data context
class DQContext {
var modelName: String! = nil
var storeType: StoreType = .SQLite
lazy var bundle: NSBundle = {
// print("using main bundle automatically")
return NSBundle.mainBundle()
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// create model
// print("init persistentStoreCoordinator automatically")
// print("model name: \(self.modelName)")
let modelURL = self.bundle.URLForResource(self.modelName, withExtension: "momd")!
// let modelURL = NSBundle(forClass: DQContext.self).URLForResource(self.modelName, withExtension: "momd")!
let model = NSManagedObjectModel(contentsOfURL: modelURL)!
// create coordinator
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: model)
// print("coordinator: \(coordinator)")
var coreDataStoreType: String
var url: NSURL?
switch self.storeType {
case .SQLite:
coreDataStoreType = NSSQLiteStoreType
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
let applicationDocumentsDirectory = urls[urls.count-1]
url = applicationDocumentsDirectory.URLByAppendingPathComponent("\(self.modelName).sqlite")
case .InMemory:
coreDataStoreType = NSInMemoryStoreType
}
do {
try coordinator.addPersistentStoreWithType(coreDataStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
let failureReason = "There was an error creating or loading the application's saved data."
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
// the context for main queue
lazy var defaultContext: NSManagedObjectContext = {
var context = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
context.parentContext = self.rootContext
return context
}()
// the private writer context running on background
lazy var rootContext: NSManagedObjectContext = {
var context = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
context.performBlockAndWait({
let coordinator = self.persistentStoreCoordinator
context.persistentStoreCoordinator = coordinator
})
return context
}()
// save all contexts
func save() {
self.defaultContext.performBlockAndWait({
// TODO this is run on the UI queue, count the performance
if self.defaultContext.hasChanges {
do {
try self.defaultContext.save()
// print("saved default")
} catch {
print("save default error")
return
}
}
})
self.rootContext.performBlock({
if self.rootContext.hasChanges {
do {
try self.rootContext.save()
// print("saved root")
} catch {
print("save root error")
return
}
}
})
}
}
class DQImpl {
var dqContext: DQContext! = nil
func query<T:NSManagedObject>(entity: T.Type) -> DQQuery<T> {
let entityName:String = NSStringFromClass(entity).componentsSeparatedByString(".").last!
return DQQuery<T>(entityName: entityName, context: dqContext.defaultContext)
}
func query<T:NSManagedObject>(entity: T.Type, context: NSManagedObjectContext) -> DQQuery<T> {
let entityName:String = NSStringFromClass(entity).componentsSeparatedByString(".").last!
return DQQuery<T>(entityName: entityName, context: context)
}
func insertObject<T:NSManagedObject>(entity: T.Type, block:(NSManagedObjectContext, T)->Void, sync: Bool = false, completion: ((NSManagedObjectID)->())?) {
let privateContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
privateContext.parentContext = dqContext.defaultContext
let entityName = NSStringFromClass(entity).componentsSeparatedByString(".").last!
let writeBlock = {
let obj = NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: privateContext) as! T
block(privateContext, obj)
do {
try privateContext.save()
} catch {
print("unable to save private context!")
}
self.dqContext.save()
let objId = obj.objectID
dispatch_async(dispatch_get_main_queue(), {
completion?(objId)
})
}
if sync {
privateContext.performBlockAndWait(writeBlock)
} else {
privateContext.performBlock(writeBlock)
}
}
func write(block: (NSManagedObjectContext)->Void, sync: Bool = false, completion: (()->Void)? = nil) {
let privateContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
privateContext.parentContext = dqContext.defaultContext
let writeBlock = {
block(privateContext)
do {
try privateContext.save()
} catch {
print("unable to save private context!")
}
self.dqContext.save()
dispatch_async(dispatch_get_main_queue(), {
completion?()
})
}
if sync {
privateContext.performBlockAndWait(writeBlock)
} else {
privateContext.performBlock(writeBlock)
}
}
}
public class DQQuery<T:NSManagedObject> {
let entityName: String
let context: NSManagedObjectContext
var predicate: NSPredicate?
var sortDescriptors = [NSSortDescriptor]()
var section: String?
var limit: Int?
var groupByKeys = [String]()
var selectedColumns = [String]()
var columnAliases = [String]()
private var fetchRequest: NSFetchRequest {
get {
let request = NSFetchRequest(entityName: entityName)
if let pred = predicate {
request.predicate = pred
}
request.sortDescriptors = self.sortDescriptors
if let limit = self.limit {
request.fetchLimit = limit
}
return request
}
}
public init(entityName: String, context: NSManagedObjectContext) {
self.context = context
self.entityName = entityName
}
public func filter(format: String, _ args: AnyObject...) -> Self {
let pred = NSPredicate(format: format, argumentArray: args)
if let oldPred = predicate {
predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [oldPred, pred])
} else {
predicate = pred
}
return self
}
public func select(columns: [String], asNames: [String]) -> Self {
self.selectedColumns = columns
self.columnAliases = asNames
return self
}
public func groupBy(key: String) -> DQGroupedQuery<T> {
return DQGroupedQuery<T>(keys: [key], query: self)
}
public func groupBy(keys: [String]) -> DQGroupedQuery<T> {
return DQGroupedQuery<T>(keys: keys, query: self)
}
public func orderBy(key: String, ascending: Bool = true) -> Self {
self.sortDescriptors.append(NSSortDescriptor(key: key, ascending: ascending))
return self
}
public func limit(limit: Int) -> Self {
self.limit = limit
return self
}
public func max(key: String) -> Self {
return orderBy(key, ascending: false).limit(1)
}
public func min(key: String) -> Self {
return orderBy(key, ascending: true).limit(1)
}
// sync fetch
public func all() -> [T] {
var results = [T]()
context.performBlockAndWait({
let request = self.fetchRequest
if let r = try? self.context.executeFetchRequest(request) {
results = r as! [T]
}
})
return results
}
// sync count
public func count() -> Int {
var result = 0
context.performBlockAndWait({
let request = self.fetchRequest
if let r = try? self.context.executeFetchRequest(request) {
result = r.count
}
})
return result
}
// return fist object
public func first() -> T? {
var result: T?
context.performBlockAndWait({
let request = self.fetchRequest
if let r = try? self.context.executeFetchRequest(request) {
for rr in r {
result = rr as? T
break
}
}
})
return result
}
// async fetch
public func execute(sync sync: Bool = false, complete: ((NSManagedObjectContext, [NSManagedObjectID]) -> Void)? = nil) {
let privateContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
privateContext.parentContext = self.context
let blk = {
let request = self.fetchRequest
if let results = try? privateContext.executeFetchRequest(request) {
var objectIDs = [NSManagedObjectID]()
for r in results {
objectIDs.append(r.objectID)
}
complete?(privateContext, objectIDs)
}
}
if sync {
privateContext.performBlockAndWait(blk)
} else {
privateContext.performBlock(blk)
}
}
public func fetchedResultsController(sectionNameKeyPath: String) -> NSFetchedResultsController {
return NSFetchedResultsController(fetchRequest: self.fetchRequest,
managedObjectContext: self.context,
sectionNameKeyPath: sectionNameKeyPath, cacheName: entityName)
}
}
public class DQGroupedQuery<T:NSManagedObject> {
var query: DQQuery<T>
var keys: [String]
var fetchRequest: NSFetchRequest {
let request = query.fetchRequest
var properties = [AnyObject]()
for (expr, alias) in zip(query.selectedColumns, query.columnAliases) {
let expressionDescription = NSExpressionDescription()
expressionDescription.name = alias
expressionDescription.expression = NSExpression(format: expr)
expressionDescription.expressionResultType = .FloatAttributeType
properties.append(expressionDescription)
}
for key in self.keys {
properties.append(key)
}
request.propertiesToFetch = properties
request.propertiesToGroupBy = self.keys
request.resultType = .DictionaryResultType
return request
}
init(keys: [String], query: DQQuery<T>) {
self.query = query
self.keys = keys
}
public func all() -> [[String: AnyObject]] {
var result = [[String: AnyObject]]()
query.context.performBlockAndWait({
if let r = try? self.query.context.executeFetchRequest(self.fetchRequest) {
result = r as! [[String: AnyObject]]
}
})
return result
}
// async fetch
public func execute(sync sync: Bool = false, complete: (([[String: AnyObject]]) -> Void)? = nil) {
let privateContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
privateContext.parentContext = self.query.context
let blk = {
let request = self.fetchRequest
if let results = try? privateContext.executeFetchRequest(request) {
complete?(results as! [[String: AnyObject]])
} else {
complete?([[String: AnyObject]]())
}
}
if sync {
privateContext.performBlockAndWait(blk)
} else {
privateContext.performBlock(blk)
}
}
}
class DQMonitor {
let monitorBlock: ([NSObject: AnyObject])->()
let context: NSManagedObjectContext
init(block: ([NSObject: AnyObject])->(), context: NSManagedObjectContext) {
self.monitorBlock = block
self.context = context
NSNotificationCenter.defaultCenter().addObserver(self, selector: "dataChanged:", name: NSManagedObjectContextObjectsDidChangeNotification, object: context)
}
deinit {
// print("deinit monitor!")
NSNotificationCenter.defaultCenter().removeObserver(self, name: NSManagedObjectContextObjectsDidChangeNotification, object: self.context)
}
@objc func dataChanged(notification: NSNotification) {
if notification.userInfo != nil {
monitorBlock(notification.userInfo!)
}
}
}
// TODO: move to separate file
public extension NSManagedObject {
public class func dq_insertInContext(context: NSManagedObjectContext) -> Self {
return dq_insertInContextHelper(context)
}
private class func dq_insertInContextHelper<T>(context: NSManagedObjectContext) -> T {
let entityName = NSStringFromClass(self).componentsSeparatedByString(".").last!
return NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: context) as! T
}
public func dq_delete() {
self.managedObjectContext?.deleteObject(self)
}
}
// TODO: move to separate file
public extension NSManagedObjectContext {
public func dq_objectWithID<T: NSManagedObject>(id: NSManagedObjectID) -> T {
return self.objectWithID(id) as! T
}
public func dq_objectsWithIDs<T: NSManagedObject>(ids: [NSManagedObjectID]) -> [T] {
return ids.map { (id) -> T in
dq_objectWithID(id)
}
}
}
| apache-2.0 | 61732dac50f5778f7c9cbb85290acd1b | 32.327869 | 166 | 0.605837 | 5.314261 | false | false | false | false |
bvic23/VinceRP | VinceRPTests/Common/Util/TrySpec.swift | 1 | 1894 | //
// Created by Viktor Belenyesi on 20/04/15.
// Copyright (c) 2015 Viktor Belenyesi. All rights reserved.
//
@testable import VinceRP
import Quick
import Nimble
class TrySpec: QuickSpec {
override func spec() {
describe("basic") {
it("successful for non-error") {
// when
let result = Try(false)
// then
expect(result.isSuccess()) == true
}
it("is not failure for non-error") {
// when
let result = Try(false)
// then
expect(result.isFailure()) == false
}
it("is failure for error") {
// when
let result = Try<Bool>(fakeError)
// then
expect(result.isFailure()) == true
}
it("is not successful for error") {
// when
let result = Try<Bool>(fakeError)
// then
expect(result.isSuccess()) == false
}
}
describe("map") {
it("maps error to error") {
// given
let a = Try<Int>(fakeError)
// when
let result = a.map { $0 * 2 }
// then
expect(result.isFailure()) == true
expect(result.description) == fakeError.description
}
it("maps non-error correctly") {
// given
let a = Try(2)
// when
let result = a.map { $0 * 2 }
// then
expect(result.isSuccess()) == true
expect(result.description) == "4"
}
}
}
}
| mit | afdac11ad8040c39810cd691bd4fd156 | 22.382716 | 67 | 0.38754 | 5.335211 | false | false | false | false |
sdcoffey/Snax | Source/Snax/Extensions/Device.swift | 1 | 758 | //
// Device.swift
// Snax
//
// Created by Coffey, Steven on 9/18/15.
// Copyright © 2015 Coffey, Steven. All rights reserved.
//
import UIKit
extension UIDevice {
class func defaultSnaxTypeForDevice() -> SnaxType {
var type: SnaxType
switch UIDevice.currentDevice().userInterfaceIdiom {
case .Pad:
type = SnaxType.Partial
case .Phone:
type = SnaxType.Full
default:
type = SnaxType.Full
}
if UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeLeft ||
UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeRight {
type = SnaxType.Partial
}
return type
}
}
| gpl-2.0 | a284bb3305eb480d9f6f1cf61638c441 | 24.233333 | 88 | 0.59181 | 4.532934 | false | false | false | false |
LeeShiYoung/DouYu | DouYuAPP/DouYuAPP/Classes/Home/ViewModel/Yo_HomeCycleViewModel.swift | 1 | 1961 | //
// Yo_HomeCycleViewModel.swift
// DouYuAPP
//
// Created by shying li on 2017/4/1.
// Copyright © 2017年 李世洋. All rights reserved.
//
import UIKit
import FSPagerView
import Kingfisher
public let cycleViewCellID = "CycleViewcell"
class Yo_HomeCycleViewModel: NSObject {
var cycleView: Yo_HomeCycleView?
var dataSoureArray: [Yo_HomeCycleModel]?
init(CycleView cycleView: Yo_HomeCycleView) {
self.cycleView = cycleView
super.init()
cycleView.dataSource = self
cycleView.delegate = self
cycleView.isInfinite = true
}
public func setCycleDataSoure(_ datas: () -> [Yo_HomeCycleModel]?, completion:() -> ()) {
dataSoureArray = datas()
cycleView?.pageControl.numberOfPages = datas()?.count ?? 0
completion()
}
}
extension Yo_HomeCycleViewModel: FSPagerViewDataSource, FSPagerViewDelegate{
func numberOfItems(in pagerView: FSPagerView) -> Int {
return dataSoureArray?.count ?? 0
}
func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
let cell = pagerView.dequeueReusableCell(withReuseIdentifier: cycleViewCellID, at: index)
cell.imageView?.yo_setImage(URL(string: (dataSoureArray?[index].pic_url)!), placeholder: "Img_default", radius: 0)
cell.textLabel?.text = dataSoureArray?[index].title
cell.textLabel?.font = UIFont.systemFont(ofSize: 13)
cell.textLabel?.superview?.backgroundColor = UIColor.black.withAlphaComponent(0.4)
return cell
}
func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int) {
cycleView?.pageControl.currentPage = index
}
func pagerViewDidScroll(_ pagerView: FSPagerView) {
guard cycleView?.pageControl.currentPage != pagerView.currentIndex else {
return
}
cycleView?.pageControl.currentPage = pagerView.currentIndex
}
}
| apache-2.0 | 5803569c76ca58a2b6579e15d3f5786a | 31.533333 | 122 | 0.672643 | 4.714976 | false | false | false | false |
benlangmuir/swift | test/Index/property_wrappers.swift | 9 | 3816 | // RUN: %target-swift-ide-test -print-indexed-symbols -source-filename %s | %FileCheck -check-prefix=CHECK %s
@propertyWrapper
public struct Wrapper<T> {
// CHECK: [[@LINE-1]]:15 | struct/Swift | Wrapper | [[Wrapper_USR:.*]] | Def | rel: 0
public var wrappedValue: T
// CHECK: [[@LINE-1]]:14 | instance-property/Swift | wrappedValue | [[wrappedValue_USR:.*]] | Def,RelChild | rel: 1
public init(initialValue: T) {
// CHECK: [[@LINE-1]]:10 | constructor/Swift | init(initialValue:) | [[WrapperInit_USR:.*]] | Def,RelChild | rel: 1
self.wrappedValue = initialValue
}
public init(body: () -> T) {
// CHECK: [[@LINE-1]]:10 | constructor/Swift | init(body:) | [[WrapperBodyInit_USR:.*]] | Def,RelChild | rel: 1
self.wrappedValue = body()
}
public var projectedValue: Projection<T> {
get { Projection(item: wrappedValue) }
}
}
public struct Projection<T> {
var item: T
}
var globalInt: Int { return 17 }
// CHECK: [[@LINE-1]]:5 | variable/Swift | globalInt | [[globalInt_USR:.*]] | Def | rel: 0
public struct HasWrappers {
@Wrapper
// CHECK: [[@LINE-1]]:4 | struct/Swift | Wrapper | [[Wrapper_USR]] | Ref,RelCont | rel: 1
public var x: Int = globalInt
// CHECK-NOT: [[@LINE-1]]:23 | variable/Swift | globalInt
// CHECK: [[@LINE-4]]:4 | constructor/Swift | init(initialValue:) | [[WrapperInit_USR]] | Ref,Call,Impl,RelCont | rel: 1
// CHECK: [[@LINE-3]]:14 | instance-property/Swift | x | [[x_USR:.*]] | Def,RelChild | rel: 1
// CHECK: [[@LINE-4]]:23 | variable/Swift | globalInt | [[globalInt_USR]] | Ref,Read,RelCont | rel: 1
@Wrapper(body: { globalInt })
// CHECK: [[@LINE-1]]:4 | struct/Swift | Wrapper | [[Wrapper_USR]] | Ref,RelCont | rel: 1
// CHECK: [[@LINE-2]]:20 | variable/Swift | globalInt | [[globalInt_USR]] | Ref,Read,RelCont | rel: 1
// CHECK: [[@LINE-3]]:4 | constructor/Swift | init(body:) | [[WrapperBodyInit_USR]] | Ref,Call,RelCont | rel: 1
public var y: Int
// CHECK: [[@LINE-1]]:14 | instance-property/Swift | y | [[y_USR:.*]] | Def,RelChild | rel: 1
// CHECK-NOT: [[@LINE-6]]:20 | variable/Swift | globalInt
@Wrapper(body: {
// CHECK: [[@LINE-1]]:4 | struct/Swift | Wrapper | [[Wrapper_USR]] | Ref,RelCont | rel: 1
struct Inner {
@Wrapper
// CHECK: [[@LINE-1]]:8 | struct/Swift | Wrapper | [[Wrapper_USR]] | Ref,RelCont | rel: 1
// CHECK: [[@LINE-2]]:8 | constructor/Swift | init(initialValue:) | [[WrapperInit_USR]] | Ref,Call,Impl,RelCont | rel: 1
var x: Int = globalInt
// CHECK: [[@LINE-1]]:20 | variable/Swift | globalInt | [[globalInt_USR]] | Ref,Read,RelCont | rel: 1
}
return Inner().x + globalInt
// CHECK: [[@LINE-1]]:24 | variable/Swift | globalInt | [[globalInt_USR]] | Ref,Read,RelCont | rel: 1
})
// CHECK: [[@LINE-12]]:4 | constructor/Swift | init(body:) | [[WrapperBodyInit_USR]] | Ref,Call,RelCont | rel: 1
public var z: Int
// CHECK: [[@LINE-1]]:14 | instance-property/Swift | z | [[z_USR:.*]] | Def,RelChild | rel: 1
func backingUse() {
_ = _y.wrappedValue + _z.wrappedValue + x + _x.wrappedValue + $y.item
// CHECK: [[@LINE-1]]:10 | instance-property/Swift | y | [[y_USR]] | Ref,Read,RelCont | rel: 1
// CHECK: [[@LINE-2]]:12 | instance-property/Swift | wrappedValue | [[wrappedValue_USR:.*]] | Ref,Read,RelCont | rel: 1
// CHECK: [[@LINE-3]]:28 | instance-property/Swift | z | [[z_USR]] | Ref,Read,RelCont | rel: 1
// CHECK: [[@LINE-4]]:45 | instance-property/Swift | x | [[x_USR]] | Ref,Read,RelCont | rel: 1
// CHECK: [[@LINE-5]]:50 | instance-property/Swift | x | [[x_USR]] | Ref,Read,RelCont | rel: 1
// CHECK: [[@LINE-6]]:68 | instance-property/Swift | y | [[y_USR]] | Ref,Read,RelCont | rel: 1
}
}
func useMemberwiseInits(i: Int) {
_ = HasWrappers(x: i)
_ = HasWrappers(y: Wrapper(initialValue: i))
}
| apache-2.0 | 0ed3a92fa5fe844d7a7b7c4cced388b4 | 47.923077 | 126 | 0.605608 | 3.143328 | false | false | false | false |
crashoverride777/Swift2-iAds-AdMob-CustomAds-Helper | Example/SwiftyAdExample/GameScene.swift | 3 | 1996 | //
// GameScene.swift
// SwiftyAds
//
// Created by Dominik on 04/09/2015.
import SpriteKit
class GameScene: SKScene {
// MARK: - Properties
var coins = 0
private lazy var textLabel: SKLabelNode = self.childNode(withName: "textLabel") as! SKLabelNode
private lazy var consentLabel: SKLabelNode = self.childNode(withName: "consentLabel") as! SKLabelNode
private let swiftyAd: SwiftyAd = .shared
private var touchCounter = 15 {
didSet {
guard touchCounter > 0 else {
swiftyAd.isRemoved = true
textLabel.text = "Removed all ads"
return
}
textLabel.text = "Remove ads in \(touchCounter) clicks"
}
}
// MARK: - Life Cycle
override func didMove(to view: SKView) {
textLabel.text = "Remove ads in \(touchCounter) clicks"
consentLabel.isHidden = !swiftyAd.isRequiredToAskForConsent
}
// MARK: - Touches
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
let node = atPoint(location)
guard let viewController = view?.window?.rootViewController else { return }
if node == consentLabel {
let gameVC = view?.window?.rootViewController as! GameViewController
swiftyAd.askForConsent(from: viewController)
}
defer {
touchCounter -= 1
}
swiftyAd.showInterstitial(from: viewController, withInterval: 2)
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
}
}
| mit | 5f826fe2a7dfaa00c384f5260fd4bc1a | 27.514286 | 105 | 0.573647 | 5.07888 | false | false | false | false |
ngageoint/fog-machine | Demo/FogStringSearch/FogStringSearch/Models/Search/FogMachine/SearchWork.swift | 1 | 943 | import Foundation
import FogMachine
public class SearchWork: FMWork {
let peerCount: Int
let peerNumber: Int
let searchTerm: String
init (peerCount: Int, peerNumber: Int, searchTerm: String) {
self.peerCount = peerCount
self.peerNumber = peerNumber
self.searchTerm = searchTerm
super.init()
}
required public init(coder decoder: NSCoder) {
self.peerCount = decoder.decodeIntegerForKey("peerCount")
self.peerNumber = decoder.decodeIntegerForKey("peerNumber")
self.searchTerm = decoder.decodeObjectForKey("searchTerm") as! String
super.init(coder: decoder)
}
public override func encodeWithCoder(coder: NSCoder) {
super.encodeWithCoder(coder);
coder.encodeInteger(peerCount, forKey: "peerCount")
coder.encodeInteger(peerNumber, forKey: "peerNumber")
coder.encodeObject(searchTerm, forKey: "searchTerm")
}
}
| mit | e59f55ec7920a965c03f75a5cd6b64ea | 29.419355 | 77 | 0.683987 | 4.6 | false | false | false | false |
jtekenos/ios_schedule | ios_schedule/addEventViewController.swift | 1 | 2503 | //
// addEventViewController.swift
// ios_schedule
//
// Created by Denis Turitsa on 2015-11-29.
// Copyright © 2015 Jess. All rights reserved.
//
import UIKit
import Parse
class addEventViewController: UIViewController {
@IBOutlet weak var nameLabel: UITextField!
@IBOutlet weak var descriptionLabel: UITextView!
@IBOutlet weak var setLabel: UITextField!
@IBOutlet weak var repeatSwitch: UISwitch!
@IBOutlet weak var datePicker: UIDatePicker!
override func viewDidLoad() {
super.viewDidLoad()
nameLabel.text = ""
setLabel.text = ""
descriptionLabel.text = ""
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func addButton(sender: AnyObject) {
var name: String = nameLabel.text!
var eventDescription: String = descriptionLabel.text!
var eventSet: String = setLabel.text!.uppercaseString
var date: NSDate = datePicker.date
var repeatEvent: Bool = repeatSwitch.on
var dayformatter = NSDateFormatter()
dayformatter.dateFormat = "EEEE"
let dayOfweek: String = dayformatter.stringFromDate(date)
var scheduleEvent = PFObject(className:"Schedule")
scheduleEvent["date"] = date
scheduleEvent["eventName"] = name
scheduleEvent["classSet"] = eventSet
scheduleEvent["eventDescription"] = eventDescription
scheduleEvent["dayOfweek"] = dayOfweek
scheduleEvent["eventRepeat"] = repeatEvent
scheduleEvent["redFlag"] = false
let alert = UIAlertView()
alert.message = ""
alert.addButtonWithTitle("OK")
scheduleEvent.saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if (success) {
alert.title = "Event Added"
} else {
alert.title = "Error"
}
alert.show()
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | a6b838a98e0ed16482ba6df5b12573cf | 28.093023 | 106 | 0.617506 | 5.190871 | false | false | false | false |
mohojojo/iOS-swiftbond-viper | reactiveKitBond/UITableVewExtension.swift | 1 | 6608 | //
// 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 ReactiveKit
import Bond
import UIKit
public enum TableAnimation {
public enum ChangeType {
case Insert
case Delete
case Update
}
// Specifies the desired animation types for a change in a list of index
// paths.
public typealias IndexPathAnimationProvider = (ChangeType, [NSIndexPath]) -> [UITableViewRowAnimation: [NSIndexPath]]
// Implements IndexPathAnimationProvider, always returning
// UITableViewRowAnimation.Automatic for all index paths.
public static func alwaysAutomatic(_: ChangeType, ips: [NSIndexPath]) -> [UITableViewRowAnimation: [NSIndexPath]] {
return [.automatic: ips]
}
}
private func applyRowUnitChangeSet<C: CollectionChangesetType>(changeSet: C, tableView: UITableView, sectionIndex: Int, animationProvider: TableAnimation.IndexPathAnimationProvider) where C.Collection.Index == Int {
if changeSet.inserts.count > 0 {
let indexPaths = changeSet.inserts.map { NSIndexPath(forItem: $0, inSection: sectionIndex) }
for (animation, ips) in animationProvider(.Insert, indexPaths) {
tableView.insertrows.insertRows(at: ips, withRowAnimation: animation)
}
}
if changeSet.updates.count > 0 {
let indexPaths = changeSet.updates.map { NSIndexPath(forItem: $0, inSection: sectionIndex) }
for (animation, ips) in animationProvider(.Update, indexPaths) {
tableView.reloadRows(at: ips, withRowAnimation: animation)
}
}
if changeSet.deletes.count > 0 {
let indexPaths = changeSet.deletes.map { NSIndexPath(forItem: $0, inSection: sectionIndex) }
for (animation, ips) in animationProvider(.Delete, indexPaths) {
tableView.deleteRowsAtIndexPaths(ips, withRowAnimation: animation)
}
}
}
extension StreamType where Element: ArrayConvertible {
public func bindTo(tableView: UITableView, animated: Bool = true, createCell: (NSIndexPath, [Element.Element], UITableView) -> UITableViewCell) -> Disposable {
return map { CollectionChangeset.initial($0.toArray()) }.bindTo(tableView, animated: animated, createCell: createCell)
}
public func bindTo(tableView: UITableView, animationProvider: TableAnimation.IndexPathAnimationProvider, createCell: (NSIndexPath, [Element.Element], UITableView) -> UITableViewCell) -> Disposable {
return map { CollectionChangeset.initial($0.toArray()) }.bindTo(tableView, animationProvider: animationProvider, createCell: createCell)
}
}
extension StreamType where Element: CollectionChangesetType, Element.Collection.Index == Int, Event.Element == Element {
public func bindTo(tableView: UITableView, animationProvider: TableAnimation.IndexPathAnimationProvider?, createCell: (NSIndexPath, Element.Collection, UITableView) -> UITableViewCell) -> Disposable {
typealias Collection = Element.Collection
let dataSource = tableView.rDataSource
let numberOfItems = Property(0)
let collection = Property<Collection!>(nil)
dataSource.feed(
collection,
to: #selector(UITableViewDataSource.tableView(_:cellForRowAtIndexPath:)),
map: { (value: Collection!, tableView: UITableView, indexPath: NSIndexPath) -> UITableViewCell in
return createCell(indexPath, value, tableView)
})
dataSource.feed(property: numberOfItems, to: #selector(UITableViewDataSource.tableView(_:numberOfRowsInSection:)), map: { (value: Int, _: UITableView, _: Int) -> Int in value })
dataSource.feed(property: Property(1), to: #selector(UITableViewDataSource.numberOfSections(in:)), map: { (value: Int, _: UITableView) -> Int in value })
tableView.reloadData()
let serialDisposable = SerialDisposable(otherDisposable: nil)
serialDisposable.otherDisposable = observeNext { [weak tableView] event in
ImmediateOnMainExecutionContext {
guard let tableView = tableView else { serialDisposable.dispose(); return }
let justReload = collection.value == nil
collection.value = event.collection
numberOfItems.value = event.collection.count
if justReload || animationProvider == nil || event.inserts.count + event.deletes.count + event.updates.count == 0 {
tableView.reloadData()
} else {
tableView.beginUpdates()
applyRowUnitChangeSet(event, tableView: tableView, sectionIndex: 0, animationProvider: animationProvider!)
tableView.endUpdates()
}
}
}
return serialDisposable
}
public func bindTo(tableView: UITableView, animated: Bool = true, createCell: (NSIndexPath, Element.Collection, UITableView) -> UITableViewCell) -> Disposable {
return self.bindTo(tableView, animationProvider: TableAnimation.alwaysAutomatic, createCell: createCell)
}
}
extension UITableView {
public var rDelegate: ProtocolProxy {
return protocolProxy(for: UITableViewDelegate.self, setter: NSSelectorFromString("setDelegate:"))
}
public var rDataSource: ProtocolProxy {
return protocolProxy(for:UITableViewDataSource.self, setter: NSSelectorFromString("setDataSource:"))
}
}
| mit | 5e34078fbcbd8b56c669bcdaa0c243b8 | 46.2 | 215 | 0.690981 | 5.122481 | false | false | false | false |
SeongBrave/MikerNetCore | MikerNetCore/Classes/MikerNetCore.swift | 1 | 1704 | //
// MikerNetCore.swift
// MikerNetCore
//
// Created by eme on 2016/11/7.
// Copyright © 2016年 eme. All rights reserved.
//
import Foundation
/// 请求超时
let NETTIMEOUT = 500000
public class MikerNetCore {
/// 网络访问基础库
public static var baseUrl:[String] = ["http://www.baokan.name/e/api"]
/// 表示是否是debug模式,debug 打印返回数据
public static var isDebug:Bool = true
/// 返回数据 状态解析key
public static var statusKey:String = "status"
/// 用于返回数据解析的key
public static var dataKey:String = "data"
/// 表示返回成功的状态码
public static var successCode:Int = 0
}
/// 基础地址管理
public class UrlManager {
public static var sharedInstance : UrlManager {
struct Static {
static let instance : UrlManager = UrlManager()
}
return Static.instance
}
/// 重试次数
public var repeatNum:Int = 2
/// retry的次数 即轮训两遍数组中的地址
public var retryNum:Int{
get{
return self.repeatNum*self.urlArr.count
}
}
/// 地址数组
private var urlArr:[String] = MikerNetCore.baseUrl
/// 当前数组位置
private var index:Int = 0
/// 基础地址
public var baseUrl:String{
get{
if self.urlArr.count > 0 {
return self.urlArr[self.index%self.urlArr.count]
}else{
return ""
}
}
}
func getNext() {
if self.index < self.urlArr.count * self.repeatNum {
self.index = self.index + 1
}else{
self.index = 0
}
}
}
| mit | 95427a792a46f5cb3ee46483e96a0206 | 22.4 | 73 | 0.573964 | 3.673913 | false | false | false | false |
va3093/AfroLayout | AfroLayout/ViewController.swift | 1 | 4097 | //
// ViewController.swift
// AfroLayout
//
// Created by Wilhelm on 01/15/2016.
// Copyright (c) 2016 Wilhelm. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
lazy private(set) var tableView: UITableView = {
let tableView = UITableView.withAutoLayout()
tableView.delegate = self
tableView.dataSource = self
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
self.view.addSubview(self.tableView)
self.tableView.addCustomConstraints(inView: self.view, selfAttributes: [.Top, .Leading, .Trailing, .Bottom])
}
//MARK: UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
switch indexPath.row {
case 0:
self.navigationController?.pushViewController(VerticalStackingViewController(), animated: true)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
case 1:
self.navigationController?.pushViewController(SimpleAnimationViewController(), animated: true)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
case 2:
self.navigationController?.pushViewController(TopViewController(), animated: true)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
case 3:
self.navigationController?.pushViewController(TopLeftViewController(), animated: true)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
case 4:
self.navigationController?.pushViewController(TopRightViewController(), animated: true)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
case 5:
self.navigationController?.pushViewController(BottomViewController(), animated: true)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
case 6:
self.navigationController?.pushViewController(BottomLeftViewController(), animated: true)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
case 7:
self.navigationController?.pushViewController(BottomRightViewController(), animated: true)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
case 8:
self.navigationController?.pushViewController(AfterViewController(), animated: true)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
case 9:
self.navigationController?.pushViewController(BeforeViewController(), animated: true)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
case 10:
self.navigationController?.pushViewController(BelowViewController(), animated: true)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
case 11:
self.navigationController?.pushViewController(OnTopOfViewController(), animated: true)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
default:
break;
}
}
//MARK: UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 12
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCellWithIdentifier("Identifier") {
return cell
} else {
let cell = UITableViewCell()
switch indexPath.row {
case 0:
cell.textLabel?.text = "Vertical Stacking"
case 1:
cell.textLabel?.text = "Simple Animation"
case 2:
cell.textLabel?.text = "Constrain to Top of view"
case 3:
cell.textLabel?.text = "Constrain to Top Left of view"
case 4:
cell.textLabel?.text = "Constrain to Top Right of view"
case 5:
cell.textLabel?.text = "Constrain to Bottom of view"
case 6:
cell.textLabel?.text = "Constrain to Bottom Left of view"
case 7:
cell.textLabel?.text = "Constrain to Bottom Right of view"
case 8:
cell.textLabel?.text = "Constrain After a view"
case 9:
cell.textLabel?.text = "Constrain Before a view"
case 10:
cell.textLabel?.text = "Constrain Below a view"
case 11:
cell.textLabel?.text = "Constrain On top of a view"
default:
break;
}
return cell
}
}
}
| mit | 3f1d4c41619edb1b8199a45f7d8d1011 | 32.581967 | 110 | 0.753234 | 4.32173 | false | false | false | false |
kstaring/swift | benchmark/single-source/ByteSwap.swift | 10 | 1756 | //===--- ByteSwap.swift ---------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This test checks performance of Swift byte swap.
// rdar://problem/22151907
import Foundation
import TestsUtils
// a naive O(n) implementation of byteswap.
func byteswap_n(_ a: UInt64) -> UInt64 {
return ((a & 0x00000000000000FF) << 56) |
((a & 0x000000000000FF00) << 40) |
((a & 0x0000000000FF0000) << 24) |
((a & 0x00000000FF000000) << 8) |
((a & 0x000000FF00000000) >> 8) |
((a & 0x0000FF0000000000) >> 24) |
((a & 0x00FF000000000000) >> 40) |
((a & 0xFF00000000000000) >> 56)
}
// a O(logn) implementation of byteswap.
func byteswap_logn(_ a: UInt64) -> UInt64 {
var a = a
a = (a & 0x00000000FFFFFFFF) << 32 | (a & 0xFFFFFFFF00000000) >> 32
a = (a & 0x0000FFFF0000FFFF) << 16 | (a & 0xFFFF0000FFFF0000) >> 16
a = (a & 0x00FF00FF00FF00FF) << 8 | (a & 0xFF00FF00FF00FF00) >> 8
return a
}
@inline(never)
public func run_ByteSwap(_ N: Int) {
for _ in 1...100*N {
// Check some results.
CheckResults(byteswap_logn(byteswap_n(2457)) == 2457, "Incorrect results in ByteSwap.")
CheckResults(byteswap_logn(byteswap_n(9129)) == 9129, "Incorrect results in ByteSwap.")
CheckResults(byteswap_logn(byteswap_n(3333)) == 3333, "Incorrect results in ByteSwap.")
}
}
| apache-2.0 | 324cfbf7dd07e50863ae44808a603f3f | 35.583333 | 91 | 0.603075 | 3.491054 | false | false | false | false |
dnevera/ImageMetalling | ImageMetalling-16/ImageMetalling-16/Classes/Common/MLSControls.swift | 1 | 487 | //
// MLSControls.swift
// ImageMetalling-16
//
// Created by denis svinarchuk on 12.06.2018.
// Copyright © 2018 ImageMetalling. All rights reserved.
//
import Foundation
public struct MLSControls {
let p:[float2]
let q:[float2]
let kind:MLSSolverKind
let alpha:Float
public init(p: [float2], q: [float2], kind:MLSSolverKind = .affine, alpha:Float = 1.0){
self.p = p
self.q = q
self.kind = kind
self.alpha = alpha
}
}
| mit | e566822256901b38f822df2a422565f7 | 20.130435 | 91 | 0.615226 | 3.261745 | false | false | false | false |
demmys/treeswift | src/TypeInference/ExpressionASTTypeInference.swift | 1 | 5995 | import AST
extension TypeInference {
public func visit(node: Expression) throws {
addConstraint(node, node.body)
try node.body.accept(self)
}
public func visit(node: ExpressionBody) throws {
addConstraint(node, node.unit)
try node.unit.accept(self)
}
public func visit(node: BinaryExpressionBody) throws {
let arg = TupleType([TupleTypeElement(node.left), TupleTypeElement(node.right)])
let functionType = FunctionType(arg, .Nothing, node)
addConstraint(functionType, node.op)
try node.left.accept(self)
try node.right.accept(self)
}
public func visit(node: ConditionalExpressionBody) throws {
addConstraint(node.cond, try boolType())
addConstraint(node, node.trueSide)
addConstraint(node.trueSide, node.falseSide)
try node.cond.accept(self)
try node.trueSide.accept(self)
try node.falseSide.accept(self)
}
public func visit(node: TypeCastingExpressionBody) throws {
guard let castType = node.castType else {
assert(false, "<system error> TypeCastingExpressionBody.castType is nil")
exit(1)
}
switch castType {
case .Is:
addConstraint(node, try boolType())
case .As:
addConstraint(node.unit, node.dist)
addConstraint(node, node.dist)
case .ConditionalAs:
addConstraint(node, OptionalType(node.dist))
case .ForcedAs:
addConstraint(node, ImplicitlyUnwrappedOptionalType(node.dist))
}
try node.unit.accept(self)
}
private func typeOfTuple(tuple: Tuple) -> TupleType {
let xs = TupleType()
for (label, exp) in tuple {
xs.elems.append(TupleTypeElement(label, exp))
}
return xs
}
public func visit(node: PrefixedExpression) throws {
if case let .Operator(o) = node.pre {
let arg = TupleType([TupleTypeElement(node.core)])
let functionType = FunctionType(arg, .Nothing, node)
addConstraint(o, functionType)
}
// Do not analyze type of PostfixedExpression here.
// Because member reference has not resolved yet.
addConstraint(node, node.core)
try node.core.accept(self)
}
public func visit(node: PostfixedExpression) throws {
switch node.core {
case let .Core(core):
addConstraint(node, core)
try core.accept(self)
case let .Operator(wrapped, ref):
let arg = TupleType([TupleTypeElement(wrapped)])
let functionType = FunctionType(arg, .Nothing, node)
addConstraint(functionType, ref)
try wrapped.accept(self)
case let .FunctionCall(wrapped, tuple):
let arg = typeOfTuple(tuple)
// TODO throwable type
let functionType = FunctionType(arg, .Nothing, node)
addConstraint(wrapped, functionType)
try wrapped.accept(self)
for (_, e) in tuple {
try e.accept(self)
}
case .Member:
assert(false, "Member dispatch is not implemented")
case let .Subscript(wrapped, es):
let arg = TupleType()
for e in es {
arg.elems.append(TupleTypeElement(e))
}
let functionType = FunctionType(arg, .Nothing, node)
// TODO not wrapped, subscript of wrapped
addConstraint(wrapped, functionType)
case let .ForcedValue(wrapped):
// TODO treat OptionalType and ImplicitlyUnwrappedOptionaltype as same type
addConstraint(OptionalType(node), wrapped)
try wrapped.accept(self)
case .OptionalChaining:
assert(false, "Member dispatch is not implemented")
}
}
public func visit(node: ExpressionCore) throws {
switch node.value {
case let .Value(r, genArgs: _):
addConstraint(node, r)
case let .BindingConstant(i):
addConstraint(node, i)
case let .BindingVariable(i):
addConstraint(node, i)
case let .ImplicitParameter(r, genArgs: _):
addConstraint(node, r)
case .Integer:
node.type.fixType(try intType())
case .FloatingPoint:
node.type.fixType(try floatType())
case .StringExpression:
node.type.fixType(try stringType())
case .Boolean:
node.type.fixType(try boolType())
case .Nil:
addConstraint(node, OptionalType(UnresolvedType()))
case let .Array(es):
let elementType = UnresolvedType()
addConstraint(node, ArrayType(UnresolvedType()))
for e in es {
addConstraint(e, elementType)
try e.accept(self)
}
case let .Dictionary(eps):
let keyType = UnresolvedType()
let valueType = UnresolvedType()
addConstraint(node, DictionaryType(keyType, valueType))
for (e1, e2) in eps {
addConstraint(e1, keyType)
addConstraint(e2, valueType)
try e1.accept(self)
try e2.accept(self)
}
case .SelfExpression, .SelfInitializer, .SelfMember, .SelfSubscript:
assert(false, "'self' is not implemented")
case .SuperClassInitializer, .SuperClassMember, .SuperClassSubscript:
assert(false, "'super' is not implemented")
case .ClosureExpression:
assert(false, "Closure expression is not implemented")
case let .TupleExpression(t):
addConstraint(node, typeOfTuple(t))
for (_, e) in t {
try e.accept(self)
}
case .ImplicitMember:
assert(false, "Implicit member expression is not implemented")
default:
break
}
}
}
| bsd-2-clause | c4a27e0fd995b65316d25d0c3264bd36 | 36.006173 | 88 | 0.58749 | 4.654503 | false | false | false | false |
gegeburu3308119/ZCweb | ZCwebo/ZCwebo/Classes/Tools/CZRefreshControl/CZRefreshView.swift | 1 | 2160 | //
// CZRefreshView.swift
// 002-刷新控件
//
// Created by apple on 16/7/8.
// Copyright © 2016年 itcast. All rights reserved.
//
import UIKit
/// 刷新视图 - 负责刷新相关的 UI 显示和动画
class CZRefreshView: UIView {
/// 刷新状态
/**
iOS 系统中 UIView 封装的旋转动画
- 默认顺时针旋转
- 就近原则
- 要想实现同方向旋转,需要调整一个 非常小的数字(近)
- 如果想实现 360 旋转,需要核心动画 CABaseAnimation
*/
var refreshState: CZRefreshState = .Normal {
didSet {
switch refreshState {
case .Normal:
// 恢复状态
tipIcon?.isHidden = false
indicator?.stopAnimating()
tipLabel?.text = "继续使劲拉..."
UIView.animate(withDuration: 0.25) {
self.tipIcon?.transform = CGAffineTransform.identity
}
case .Pulling:
tipLabel?.text = "放手就刷新..."
UIView.animate(withDuration: 0.25) {
self.tipIcon?.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI + 0.001))
}
case .WillRefresh:
tipLabel?.text = "正在刷新中..."
// 隐藏提示图标
tipIcon?.isHidden = true
// 显示菊花
indicator?.startAnimating()
}
}
}
/// 父视图的高度 - 为了刷新控件不需要关心当前具体的刷新视图是谁!
var parentViewHeight: CGFloat = 0
/// 指示器
@IBOutlet weak var indicator: UIActivityIndicatorView?
/// 提示图标
@IBOutlet weak var tipIcon: UIImageView?
/// 提示标签
@IBOutlet weak var tipLabel: UILabel?
class func refreshView() -> CZRefreshView {
let nib = UINib(nibName: "CZMeituanRefreshView", bundle: nil)
return nib.instantiate(withOwner: nil, options: nil)[0] as! CZRefreshView
}
}
| apache-2.0 | 49867f457ab9a6f0b41f00139d6c9d19 | 25.884058 | 101 | 0.509434 | 4.35446 | false | false | false | false |
PokemonGoSucks/pgoapi-swift | PGoApi/Classes/PGoUtils.swift | 1 | 11431 | //
// PGoUtils.swift
// pgoapi
//
// Created by PokemonGoSucks on 2016-08-03.
//
//
import Foundation
import CoreLocation
import MapKit
import Alamofire
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
open class PGoLocationUtils {
public enum unit {
case kilometers, miles, meters, feet
}
public enum bearingUnits {
case degree, radian
}
public init () {}
public struct PGoCoordinate {
public var latitude: Double?
public var longitude: Double?
public var altitude: Double?
public var distance: Double?
public var displacement: Double?
public var address: [AnyHashable: Any]?
public var mapItem: MKMapItem?
}
public struct PGoDirections {
public var coordinates: Array<PGoLocationUtils.PGoCoordinate>
public var duration: Double
}
open func getAltitudeAndVerticalAccuracy(latitude: Double, longitude: Double, completionHandler: @escaping (_ altitude: Double?, _ horizontalAccuracy: Double?) -> ()) {
/*
Example func for completionHandler:
func receiveAltitudeAndHorizontalAccuracy(altitude: Double?, verticalAccuracy: Double?)
*/
Alamofire.request("https://maps.googleapis.com/maps/api/elevation/json?locations=\(latitude),\(longitude)&sensor=false").responseJSON { response in
var altitude:Double? = nil
var verticalAccuracy:Double? = nil
if let JSON = response.result.value {
let dict = JSON as! [String:AnyObject]
if let result = dict["results"] as? [[String:AnyObject]] {
if result.count > 0 {
if let alt = result[0]["elevation"] as? Double {
altitude = alt
}
if let horAcc = result[0]["resolution"] as? Double {
verticalAccuracy = horAcc
}
}
}
completionHandler(altitude, verticalAccuracy)
} else {
completionHandler(nil, nil)
}
}
}
open func reverseGeocode(latitude: Double, longitude: Double, completionHandler: @escaping (PGoLocationUtils.PGoCoordinate?) -> ()) {
/*
Example func for completionHandler:
func receivedReverseGeocode(results:PGoLocationUtils.PGoCoordinate?)
*/
let location = CLLocation(latitude: latitude, longitude: longitude)
CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placeData, error) -> Void in
if placeData?.count > 0 {
let addressDictionary = placeData![0]
let address = addressDictionary.addressDictionary!
let result = PGoCoordinate(
latitude: latitude,
longitude: longitude,
altitude: nil,
distance: nil,
displacement: nil,
address: address,
mapItem: MKMapItem(
placemark: MKPlacemark(
coordinate: placeData![0].location!.coordinate,
addressDictionary: placeData![0].addressDictionary as! [String:AnyObject]?
)
)
)
completionHandler(result)
} else {
completionHandler(nil)
}
})
}
open func geocode(location: String, completionHandler: @escaping (PGoLocationUtils.PGoCoordinate?) -> ()) {
/*
Example func for completionHandler:
func receivedGeocode(results:PGoLocationUtils.PGoCoordinate?)
*/
var result: PGoCoordinate?
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(location, completionHandler: {(placeData: [CLPlacemark]?, error: NSError?) -> Void in
if (placeData?.count > 0) {
let addressDictionary = placeData![0]
result = PGoCoordinate(
latitude: (placeData![0].location?.coordinate.latitude)!,
longitude: (placeData![0].location?.coordinate.longitude)!,
altitude: placeData![0].location?.altitude,
distance: nil,
displacement: nil,
address: addressDictionary.addressDictionary!,
mapItem: MKMapItem(
placemark: MKPlacemark(
coordinate: placeData![0].location!.coordinate,
addressDictionary: placeData![0].addressDictionary as! [String:AnyObject]?
)
)
)
completionHandler(result)
} else {
completionHandler(nil)
}
} as! CLGeocodeCompletionHandler)
}
open func getDistanceBetweenPoints(startLatitude:Double, startLongitude:Double, endLatitude:Double, endLongitude: Double, unit: PGoLocationUtils.unit? = .meters) -> Double {
let start = CLLocation.init(latitude: startLatitude, longitude: startLongitude)
let end = CLLocation.init(latitude: endLatitude, longitude: endLongitude)
var distance = start.distance(from: end)
if unit == .miles {
distance = distance/1609.344
} else if unit == .kilometers {
distance = distance/1000
} else if unit == .feet {
distance = distance * 3.28084
}
return distance
}
open func moveDistanceToPoint(startLatitude:Double, startLongitude:Double, endLatitude:Double, endLongitude: Double, distance: Double, unitOfDistance: PGoLocationUtils.unit? = .meters) -> PGoLocationUtils.PGoCoordinate {
let maxDistance = getDistanceBetweenPoints(startLatitude: startLatitude, startLongitude: startLongitude, endLatitude: endLatitude, endLongitude: endLongitude)
var distanceConverted = distance
if unitOfDistance == .miles {
distanceConverted = distance * 1609.344
} else if unitOfDistance == .kilometers {
distanceConverted = distance * 1000
} else if unitOfDistance == .feet {
distanceConverted = distance / 3.28084
}
var distanceMove = distanceConverted/maxDistance
if distanceMove > 1 {
distanceMove = 1
}
return PGoCoordinate(
latitude: startLatitude + ((endLatitude - startLatitude) * distanceMove),
longitude: startLongitude + ((endLongitude - startLongitude) * distanceMove),
altitude: nil,
distance: maxDistance,
displacement: distanceMove * maxDistance,
address: nil,
mapItem: nil
)
}
open func moveDistanceWithBearing(startLatitude:Double, startLongitude:Double, bearing: Double, distance: Double, bearingUnits: PGoLocationUtils.bearingUnits? = .radian, unitOfDistance: PGoLocationUtils.unit? = .meters) -> PGoLocationUtils.PGoCoordinate {
var distanceConverted = distance
if unitOfDistance == .miles {
distanceConverted = distance * 1609.344
} else if unitOfDistance == .kilometers {
distanceConverted = distance * 1000
} else if unitOfDistance == .feet {
distanceConverted = distance / 3.28084
}
var bearingConverted = bearing
if bearingUnits == .degree {
bearingConverted = bearing * M_PI / 180.0
}
let distanceRadian = distanceConverted / (6372797.6)
let lat = startLatitude * M_PI / 180
let long = startLongitude * M_PI / 180
let latitude = (asin(sin(lat) * cos(distanceRadian) + cos(lat) * sin(distanceRadian) * cos(bearingConverted))) * 180 / M_PI
let longitude = (long + atan2(sin(bearingConverted) * sin(distanceRadian) * cos(lat), cos(distanceRadian) - sin(lat) * sin(latitude))) * 180 / M_PI
return PGoCoordinate(
latitude: latitude,
longitude: longitude,
altitude: nil,
distance: nil,
displacement: nil,
address: nil,
mapItem: nil
)
}
fileprivate func getMKMapItem(lat: Double, long: Double) -> MKMapItem {
let sourceLoc2D = CLLocationCoordinate2DMake(lat, long)
let sourcePlacemark = MKPlacemark(coordinate: sourceLoc2D, addressDictionary: nil)
let source = MKMapItem(placemark: sourcePlacemark)
return source
}
open func getDirectionsFromToLocations(startLatitude:Double, startLongitude:Double, endLatitude:Double, endLongitude: Double, transportType: MKDirectionsTransportType? = .walking, completionHandler: @escaping (PGoLocationUtils.PGoDirections?) -> ()) {
/*
Example func for completionHandler:
func receivedDirections(result: PGoLocationUtils.PGoDirections?)
*/
var result:Array<PGoCoordinate> = []
let request: MKDirectionsRequest = MKDirectionsRequest()
let start = getMKMapItem(lat: startLatitude, long: startLongitude)
let end = getMKMapItem(lat: endLatitude, long: endLongitude)
request.source = start
request.destination = end
request.requestsAlternateRoutes = true
request.transportType = transportType!
let directions = MKDirections(request: request)
directions.calculate (completionHandler: {
(response: MKDirectionsResponse?, error: NSError?) in
if let routeResponse = response?.routes {
let fastestRoute: MKRoute =
routeResponse.sorted(by: {$0.expectedTravelTime <
$1.expectedTravelTime})[0]
for step in fastestRoute.steps {
result.append(
PGoCoordinate(
latitude: step.polyline.coordinate.latitude,
longitude: step.polyline.coordinate.longitude,
altitude: nil,
distance: step.distance,
displacement: nil,
address: nil,
mapItem: nil
)
)
}
completionHandler(
PGoLocationUtils.PGoDirections(
coordinates: result,
duration: fastestRoute.expectedTravelTime
)
)
} else {
completionHandler(nil)
}
} as! MKDirectionsHandler)
}
}
| mit | 9ae195518527454c7b5c00790fef9460 | 37.35906 | 259 | 0.556907 | 5.376764 | false | false | false | false |
atrick/swift | test/AutoDiff/validation-test/inout_parameters.swift | 5 | 7181 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
// Would fail due to unavailability of swift_autoDiffCreateLinearMapContext.
// `inout` parameter differentiation tests.
import DifferentiationUnittest
import StdlibUnittest
var InoutParameterAutoDiffTests = TestSuite("InoutParameterDifferentiation")
// TODO(TF-1173): Move floating-point mutating operation tests to
// `test/AutoDiff/stdlib/floating_point.swift.gyb` when forward-mode
// differentiation supports `inout` parameter differentiation.
InoutParameterAutoDiffTests.test("Float.+=") {
func mutatingAddWrapper(_ x: Float, _ y: Float) -> Float {
var result: Float = x
result += y
return result
}
expectEqual((1, 1), gradient(at: 4, 5, of: mutatingAddWrapper))
expectEqual((10, 10), pullback(at: 4, 5, of: mutatingAddWrapper)(10))
}
InoutParameterAutoDiffTests.test("Float.-=") {
func mutatingSubtractWrapper(_ x: Float, _ y: Float) -> Float {
var result: Float = x
result += y
return result
}
expectEqual((1, 1), gradient(at: 4, 5, of: mutatingSubtractWrapper))
expectEqual((10, 10), pullback(at: 4, 5, of: mutatingSubtractWrapper)(10))
}
InoutParameterAutoDiffTests.test("Float.*=") {
func mutatingMultiplyWrapper(_ x: Float, _ y: Float) -> Float {
var result: Float = x
result += y
return result
}
expectEqual((1, 1), gradient(at: 4, 5, of: mutatingMultiplyWrapper))
expectEqual((10, 10), pullback(at: 4, 5, of: mutatingMultiplyWrapper)(10))
}
InoutParameterAutoDiffTests.test("Float./=") {
func mutatingDivideWrapper(_ x: Float, _ y: Float) -> Float {
var result: Float = x
result += y
return result
}
expectEqual((1, 1), gradient(at: 4, 5, of: mutatingDivideWrapper))
expectEqual((10, 10), pullback(at: 4, 5, of: mutatingDivideWrapper)(10))
}
// Simplest possible `inout` parameter differentiation.
InoutParameterAutoDiffTests.test("InoutIdentity") {
// Semantically, an empty function with an `inout` parameter is an identity
// function.
func inoutIdentity(_ x: inout Float) {}
func identity(_ x: Float) -> Float {
var result = x
inoutIdentity(&result)
return result
}
expectEqual(1, gradient(at: 10, of: identity))
expectEqual(10, pullback(at: 10, of: identity)(10))
}
extension Float {
// Custom version of `Float.*=`, implemented using `Float.*` and mutation.
// Verify that its generated derivative has the same behavior as the
// registered derivative for `Float.*=`.
@differentiable(reverse)
static func multiplyAssign(_ lhs: inout Float, _ rhs: Float) {
lhs = lhs * rhs
}
}
InoutParameterAutoDiffTests.test("ControlFlow") {
func sum(_ array: [Float]) -> Float {
var result: Float = 0
for i in withoutDerivative(at: array.indices) {
result += array[i]
}
return result
}
expectEqual([1, 1, 1], gradient(at: [1, 2, 3], of: sum))
func product(_ array: [Float]) -> Float {
var result: Float = 1
for i in withoutDerivative(at: array.indices) {
result *= array[i]
}
return result
}
expectEqual([20, 15, 12], gradient(at: [3, 4, 5], of: product))
func productCustom(_ array: [Float]) -> Float {
var result: Float = 1
for i in withoutDerivative(at: array.indices) {
Float.multiplyAssign(&result, array[i])
}
return result
}
expectEqual([20, 15, 12], gradient(at: [3, 4, 5], of: productCustom))
}
InoutParameterAutoDiffTests.test("SetAccessor") {
struct S: Differentiable {
var x: Float
var computed: Float {
get { x }
set { x = newValue }
}
// Computed property with explicit `@differentiable` accessors.
var doubled: Float {
@differentiable(reverse)
get { x + x }
@differentiable(reverse)
set { x = newValue / 2 }
}
}
// `squared` implemented using a `set` accessor.
func squared(_ x: Float) -> Float {
var s = S(x: 1)
s.x *= x
s.computed *= x
return s.x
}
expectEqual((9, 6), valueWithGradient(at: 3, of: squared))
expectEqual((16, 8), valueWithGradient(at: 4, of: squared))
// `quadrupled` implemented using a `set` accessor.
func quadrupled(_ x: Float) -> Float {
var s = S(x: 1)
s.doubled *= 4 * x
return s.x
}
print(valueWithGradient(at: 3, of: quadrupled))
print(valueWithGradient(at: 4, of: quadrupled))
expectEqual((12, 4), valueWithGradient(at: 3, of: quadrupled))
expectEqual((16, 4), valueWithGradient(at: 4, of: quadrupled))
}
// Test differentiation wrt `inout` parameters that have a class type.
InoutParameterAutoDiffTests.test("InoutClassParameter") {
class Class: Differentiable {
@differentiable(reverse)
var x: Float
init(_ x: Float) {
self.x = x
}
}
do {
func squaredViaMutation(_ c: inout Class) {
c = Class(c.x * c.x)
}
func squared(_ x: Float) -> Float {
var c = Class(x)
squaredViaMutation(&c)
return c.x
}
expectEqual((100, 20), valueWithGradient(at: 10, of: squared))
expectEqual(200, pullback(at: 10, of: squared)(10))
}
do {
func squaredViaModifyAccessor(_ c: inout Class) {
// The line below calls `Class.x.modify`.
c.x *= c.x
}
func squared(_ x: Float) -> Float {
var c = Class(x)
squaredViaModifyAccessor(&c)
return c.x
}
// FIXME(TF-1080): Fix incorrect class property `modify` accessor derivative values.
// expectEqual((100, 20), valueWithGradient(at: 10, of: squared))
// expectEqual(200, pullback(at: 10, of: squared)(10))
expectEqual((100, 1), valueWithGradient(at: 10, of: squared))
expectEqual(10, pullback(at: 10, of: squared)(10))
}
}
// SR-13305: Test function with non-wrt `inout` parameter, which should be
// treated as a differentiability result.
protocol SR_13305_Protocol {
@differentiable(reverse, wrt: x)
func method(_ x: Float, _ y: inout Float)
@differentiable(reverse, wrt: x)
func genericMethod<T: Differentiable>(_ x: T, _ y: inout T)
}
InoutParameterAutoDiffTests.test("non-wrt inout parameter") {
struct SR_13305_Struct: SR_13305_Protocol {
@differentiable(reverse, wrt: x)
func method(_ x: Float, _ y: inout Float) {
y = y * x
}
@differentiable(reverse, wrt: x)
func genericMethod<T: Differentiable>(_ x: T, _ y: inout T) {
y = x
}
}
@differentiable(reverse, wrt: x)
func foo(_ s: SR_13305_Struct, _ x: Float, _ y: Float) -> Float {
var y = y
s.method(x, &y)
return y
}
@differentiable(reverse, wrt: x)
func fooGeneric<T: SR_13305_Protocol>(_ s: T, _ x: Float, _ y: Float) -> Float {
var y = y
s.method(x, &y)
return x
}
let s = SR_13305_Struct()
do {
let (value, (dx, dy)) = valueWithGradient(at: 2, 3, of: { foo(s, $0, $1) })
expectEqual(6, value)
expectEqual((3, 2), (dx, dy))
}
expectEqual((value: 6, gradient: 3), valueWithGradient(at: 2, of: { foo(s, $0, 3) }))
do {
let (value, (dx, dy)) = valueWithGradient(at: 2, 3, of: { fooGeneric(s, $0, $1) })
expectEqual(2, value)
expectEqual((1, 0), (dx, dy))
}
expectEqual((value: 2, gradient: 1), valueWithGradient(at: 2, of: { fooGeneric(s, $0, 3) }))
}
runAllTests()
| apache-2.0 | 49b2e9b010e7f155709fa96ab96d2499 | 27.839357 | 94 | 0.640997 | 3.460723 | false | true | false | false |
auth0/Auth0.swift | Auth0Tests/WebAuthSpec.swift | 1 | 24825 | import Quick
import Nimble
import SafariServices
@testable import Auth0
private let ClientId = "ClientId"
private let Domain = "samples.auth0.com"
private let DomainURL = URL.httpsURL(from: Domain)
private let RedirectURL = URL(string: "https://samples.auth0.com/callback")!
private let State = "state"
extension URL {
var a0_components: URLComponents? {
return URLComponents(url: self, resolvingAgainstBaseURL: true)
}
}
private let ValidAuthorizeURLExample = "valid authorize url"
class WebAuthSharedExamplesConfiguration: QuickConfiguration {
override class func configure(_ configuration: QCKConfiguration) {
sharedExamples(ValidAuthorizeURLExample) { (context: SharedExampleContext) in
let attrs = context()
let url = attrs["url"] as! URL
let params = attrs["query"] as! [String: String]
let domain = attrs["domain"] as! String
let components = url.a0_components
it("should use domain \(domain)") {
expect(components?.scheme) == "https"
expect(components?.host) == String(domain.split(separator: "/").first!)
expect(components?.path).to(endWith("/authorize"))
}
it("should have state parameter") {
expect(components?.queryItems).to(containItem(withName:"state"))
}
params.forEach { key, value in
it("should have query parameter \(key)") {
expect(components?.queryItems).to(containItem(withName: key, value: value))
}
}
}
}
}
private func newWebAuth() -> Auth0WebAuth {
return Auth0WebAuth(clientId: ClientId, url: DomainURL)
}
private func defaultQuery(withParameters parameters: [String: String] = [:]) -> [String: String] {
var query = [
"client_id": ClientId,
"response_type": "code",
"redirect_uri": RedirectURL.absoluteString,
"scope": defaultScope,
]
parameters.forEach { query[$0] = $1 }
return query
}
private let defaults = ["response_type": "code"]
class WebAuthSpec: QuickSpec {
override func spec() {
describe("init") {
it("should init with client id & url") {
let webAuth = Auth0WebAuth(clientId: ClientId, url: DomainURL)
expect(webAuth.clientId) == ClientId
expect(webAuth.url) == DomainURL
}
it("should init with client id, url & session") {
let session = URLSession(configuration: URLSession.shared.configuration)
let webAuth = Auth0WebAuth(clientId: ClientId, url: DomainURL, session: session)
expect(webAuth.session).to(be(session))
}
it("should init with client id, url & storage") {
let storage = TransactionStore()
let webAuth = Auth0WebAuth(clientId: ClientId, url: DomainURL, storage: storage)
expect(webAuth.storage).to(be(storage))
}
it("should init with client id, url & telemetry") {
let telemetryInfo = "info"
var telemetry = Telemetry()
telemetry.info = telemetryInfo
let webAuth = Auth0WebAuth(clientId: ClientId, url: DomainURL, telemetry: telemetry)
expect(webAuth.telemetry.info) == telemetryInfo
}
}
describe("authorize URL") {
itBehavesLike(ValidAuthorizeURLExample) {
return [
"url": newWebAuth()
.buildAuthorizeURL(withRedirectURL: RedirectURL, defaults: defaults, state: State, organization: nil, invitation: nil),
"domain": Domain,
"query": defaultQuery(),
]
}
itBehavesLike(ValidAuthorizeURLExample) {
return [
"url": newWebAuth()
.buildAuthorizeURL(withRedirectURL: RedirectURL, defaults: defaults, state: State, organization: nil, invitation: nil),
"domain": "\(Domain)/foo",
"query": defaultQuery()
]
}
itBehavesLike(ValidAuthorizeURLExample) {
return [
"url": newWebAuth()
.buildAuthorizeURL(withRedirectURL: RedirectURL, defaults: defaults, state: State, organization: nil, invitation: nil),
"domain": "\(Domain)/foo/",
"query": defaultQuery()
]
}
itBehavesLike(ValidAuthorizeURLExample) {
return [
"url": newWebAuth()
.buildAuthorizeURL(withRedirectURL: RedirectURL, defaults: defaults, state: State, organization: nil, invitation: nil),
"domain": "\(Domain)/foo/bar",
"query": defaultQuery()
]
}
itBehavesLike(ValidAuthorizeURLExample) {
return [
"url": newWebAuth()
.buildAuthorizeURL(withRedirectURL: RedirectURL, defaults: defaults, state: State, organization: nil, invitation: nil),
"domain": "\(Domain)/foo/bar/",
"query": defaultQuery()
]
}
itBehavesLike(ValidAuthorizeURLExample) {
return [
"url": newWebAuth()
.connection("facebook")
.buildAuthorizeURL(withRedirectURL: RedirectURL, defaults: defaults, state: State, organization: nil, invitation: nil),
"domain": Domain,
"query": defaultQuery(withParameters: ["connection": "facebook"]),
]
}
itBehavesLike(ValidAuthorizeURLExample) {
let state = UUID().uuidString
return [
"url": newWebAuth()
.state(state)
.buildAuthorizeURL(withRedirectURL: RedirectURL, defaults: defaults, state: State, organization: nil, invitation: nil),
"domain": Domain,
"query": defaultQuery(withParameters: ["state": state]),
]
}
itBehavesLike(ValidAuthorizeURLExample) {
let scope = "openid email phone"
return [
"url": newWebAuth()
.scope(scope)
.buildAuthorizeURL(withRedirectURL: RedirectURL, defaults: defaults, state: State, organization: nil, invitation: nil),
"domain": Domain,
"query": defaultQuery(withParameters: ["scope": scope]),
]
}
itBehavesLike(ValidAuthorizeURLExample) {
let scope = "email phone"
return [
"url": newWebAuth()
.scope(scope)
.buildAuthorizeURL(withRedirectURL: RedirectURL, defaults: defaults, state: State, organization: nil, invitation: nil),
"domain": Domain,
"query": defaultQuery(withParameters: ["scope": "openid \(scope)"]),
]
}
itBehavesLike(ValidAuthorizeURLExample) {
return [
"url": newWebAuth()
.maxAge(10000) // 1 second
.buildAuthorizeURL(withRedirectURL: RedirectURL, defaults: defaults, state: State, organization: nil, invitation: nil),
"domain": Domain,
"query": defaultQuery(withParameters: ["max_age": "10000"]),
]
}
itBehavesLike(ValidAuthorizeURLExample) {
return [
"url": newWebAuth()
.buildAuthorizeURL(withRedirectURL: RedirectURL, defaults: defaults, state: State, organization: "abc1234", invitation: nil),
"domain": Domain,
"query": defaultQuery(withParameters: ["organization": "abc1234"]),
]
}
itBehavesLike(ValidAuthorizeURLExample) {
return [
"url": newWebAuth()
.buildAuthorizeURL(withRedirectURL: RedirectURL, defaults: defaults, state: State, organization: "abc1234", invitation: "xyz6789"),
"domain": Domain,
"query": defaultQuery(withParameters: ["organization": "abc1234", "invitation": "xyz6789"]),
]
}
itBehavesLike(ValidAuthorizeURLExample) {
var newDefaults = defaults
newDefaults["audience"] = "https://wwww.google.com"
return [
"url": newWebAuth()
.buildAuthorizeURL(withRedirectURL: RedirectURL, defaults: newDefaults, state: State, organization: nil, invitation: nil),
"domain": Domain,
"query": defaultQuery(withParameters: ["audience": "https://wwww.google.com"]),
]
}
itBehavesLike(ValidAuthorizeURLExample) {
var newDefaults = defaults
newDefaults["audience"] = "https://wwww.google.com"
return [
"url": newWebAuth()
.audience("https://domain.auth0.com")
.buildAuthorizeURL(withRedirectURL: RedirectURL, defaults: newDefaults, state: State, organization: nil, invitation: nil),
"domain": Domain,
"query": defaultQuery(withParameters: ["audience": "https://domain.auth0.com"]),
]
}
itBehavesLike(ValidAuthorizeURLExample) {
return [
"url": newWebAuth()
.audience("https://domain.auth0.com")
.buildAuthorizeURL(withRedirectURL: RedirectURL, defaults: defaults, state: State, organization: nil, invitation: nil),
"domain": Domain,
"query": defaultQuery(withParameters: ["audience": "https://domain.auth0.com"]),
]
}
itBehavesLike(ValidAuthorizeURLExample) {
return [
"url": newWebAuth()
.connectionScope("user_friends,email")
.buildAuthorizeURL(withRedirectURL: RedirectURL, defaults: defaults, state: State, organization: nil, invitation: nil),
"domain": Domain,
"query": defaultQuery(withParameters: ["connection_scope": "user_friends,email"]),
]
}
itBehavesLike(ValidAuthorizeURLExample) {
var newDefaults = defaults
newDefaults["connection_scope"] = "email"
return [
"url": newWebAuth()
.connectionScope("user_friends")
.buildAuthorizeURL(withRedirectURL: RedirectURL, defaults: newDefaults, state: State, organization: nil, invitation: nil),
"domain": Domain,
"query": defaultQuery(withParameters: ["connection_scope": "user_friends"]),
]
}
itBehavesLike(ValidAuthorizeURLExample) {
let organization = "foo"
let invitation = "bar"
let url = URL(string: "https://example.com?organization=\(organization)&invitation=\(invitation)")!
return [
"url": newWebAuth()
.invitationURL(url)
.buildAuthorizeURL(withRedirectURL: RedirectURL, defaults: defaults, state: State, organization: organization, invitation: invitation),
"domain": Domain,
"query": defaultQuery(withParameters: ["organization": organization, "invitation": invitation]),
]
}
context("encoding") {
it("should encode + as %2B"){
let url = newWebAuth()
.parameters(["login_hint": "[email protected]"])
.buildAuthorizeURL(withRedirectURL: RedirectURL, defaults: defaults, state: State, organization: nil, invitation: nil)
expect(url.absoluteString.contains("first%[email protected]")).to(beTrue())
}
}
}
describe("redirect uri") {
#if os(iOS)
let platform = "ios"
#else
let platform = "macos"
#endif
context("custom scheme") {
let bundleId = Bundle.main.bundleIdentifier!
it("should build with the domain") {
expect(newWebAuth().redirectURL?.absoluteString) == "\(bundleId)://\(Domain)/\(platform)/\(bundleId)/callback"
}
it("should build with the domain and a subpath") {
let subpath = "foo"
let uri = "\(bundleId)://\(Domain)/\(subpath)/\(platform)/\(bundleId)/callback"
let webAuth = Auth0WebAuth(clientId: ClientId, url: DomainURL.appendingPathComponent(subpath))
expect(webAuth.redirectURL?.absoluteString) == uri
}
it("should build with the domain and subpaths") {
let subpaths = "foo/bar"
let uri = "\(bundleId)://\(Domain)/\(subpaths)/\(platform)/\(bundleId)/callback"
let webAuth = Auth0WebAuth(clientId: ClientId, url: DomainURL.appendingPathComponent(subpaths))
expect(webAuth.redirectURL?.absoluteString) == uri
}
}
it("should build with a custom url") {
expect(newWebAuth().redirectURL(RedirectURL).redirectURL) == RedirectURL
}
}
describe("other builder methods") {
context("ephemeral session") {
it("should not use ephemeral session by default") {
expect(newWebAuth().ephemeralSession).to(beFalse())
}
it("should use ephemeral session") {
expect(newWebAuth().useEphemeralSession().ephemeralSession).to(beTrue())
}
}
context("nonce") {
it("should use a custom nonce value") {
let nonce = "foo"
expect(newWebAuth().nonce(nonce).nonce).to(equal(nonce))
}
}
context("leeway") {
it("should use the default leeway value") {
expect(newWebAuth().leeway).to(equal(60000)) // 60 seconds
}
it("should use a custom leeway value") {
expect(newWebAuth().leeway(30000).leeway).to(equal(30000)) // 30 seconds
}
}
context("issuer") {
it("should use the default issuer value") {
expect(newWebAuth().issuer).to(equal(DomainURL.absoluteString))
}
it("should use a custom issuer value") {
expect(newWebAuth().issuer("https://example.com/").issuer).to(equal("https://example.com/"))
}
}
context("organization") {
it("should use no organization value by default") {
expect(newWebAuth().organization).to(beNil())
}
it("should use an organization value") {
expect(newWebAuth().organization("abc1234").organization).to(equal("abc1234"))
}
}
context("organization invitation") {
it("should use no organization invitation URL by default") {
expect(newWebAuth().invitationURL).to(beNil())
}
it("should use an organization invitation URL") {
let invitationUrl = URL(string: "https://example.com/")!
expect(newWebAuth().invitationURL(invitationUrl).invitationURL?.absoluteString).to(equal("https://example.com/"))
}
}
context("provider") {
it("should use no custom provider by default") {
expect(newWebAuth().provider).to(beNil())
}
it("should use a custom provider") {
expect(newWebAuth().provider(WebAuthentication.asProvider(urlScheme: "")).provider).toNot(beNil())
}
}
}
#if os(iOS)
describe("login") {
var auth: Auth0WebAuth!
beforeEach {
auth = newWebAuth()
}
it("should start the supplied provider") {
var isStarted = false
_ = auth.provider({ url, _ in
isStarted = true
return SpyUserAgent()
})
auth.start { _ in }
expect(isStarted).toEventually(beTrue())
}
it("should generate a state") {
auth.start { _ in }
expect(auth.state).toNot(beNil())
}
it("should generate different state on every start") {
auth.start { _ in }
let state = auth.state
auth.start { _ in }
expect(auth.state) != state
}
it("should use the supplied state") {
let state = UUID().uuidString
auth.state(state).start { _ in }
expect(auth.state) == state
}
it("should use the state supplied via parameters") {
let state = UUID().uuidString
auth.parameters(["state": state]).start { _ in }
expect(auth.state) == state
}
it("should use the organization and invitation from the invitation URL") {
let url = "https://\(Domain)?organization=foo&invitation=bar"
var redirectURL: URL?
_ = auth.invitationURL(URL(string: url)!).provider({ url, _ in
redirectURL = url
return SpyUserAgent()
})
auth.start { _ in }
expect(redirectURL?.query).toEventually(contain("organization=foo"))
expect(redirectURL?.query).toEventually(contain("invitation=bar"))
}
it("should produce an invalid invitation URL error when the organization is missing") {
let url = "https://\(Domain)?invitation=foo"
let expectedError = WebAuthError(code: .invalidInvitationURL(url))
var result: WebAuthResult<Credentials>?
_ = auth.invitationURL(URL(string: url)!)
auth.start { result = $0 }
expect(result).toEventually(haveWebAuthError(expectedError))
}
it("should produce an invalid invitation URL error when the invitation is missing") {
let url = "https://\(Domain)?organization=foo"
let expectedError = WebAuthError(code: .invalidInvitationURL(url))
var result: WebAuthResult<Credentials>?
_ = auth.invitationURL(URL(string: url)!)
auth.start { result = $0 }
expect(result).toEventually(haveWebAuthError(expectedError))
}
it("should produce an invalid invitation URL error when the organization and invitation are missing") {
let url = "https://\(Domain)?foo=bar"
let expectedError = WebAuthError(code: .invalidInvitationURL(url))
var result: WebAuthResult<Credentials>?
_ = auth.invitationURL(URL(string: url)!)
auth.start { result = $0 }
expect(result).toEventually(haveWebAuthError(expectedError))
}
it("should produce an invalid invitation URL error when the query parameters are missing") {
let expectedError = WebAuthError(code: .invalidInvitationURL(DomainURL.absoluteString))
var result: WebAuthResult<Credentials>?
_ = auth.invitationURL(DomainURL)
auth.start { result = $0 }
expect(result).toEventually(haveWebAuthError(expectedError))
}
it("should produce a no bundle identifier error when redirect URL is missing") {
let expectedError = WebAuthError(code: .noBundleIdentifier)
var result: WebAuthResult<Credentials>?
auth.redirectURL = nil
auth.start { result = $0 }
expect(result).toEventually(haveWebAuthError(expectedError))
}
context("transaction") {
beforeEach {
TransactionStore.shared.clear()
}
it("should store a new transaction") {
auth.start { _ in }
expect(TransactionStore.shared.current).toNot(beNil())
TransactionStore.shared.cancel()
}
it("should cancel the current transaction") {
var result: WebAuthResult<Credentials>?
auth.start { result = $0 }
TransactionStore.shared.cancel()
expect(result).to(haveWebAuthError(WebAuthError(code: .userCancelled)))
expect(TransactionStore.shared.current).to(beNil())
}
}
}
describe("logout") {
var auth: Auth0WebAuth!
beforeEach {
auth = newWebAuth()
}
it("should start the supplied provider") {
var isStarted = false
_ = auth.provider({ url, _ in
isStarted = true
return SpyUserAgent()
})
auth.start { _ in }
expect(isStarted).toEventually(beTrue())
}
it("should not include the federated parameter by default") {
var redirectURL: URL?
_ = auth.provider({ url, _ in
redirectURL = url
return SpyUserAgent()
})
auth.clearSession() { _ in }
expect(redirectURL?.query?.contains("federated")).toEventually(beFalse())
}
it("should include the federated parameter") {
var redirectURL: URL?
_ = auth.provider({ url, _ in
redirectURL = url
return SpyUserAgent()
})
auth.clearSession(federated: true) { _ in }
expect(redirectURL?.query?.contains("federated")).toEventually(beTrue())
}
it("should produce a no bundle identifier error when redirect URL is missing") {
var result: WebAuthResult<Void>?
auth.redirectURL = nil
auth.clearSession() { result = $0 }
expect(result).to(haveWebAuthError(WebAuthError(code: .noBundleIdentifier)))
}
context("transaction") {
var result: WebAuthResult<Void>?
beforeEach {
result = nil
TransactionStore.shared.clear()
}
it("should store a new transaction") {
auth.clearSession() { _ in }
expect(TransactionStore.shared.current).toNot(beNil())
}
it("should cancel the current transaction") {
auth.clearSession() { result = $0 }
TransactionStore.shared.cancel()
expect(result).to(haveWebAuthError(WebAuthError(code: .userCancelled)))
expect(TransactionStore.shared.current).to(beNil())
}
it("should resume the current transaction") {
auth.clearSession() { result = $0 }
_ = TransactionStore.shared.resume(URL(string: "http://fake.com")!)
expect(result).to(beSuccessful())
expect(TransactionStore.shared.current).to(beNil())
}
}
}
#endif
}
}
| mit | ded364027ec5c536285c6800f30a0207 | 38.783654 | 159 | 0.512064 | 5.390879 | false | false | false | false |
gmission/gmission-ios | gmission/gmission/UserManager.swift | 1 | 3553 | //
// UserManager.swift
// gmission
//
// Created by CHEN Zhao on 6/12/2015.
// Copyright © 2015 CHEN Zhao. All rights reserved.
//
import Foundation
import SwiftyJSON
class User{
// class UserModel:JsonEntity{
// override class var urlname:String{return "user"}
// }
func refresh(done:F){
let paras = ["username":username, "password":password]
print(paras)
HTTP.requestJSON(.POST, "user/auth", paras) { (json) -> () in
print("refresh OK", json)
UserManager.global.afterLogin(json, pwd: self.password)
self.email = json["email"].stringValue
self.credit = json["credit"].intValue
done?()
}
}
var credit:Int!
var email:String!
// var model:UserModel! = nil
var id:Int = 0
var token:String = ""
var username:String = ""
var password:String = ""
init(id:Int, username:String, password:String,token:String){
self.id = id
self.token = token
self.username = username
self.password = password
}
}
class BaiduPushInfo:JsonEntity{
override class var urlname:String {return "baidu_push_info"}
}
class UserManager{
static let global = UserManager()
static var currentUser:User! = nil
static func logout(){
settings.save("", forKey: "loginUsername")
settings.save("", forKey: "loginPassword")
settings.save("", forKey: "loginToken")
settings.save("", forKey: "loginUserID")
settings.save("", forKey: "baidu_info_posted")
currentUser = nil
}
func postPushInfo(){
let bdPosted = settings.load("baidu_info_posted")
if bdPosted == ""{
let uid = UserManager.currentUser.id
let buid = SettingManager.global.load("baidu_user_id") ?? ""
let bcid = SettingManager.global.load("baidu_channel_id") ?? ""
let baiduPushInfo = BaiduPushInfo(jsonDict:["baidu_user_id":buid, "baidu_channel_id":bcid, "user_id":uid, "type":"ios", "is_valid":true])
BaiduPushInfo.postOne(baiduPushInfo) { (bpi:BaiduPushInfo) -> Void in
print("bpi posted")
settings.save("true", forKey: "baidu_info_posted")
}
}
}
func saveUserInfo(user:User){
settings.save(user.username, forKey: "loginUsername")
settings.save(user.password, forKey: "loginPassword")
settings.save(user.token, forKey: "loginToken")
settings.save("\(user.id)", forKey: "loginUserID")
}
func loadUserInfo(){
let username = settings.load("loginUsername") ?? ""
let password = settings.load("loginPassword") ?? ""
let token = settings.load("loginToken") ?? ""
let id = Int(settings.load("loginUserID") ?? "0") ?? 0
if id != 0 {
UserManager.currentUser = User(id:id, username:username, password:password, token:token)
}else{
print("no login user")
}
}
func afterLogin(json:JSON, pwd:String){
let user = User(id: json["id"].intValue, username: json["username"].stringValue, password: json["password"].stringValue, token: json["token"].stringValue)
user.password = pwd
user.credit = json["credit"].intValue
user.email = json["email"].stringValue
UserManager.currentUser = user
saveUserInfo(user)
postPushInfo()
}
init(){
}
}
//user = UserManager.global
| mit | 1dca5de62832b45b3f83a2e0fd8bea0d | 28.114754 | 162 | 0.583052 | 4.078071 | false | false | false | false |
SSamanta/SSPhotoBrowser | PhotoBrowser/PreviewImage.swift | 1 | 1542 | //
// PreviewImage.swift
// WovaxIOSApp
//
// Created by Susim Samanta on 11/05/16.
// Copyright © 2016 SusimSamanta. All rights reserved.
//
import UIKit
class PreviewImage: UIViewController,UIScrollViewDelegate {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var imageView: UIImageView!
var isShowingFullScreen = false
var image : UIImage?
var pageIndex : Int = 0
override func viewDidLoad() {
super.viewDidLoad()
self.loadUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func loadImage(image :UIImage) {
self.image = image
}
func loadUI(){
self.imageView.image = image
self.scrollView.minimumZoomScale = 1.0;
self.scrollView.maximumZoomScale = 6.0;
self.addTapGestureOnImage()
}
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return self.imageView
}
func addTapGestureOnImage(){
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.handleImageTap(_:)))
self.imageView.userInteractionEnabled = true
self.imageView.addGestureRecognizer(tapGestureRecognizer)
}
func handleImageTap(sender : UITapGestureRecognizer) {
isShowingFullScreen = !isShowingFullScreen
self.navigationController?.setNavigationBarHidden(isShowingFullScreen, animated: true)
self.navigationController?.setToolbarHidden(isShowingFullScreen, animated: true)
}
}
| mit | b2ba6e8ff203cdce30b1e3401369876d | 31.787234 | 115 | 0.698897 | 4.970968 | false | false | false | false |
BobElDevil/ScriptWorker | ScriptWorker/ScriptWorker+Commands.swift | 1 | 2847 | //
// ScriptWorker+Commands.swift
// ScriptWorker
//
// Created by Steve Marquis on 8/20/16.
// Copyright © 2016 Stephen Marquis. All rights reserved.
//
import Foundation
extension ScriptWorker {
/// Create a ScriptTask object with the given command name. The working directory of the task will be
/// set to 'path()' (or the parent directory if the current one doesn't exist)
public func task(_ command: String) -> ScriptTask {
let workingDir = directoryExists() ? path() : url().deletingLastPathComponent().path
return ScriptTask(command, workingDirectory: workingDir)
}
// MARK: Legacy methods for api compatibility
/// Launches the given command with the working directory set to path (or the parent directory if path is a file)
///
/// Returns a tuple with status, stdout and stderr
public func launch(commandForOutput command: String, arguments: [String] = [], environment: [String: String] = [:], exitOnFailure: Bool = false) -> (Int, String, String) {
let ret = task(command).args(arguments).env(environment)
if exitOnFailure {
ret.exitOnFailure()
}
return ret.runForOutput()
}
/// Launches the given command with the working directory set to path (or the parent directory if path is a file). If provided, calls dataHandler with any data from the command. If the bool is true, it came from stdout, otherwise stderr.
/// If not provided, all output is piped to the current stdout/stderr respectively
/// Note: While dataHandler is technically marked '@escaping', because we always wait for the task to complete, you can be guaranteed that dataHandler will not be called after this method completes.
///
/// Returns the status.
@discardableResult public func launch(command: String, arguments: [String] = [], environment: [String: String] = [:], exitOnFailure: Bool = false, dataHandler: ScriptTask.DataHandler? = nil) -> Int {
let ret = self.task(command).args(arguments).env(environment)
if exitOnFailure {
ret.exitOnFailure()
}
let status: Int
if let providedHandler = dataHandler {
ret.output(to: providedHandler)
status = ret.run(printOutput: false)
} else {
status = ret.run()
}
return status
}
// MARK: Background commands
public func launchBackground(command: String, arguments: [String] = [], environment: [String: String] = [:], dataHandler: ScriptTask.DataHandler? = nil, terminationHandler: ScriptTask.TerminationHandler? = nil) {
let task = self.task(command).args(arguments).env(environment)
if let dataHandler = dataHandler {
task.output(to: dataHandler)
}
task.runAsync(printOutput: false, terminationHandler)
}
}
| mit | f65a8f0a94d22a61b4588a5cccaf5833 | 44.174603 | 241 | 0.670766 | 4.582931 | false | false | false | false |
Cein-Markey/ios-guessinggame-app | Fingers/ViewController.swift | 1 | 942 | //
// ViewController.swift
// Fingers
//
// Created by Cein Markey on 9/13/15.
// Copyright © 2015 Cein Markey. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var userGuess: UITextField!
@IBOutlet var response: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func submitGuess(sender: AnyObject) {
let guess = String(arc4random_uniform(6))
if guess == userGuess.text {
response.text = "Correct! It was " + userGuess.text! + "!"
} else if userGuess.text == "" {
response.text = "Sorry, you need to make a guess!";
} else {
response.text = "Wrong! It was " + guess + "!"
}
}
}
| mit | 49f78a4c2bcb06b46c0d0b7ed8baa9e3 | 21.95122 | 70 | 0.583422 | 4.296804 | false | false | false | false |
AlphaJian/PaperCalculator | PaperCalculator/PaperCalculator/Views/Create/SettingPaperTableView.swift | 1 | 3664 | //
// ReviewPaperTableView.swift
// PaperCalculator
//
// Created by Jian Zhang on 9/28/16.
// Copyright © 2016 apple. All rights reserved.
//
import UIKit
class SettingPaperTableView: UITableView, UITableViewDelegate, UITableViewDataSource {
var model = DataManager.shareManager.paperModel
var numSection = 0
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
self.delegate = self
self.dataSource = self
self.register(NoneSettingCell.classForCoder(), forCellReuseIdentifier: "noneCell")
self.register(EditSettingCell.classForCoder(), forCellReuseIdentifier: "editCell")
self.separatorStyle = .none
}
required init?(coder aDecoder: NSCoder) {
fatalError("")
}
func numberOfSections(in tableView: UITableView) -> Int {
return model.sectionQuestionArr.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if model.sectionQuestionArr[indexPath.section].editStatus == .editing {
let cell = tableView.dequeueReusableCell(withIdentifier: "editCell") as! EditSettingCell
cell.clearCell()
cell.selectionStyle = .none
cell.initUI(questionNum: (model.sectionQuestionArr[indexPath.section].cellQuestionArr as NSArray).count , markNum: model.sectionQuestionArr[indexPath.section].preSettingQuesScore , index: indexPath)
cell.btnHandler = {
self.reloadData()
}
return cell
} else if model.sectionQuestionArr[indexPath.section].editStatus == QuestionStatus.none {
let cell = tableView.dequeueReusableCell(withIdentifier: "noneCell") as! NoneSettingCell
cell.clearCell()
cell.selectionStyle = .none
cell.initUI(questionNum: (model.sectionQuestionArr[indexPath.section].cellQuestionArr as NSArray).count , markNum: 5, index: indexPath)
cell.btnHandler = {
self.reloadData()
}
return cell
} else {
let cell = UITableViewCell(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
return cell
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: 40))
let titleLabel = UILabel(frame: CGRect(x: 10, y: 10, width: 100, height: 20))
titleLabel.text = "第 \(section + 1) 大题"
titleLabel.font = mediumFont
titleLabel.textColor = UIColor.white
view.addSubview(titleLabel)
view.backgroundColor = UIColor.darkGray
return view
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if model.sectionQuestionArr[indexPath.section].editStatus == .editing {
return CGFloat((model.sectionQuestionArr[indexPath.section].cellQuestionArr as NSArray).count) * 70 + 20
}else if model.sectionQuestionArr[indexPath.section].editStatus == .finish {
return 0
} else {
return 150
}
}
}
| gpl-3.0 | daf9bc48380671694b55d75947f157b0 | 34.504854 | 210 | 0.617446 | 5.136236 | false | false | false | false |
cristinasitaa/Bubbles | Bubbles/Bubbles/AppDelegate.swift | 1 | 2607 | //
// AppDelegate.swift
// Bubbles
//
// Created by Admin on 4/11/17.
// Copyright © 2017 Admin. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.backgroundColor = UIColor.white
let viewController = ViewController(nibName: "ViewController", bundle: nil)
let welcomeNavigationController = UINavigationController(rootViewController: viewController)
self.window?.rootViewController = welcomeNavigationController
self.window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | eefc7db0791245c8c2bc94f1cff43d67 | 43.931034 | 285 | 0.739447 | 5.765487 | false | false | false | false |
zixun/GodEye | GodEye/Classes/Main/ORM/CrashRecordModel+ORM.swift | 1 | 2241 | //
// CrashRecordModel+ORM.swift
// Pods
//
// Created by zixun on 17/1/9.
//
//
import Foundation
import SQLite
extension CrashRecordModel: RecordORMProtocol {
static var type: RecordType {
return RecordType.crash
}
func mappingToRelation() -> [Setter] {
return [CrashRecordModel.col.type <- self.type.rawValue,
CrashRecordModel.col.name <- self.name,
CrashRecordModel.col.reason <- self.reason,
CrashRecordModel.col.appinfo <- self.appinfo,
CrashRecordModel.col.callStack <- self.callStack]
}
static func mappingToObject(with row: Row) -> CrashRecordModel {
let type = CrashModelType(rawValue:row[CrashRecordModel.col.type])!
let name = row[CrashRecordModel.col.name]
let reason = row[CrashRecordModel.col.reason]
let appinfo = row[CrashRecordModel.col.appinfo]
let callStack = row[CrashRecordModel.col.callStack]
return CrashRecordModel(type: type, name: name, reason: reason, appinfo: appinfo, callStack: callStack)
}
static func configure(tableBuilder:TableBuilder) {
tableBuilder.column(CrashRecordModel.col.type)
tableBuilder.column(CrashRecordModel.col.name)
tableBuilder.column(CrashRecordModel.col.reason)
tableBuilder.column(CrashRecordModel.col.appinfo)
tableBuilder.column(CrashRecordModel.col.callStack)
}
static func configure(select table:Table) -> Table {
return table.select(CrashRecordModel.col.type,
CrashRecordModel.col.name,
CrashRecordModel.col.reason,
CrashRecordModel.col.appinfo,
CrashRecordModel.col.callStack)
}
func attributeString() -> NSAttributedString {
return CrashRecordViewModel(self).attributeString()
}
class col: NSObject {
static let type = Expression<Int>("type")
static let name = Expression<String>("name")
static let reason = Expression<String>("reason")
static let appinfo = Expression<String>("appinfo")
static let callStack = Expression<String>("callStack")
}
}
| mit | 9216022929287bed87a50b259ae72ee8 | 35.145161 | 111 | 0.641678 | 4.678497 | false | false | false | false |
mikaoj/EnigmaKit | Sources/EnigmaKit/Rotor.swift | 1 | 4104 | // The MIT License (MIT)
//
// Copyright (c) 2017 Joakim Gyllström
//
// 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
public struct Rotor {
enum Direction {
case `in`
case out
}
public var name: String
public var notches: [Character]
public var position: Int
public var setting: Int {
get {
return wheel.setting
}
set {
wheel.setting = newValue
}
}
var wheel: Wheel
public init(name: String, wiring: [Character], notch: [Character], position: Int = 0, setting: Int = 0) {
self.name = name
self.notches = notch
self.wheel = try! Wheel(inner: wiring, setting: setting)
self.position = position
}
mutating func step() {
position += 1
// Reset to if we go out of bounds
if position >= wheel.outer.count {
position = 0
}
}
public var isAtNotch: Bool {
return notches.contains(wheel.outer[position])
}
}
extension Rotor {
func encode(_ character: Character, direction: Direction) -> Character {
switch direction {
case .in:
return code(character, coder: wheel.encode)
case .out:
return code(character, coder: wheel.decode)
}
}
private func code(_ character: Character, coder: (Character) -> Character) -> Character {
// Get index of character
guard let inputIndex = wheel.outer.firstIndex(of: character) else { return character }
// Encode character at that index + offset
let c = coder(wheel.outer[wrap: inputIndex + position])
// Get index of encoded character
guard let outputIndex = wheel.outer.firstIndex(of: c) else { return character }
// Aaand return character at that index - offset
return wheel.outer[wrap: outputIndex - position]
}
}
extension Rotor: Equatable {
public static func ==(lhs: Rotor, rhs: Rotor) -> Bool {
return lhs.name == rhs.name && lhs.notches == rhs.notches && lhs.position == rhs.position && lhs.wheel == rhs.wheel
}
}
extension Rotor {
// Convenience initializer
public init(name: String, wiring: String, notch: String) {
self.init(name: name, wiring: Array(wiring), notch: Array(notch))
}
public static var I: Rotor {
return Rotor(name: "I", wiring: "EKMFLGDQVZNTOWYHXUSPAIBRCJ", notch: "Q")
}
public static var II: Rotor {
return Rotor(name: "II", wiring: "AJDKSIRUXBLHWTMCQGZNPYFVOE", notch: "E")
}
public static var III: Rotor {
return Rotor(name: "III", wiring: "BDFHJLCPRTXVZNYEIWGAKMUSQO", notch: "V")
}
public static var IV: Rotor {
return Rotor(name: "IV", wiring: "ESOVPZJAYQUIRHXLNFTGKDCMWB", notch: "J")
}
public static var V: Rotor {
return Rotor(name: "V", wiring: "VZBRGITYUPSDNHLXAWMJQOFECK", notch: "Z")
}
public static var VI: Rotor {
return Rotor(name: "VI", wiring: "JPGVOUMFYQBENHZRDKASXLICTW", notch: "ZM")
}
public static var VII: Rotor {
return Rotor(name: "VII", wiring: "NZJHGRCXMYSWBOUFAIVLPEKQDT", notch: "ZM")
}
public static var VIII: Rotor {
return Rotor(name: "VIII", wiring: "FKQHTLXOCBJSPDZRAMEWNIUYGV", notch: "ZM")
}
}
| mit | 16c93947c3741c61e18dcb3daaf73c84 | 29.849624 | 119 | 0.686815 | 3.586538 | false | false | false | false |
vadymmarkov/Pitchy | Source/Calculators/NoteCalculator.swift | 1 | 3124 | import Foundation
public struct NoteCalculator {
public struct Standard {
public static let frequency = 440.0
public static let octave = 4
}
public static var letters: [Note.Letter] = [
.A,
.ASharp,
.B,
.C,
.CSharp,
.D,
.DSharp,
.E,
.F,
.FSharp,
.G,
.GSharp
]
// MARK: - Bounds
public static var indexBounds: (minimum: Int, maximum: Int) {
let minimum = try! index(forFrequency: FrequencyValidator.minimumFrequency)
let maximum = try! index(forFrequency: FrequencyValidator.maximumFrequency)
return (minimum: minimum, maximum: maximum)
}
public static var octaveBounds: (minimum: Int, maximum: Int) {
let bounds = indexBounds
let minimum = try! octave(forIndex: bounds.minimum)
let maximum = try! octave(forIndex: bounds.maximum)
return (minimum: minimum, maximum: maximum)
}
// MARK: - Validators
public static func isValid(index: Int) -> Bool {
let bounds = indexBounds
return index >= bounds.minimum
&& index <= bounds.maximum
}
public static func validate(index: Int) throws {
if !isValid(index: index) {
throw PitchError.invalidPitchIndex
}
}
public static func isValid(octave: Int) -> Bool {
let bounds = octaveBounds
return octave >= bounds.minimum
&& octave <= bounds.maximum
}
public static func validate(octave: Int) throws {
if !isValid(octave: octave) {
throw PitchError.invalidOctave
}
}
// MARK: - Pitch Notations
public static func frequency(forIndex index: Int) throws -> Double {
try validate(index: index)
let count = letters.count
let power = Double(index) / Double(count)
return pow(2, power) * Standard.frequency
}
public static func letter(forIndex index: Int) throws -> Note.Letter {
try validate(index: index)
let count = letters.count
var lettersIndex = index < 0
? count - abs(index) % count
: index % count
if lettersIndex == 12 {
lettersIndex = 0
}
guard lettersIndex >= 0 && lettersIndex < letters.count else {
throw PitchError.invalidPitchIndex
}
return letters[lettersIndex]
}
public static func octave(forIndex index: Int) throws -> Int {
try validate(index: index)
let count = letters.count
let resNegativeIndex = Standard.octave - (abs(index) + 2) / count
let resPositiveIndex = Standard.octave + (index + 9) / count
return index < 0
? resNegativeIndex
: resPositiveIndex
}
// MARK: - Pitch Index
public static func index(forFrequency frequency: Double) throws -> Int {
try FrequencyValidator.validate(frequency: frequency)
let count = Double(letters.count)
return Int(round(count * log2(frequency / Standard.frequency)))
}
public static func index(forLetter letter: Note.Letter, octave: Int) throws -> Int {
try validate(octave: octave)
let count = letters.count
let letterIndex = letters.index(of: letter) ?? 0
let offset = letterIndex < 3 ? 0 : count
return letterIndex + count * (octave - Standard.octave) - offset
}
}
| mit | c46794638782c0acd6220d9161f967cd | 23.40625 | 86 | 0.65685 | 4.025773 | false | false | false | false |
andyyhope/Elbbbird | Elbbbird/ViewModel/FeedViewModel.swift | 1 | 2197 | //
// FeedViewModel.swift
// Elbbbird
//
// Created by Andyy Hope on 19/03/2016.
// Copyright © 2016 Andyy Hope. All rights reserved.
//
import Foundation
import RxSwift
import RxViewModel
class FeedViewModel : RxViewModel {
let shots: [Shot]
init(shots: [Shot]) {
self.shots = shots
}
func viewModelForHeadingCell(atIndexPath indexPath: NSIndexPath) -> FeedViewHeadingCellViewModel {
let viewModel = FeedViewHeadingCellViewModel(shot: shots[indexPath.section])
return viewModel
}
func viewModelForImageCell(atIndexPath indexPath: NSIndexPath) -> FeedViewImageCellViewModel {
let viewModel = FeedViewImageCellViewModel(shot: shots[indexPath.section])
return viewModel
}
func viewModelForDetailCell(atIndexPath indexPath: NSIndexPath) -> FeedViewDetailCellViewModel {
let viewModel = FeedViewDetailCellViewModel(shot: shots[indexPath.section])
return viewModel
}
}
struct FeedViewHeadingCellViewModel {
let shot: Shot
let username: String
let location: String
let date: String
let imageURL: NSURL
init(shot: Shot, username: String = "", location: String = "", date: String = "", imageURL: NSURL = NSURL()) {
self.shot = shot
self.username = shot.user?.username ?? username
self.location = shot.user?.location ?? location
self.date = date
self.imageURL = NSURL(string: shot.user?.avatarURL ?? "") ?? NSURL()
}
}
struct FeedViewImageCellViewModel {
let imageURL: NSURL
init(shot: Shot, imageURL: NSURL = NSURL()) {
self.imageURL = NSURL(string: shot.images.normalURL) ?? NSURL()
}
}
struct FeedViewDetailCellViewModel {
let title: String
let description: String
let comments: String
let likes: String
init(shot: Shot, title: String = "", description: String = "", comments: String = "0", likes: String = "0") {
self.title = shot.title ?? title
self.description = shot.description ?? description
self.comments = String(shot.comments?.count ?? 0)
self.likes = String(shot.likes?.count ?? 0)
}
} | gpl-3.0 | a7e01dc5db2674316486de8440040dd2 | 28.293333 | 114 | 0.65255 | 4.445344 | false | false | false | false |
nathawes/swift | test/Constraints/argument_matching.swift | 3 | 76879 | // RUN: %target-typecheck-verify-swift
// Single extraneous keyword argument (tuple-to-scalar)
func f1(_ a: Int) { }
f1(a: 5) // expected-error{{extraneous argument label 'a:' in call}}{{4-7=}}
struct X1 {
init(_ a: Int) { }
func f1(_ a: Int) {}
}
X1(a: 5).f1(b: 5)
// expected-error@-1 {{extraneous argument label 'a:' in call}} {{4-7=}}
// expected-error@-2 {{extraneous argument label 'b:' in call}} {{13-16=}}
// <rdar://problem/16801056>
enum Policy {
case Head(Int)
}
func extra2(x: Int, y: Int) { }
func testExtra2(_ policy : Policy) {
switch (policy)
{
case .Head(let count):
extra2(x: 0, y: count)
}
}
// Single missing keyword argument (scalar-to-tuple)
func f2(a: Int) { }
f2(5) // expected-error{{missing argument label 'a:' in call}}{{4-4=a: }}
struct X2 {
init(a: Int) { }
func f2(b: Int) { }
}
X2(5).f2(5)
// expected-error@-1 {{missing argument label 'a:' in call}} {{4-4=a: }}
// expected-error@-2 {{missing argument label 'b:' in call}} {{10-10=b: }}
// -------------------------------------------
// Missing keywords
// -------------------------------------------
func allkeywords1(x: Int, y: Int) { }
// Missing keywords.
allkeywords1(1, 2) // expected-error{{missing argument labels}} {{14-14=x: }} {{17-17=y: }}
allkeywords1(x: 1, 2) // expected-error{{missing argument label 'y:' in call}} {{20-20=y: }}
allkeywords1(1, y: 2) // expected-error{{missing argument label 'x:' in call}} {{14-14=x: }}
// If keyword is reserved, make sure to quote it. rdar://problem/21392294
func reservedLabel(_ x: Int, `repeat`: Bool) {}
reservedLabel(1, true) // expected-error{{missing argument label 'repeat:' in call}}{{18-18=repeat: }}
// Insert missing keyword before initial backtick. rdar://problem/21392294 part 2
func reservedExpr(_ x: Int, y: Int) {}
let `do` = 2
reservedExpr(1, `do`) // expected-error{{missing argument label 'y:' in call}}{{17-17=y: }}
reservedExpr(1, y: `do`)
class GenericCtor<U> {
init<T>(t : T) {} // expected-note {{'init(t:)' declared here}}
}
GenericCtor<Int>() // expected-error{{missing argument for parameter 't' in call}}
func secondArgumentNotLabeled(a: Int, _ b: Int) { }
secondArgumentNotLabeled(10, 20)
// expected-error@-1 {{missing argument label 'a:' in call}}
func f_31849281(x: Int, y: Int, z: Int) {}
f_31849281(42, y: 10, x: 20) // expected-error {{incorrect argument labels in call (have '_:y:x:', expected 'x:y:z:')}} {{12-12=x: }} {{23-24=z}}
// -------------------------------------------
// Extraneous keywords
// -------------------------------------------
func nokeywords1(_ x: Int, _ y: Int) { }
nokeywords1(x: 1, y: 1) // expected-error{{extraneous argument labels 'x:y:' in call}}{{13-16=}}{{19-22=}}
// -------------------------------------------
// Some missing, some extraneous keywords
// -------------------------------------------
func somekeywords1(_ x: Int, y: Int, z: Int) { }
somekeywords1(x: 1, y: 2, z: 3) // expected-error{{extraneous argument label 'x:' in call}}{{15-18=}}
somekeywords1(1, 2, 3) // expected-error{{missing argument labels 'y:z:' in call}}{{18-18=y: }}{{21-21=z: }}
somekeywords1(x: 1, 2, z: 3) // expected-error{{incorrect argument labels in call (have 'x:_:z:', expected '_:y:z:')}}{{15-18=}}{{21-21=y: }}
// SR-2242: poor diagnostic when argument label is omitted
func r27212391(x: Int, _ y: Int) {
let _: Int = x + y
}
func r27212391(a: Int, x: Int, _ y: Int) {
let _: Int = a + x + y
}
r27212391(3, 5) // expected-error {{missing argument label 'x:' in call}}
r27212391(3, y: 5) // expected-error {{incorrect argument labels in call (have '_:y:', expected 'x:_:')}}
r27212391(3, x: 5) // expected-error {{argument 'x' must precede unnamed argument #1}} {{11-11=x: 5, }} {{12-18=}}
r27212391(y: 3, x: 5) // expected-error {{incorrect argument labels in call (have 'y:x:', expected 'x:_:')}} {{11-12=x}} {{17-20=}}
r27212391(y: 3, 5) // expected-error {{incorrect argument label in call (have 'y:_:', expected 'x:_:')}}
r27212391(x: 3, x: 5) // expected-error {{extraneous argument label 'x:' in call}}
r27212391(a: 1, 3, y: 5) // expected-error {{incorrect argument labels in call (have 'a:_:y:', expected 'a:x:_:')}}
r27212391(1, x: 3, y: 5) // expected-error {{incorrect argument labels in call (have '_:x:y:', expected 'a:x:_:')}}
r27212391(a: 1, y: 3, x: 5) // expected-error {{incorrect argument labels in call (have 'a:y:x:', expected 'a:x:_:')}}
r27212391(a: 1, 3, x: 5) // expected-error {{argument 'x' must precede unnamed argument #2}} {{17-17=x: 5, }} {{18-24=}}
// -------------------------------------------
// Out-of-order keywords
// -------------------------------------------
allkeywords1(y: 1, x: 2) // expected-error{{argument 'x' must precede argument 'y'}} {{14-14=x: 2, }} {{18-24=}}
// rdar://problem/31849281 - Let's play "bump the argument"
struct rdar31849281 { var foo, a, b, c: Int }
_ = rdar31849281(a: 101, b: 102, c: 103, foo: 104) // expected-error {{argument 'foo' must precede argument 'a'}} {{18-18=foo: 104, }} {{40-50=}}
_ = rdar31849281(a: 101, c: 103, b: 102, foo: 104) // expected-error {{argument 'foo' must precede argument 'a'}} {{18-18=foo: 104, }} {{40-50=}}
_ = rdar31849281(foo: 104, a: 101, c: 103, b: 102) // expected-error {{argument 'b' must precede argument 'c'}} {{36-36=b: 102, }} {{42-50=}}
_ = rdar31849281(b: 102, c: 103, a: 101, foo: 104) // expected-error {{incorrect argument labels in call (have 'b:c:a:foo:', expected 'foo:a:b:c:')}} {{18-19=foo}} {{26-27=a}} {{34-35=b}} {{42-45=c}}
_ = rdar31849281(foo: 104, b: 102, c: 103, a: 101) // expected-error {{argument 'a' must precede argument 'b'}} {{28-28=a: 101, }} {{42-50=}}
func fun_31849281(a: (Bool) -> Bool, b: (Int) -> (String), c: [Int?]) {}
fun_31849281(c: [nil, 42], a: { !$0 }, b: { (num: Int) -> String in return "\(num)" })
// expected-error @-1 {{incorrect argument labels in call (have 'c:a:b:', expected 'a:b:c:')}} {{14-15=a}} {{28-29=b}} {{40-41=c}}
fun_31849281(a: { !$0 }, c: [nil, 42], b: { (num: Int) -> String in return String(describing: num) })
// expected-error @-1 {{argument 'b' must precede argument 'c'}} {{26-26=b: { (num: Int) -> String in return String(describing: num) }, }} {{38-101=}}
fun_31849281(a: { !$0 }, c: [nil, 42], b: { "\($0)" })
// expected-error @-1 {{argument 'b' must precede argument 'c'}} {{26-26=b: { "\\($0)" }, }} {{38-54=}}
struct ReorderAndAllLabels {
func f(aa: Int, bb: Int, cc: Int, dd: Int) {}
func test() {
f(bb: 1, ccx: 2, ddx: 3, aa: 0) // expected-error {{argument 'aa' must precede argument 'bb'}} {{28-35=}} {{7-7=aa: 0, }} {{none}}
f(bbx: 1, ccx: 2, ddx: 3, aa: 0) // expected-error {{incorrect argument labels in call (have 'bbx:ccx:ddx:aa:', expected 'aa:bb:cc:dd:')}} {{7-10=aa}} {{15-18=bb}} {{23-26=cc}} {{31-33=dd}} {{none}}
}
}
// -------------------------------------------
// Default arguments
// -------------------------------------------
func defargs1(x: Int = 1, y: Int = 2, z: Int = 3) {}
// Using defaults (in-order)
defargs1()
defargs1(x: 1)
defargs1(x: 1, y: 2)
// Using defaults (in-order, some missing)
defargs1(y: 2)
defargs1(y: 2, z: 3)
defargs1(z: 3)
defargs1(x: 1, z: 3)
// Using defaults (out-of-order, error by SE-0060)
defargs1(z: 3, y: 2, x: 1) // expected-error{{argument 'x' must precede argument 'z'}} {{10-10=x: 1, }} {{20-26=}}
defargs1(x: 1, z: 3, y: 2) // expected-error{{argument 'y' must precede argument 'z'}} {{16-16=y: 2, }} {{20-26=}}
defargs1(y: 2, x: 1) // expected-error{{argument 'x' must precede argument 'y'}} {{10-10=x: 1, }} {{14-20=}}
// Default arguments "boxed in".
func defargs2(first: Int, x: Int = 1, y: Int = 2, z: Int = 3, last: Int) { }
// Using defaults in the middle (in-order, some missing)
defargs2(first: 1, x: 1, z: 3, last: 4)
defargs2(first: 1, x: 1, last: 4)
defargs2(first: 1, y: 2, z: 3, last: 4)
defargs2(first: 1, last: 4)
// Using defaults in the middle (out-of-order, error by SE-0060)
defargs2(first: 1, z: 3, x: 1, last: 4) // expected-error{{argument 'x' must precede argument 'z'}} {{20-20=x: 1, }} {{24-30=}}
defargs2(first: 1, z: 3, y: 2, last: 4) // expected-error{{argument 'y' must precede argument 'z'}} {{20-20=y: 2, }} {{24-30=}}
// Using defaults that have moved past a non-defaulted parameter
defargs2(x: 1, first: 1, last: 4) // expected-error{{argument 'first' must precede argument 'x'}} {{10-10=first: 1, }} {{14-24=}}
defargs2(first: 1, last: 4, x: 1) // expected-error{{argument 'x' must precede argument 'last'}} {{20-20=x: 1, }} {{27-33=}}
func rdar43525641(_ a: Int, _ b: Int = 0, c: Int = 0, _ d: Int) {}
rdar43525641(1, c: 2, 3) // Ok
func testLabelErrorDefault() {
func f(aa: Int, bb: Int, cc: Int = 0) {}
f(aax: 0, bbx: 1, cc: 2)
// expected-error@-1 {{incorrect argument labels in call (have 'aax:bbx:cc:', expected 'aa:bb:cc:')}}
f(aax: 0, bbx: 1)
// expected-error@-1 {{incorrect argument labels in call (have 'aax:bbx:', expected 'aa:bb:')}}
}
// -------------------------------------------
// Variadics
// -------------------------------------------
func variadics1(x: Int, y: Int, _ z: Int...) { }
// Using variadics (in-order, complete)
variadics1(x: 1, y: 2)
variadics1(x: 1, y: 2, 1)
variadics1(x: 1, y: 2, 1, 2)
variadics1(x: 1, y: 2, 1, 2, 3)
// Using various (out-of-order)
variadics1(1, 2, 3, 4, 5, x: 6, y: 7) // expected-error {{incorrect argument labels in call (have '_:_:_:_:_:x:y:', expected 'x:y:_:')}} {{12-12=x: }} {{15-15=y: }} {{27-30=}} {{33-36=}}
func variadics2(x: Int, y: Int = 2, z: Int...) { } // expected-note {{'variadics2(x:y:z:)' declared here}}
// Using variadics (in-order, complete)
variadics2(x: 1, y: 2, z: 1)
variadics2(x: 1, y: 2, z: 1, 2)
variadics2(x: 1, y: 2, z: 1, 2, 3)
// Using variadics (in-order, some missing)
variadics2(x: 1, z: 1, 2, 3)
variadics2(x: 1)
// Using variadics (out-of-order)
variadics2(z: 1, 2, 3, y: 2) // expected-error{{missing argument for parameter 'x' in call}}
variadics2(z: 1, 2, 3, x: 1) // expected-error{{argument 'x' must precede argument 'z'}} {{12-12=x: 1, }} {{22-28=}}
func variadics3(_ x: Int..., y: Int = 2, z: Int = 3) { }
// Using variadics (in-order, complete)
variadics3(1, 2, 3, y: 0, z: 1)
variadics3(1, y: 0, z: 1)
variadics3(y: 0, z: 1)
// Using variadics (in-order, some missing)
variadics3(1, 2, 3, y: 0)
variadics3(1, z: 1)
variadics3(z: 1)
variadics3(1, 2, 3, z: 1)
variadics3(1, z: 1)
variadics3(z: 1)
variadics3(1, 2, 3)
variadics3(1)
variadics3()
// Using variadics (out-of-order)
variadics3(y: 0, 1, 2, 3) // expected-error{{unnamed argument #2 must precede argument 'y'}} {{12-12=1, 2, 3, }} {{16-25=}}
variadics3(z: 1, 1) // expected-error{{unnamed argument #2 must precede argument 'z'}} {{12-12=1, }} {{16-19=}}
func variadics4(x: Int..., y: Int = 2, z: Int = 3) { }
// Using variadics (in-order, complete)
variadics4(x: 1, 2, 3, y: 0, z: 1)
variadics4(x: 1, y: 0, z: 1)
variadics4(y: 0, z: 1)
// Using variadics (in-order, some missing)
variadics4(x: 1, 2, 3, y: 0)
variadics4(x: 1, z: 1)
variadics4(z: 1)
variadics4(x: 1, 2, 3, z: 1)
variadics4(x: 1, z: 1)
variadics4(z: 1)
variadics4(x: 1, 2, 3)
variadics4(x: 1)
variadics4()
// Using variadics (in-order, some missing)
variadics4(y: 0, x: 1, 2, 3) // expected-error{{argument 'x' must precede argument 'y'}} {{12-12=x: 1, 2, 3, }} {{16-28=}}
variadics4(z: 1, x: 1) // expected-error{{argument 'x' must precede argument 'z'}} {{12-12=x: 1, }} {{16-22=}}
func variadics5(_ x: Int, y: Int, _ z: Int...) { } // expected-note {{declared here}}
// Using variadics (in-order, complete)
variadics5(1, y: 2)
variadics5(1, y: 2, 1)
variadics5(1, y: 2, 1, 2)
variadics5(1, y: 2, 1, 2, 3)
// Using various (out-of-order)
variadics5(1, 2, 3, 4, 5, 6, y: 7) // expected-error{{argument 'y' must precede unnamed argument #2}} {{15-15=y: 7, }} {{28-34=}}
variadics5(y: 1, 2, 3, 4, 5, 6, 7) // expected-error{{missing argument for parameter #1 in call}}
func variadics6(x: Int..., y: Int = 2, z: Int) { } // expected-note 4 {{'variadics6(x:y:z:)' declared here}}
// Using variadics (in-order, complete)
variadics6(x: 1, 2, 3, y: 0, z: 1)
variadics6(x: 1, y: 0, z: 1)
variadics6(y: 0, z: 1)
// Using variadics (in-order, some missing)
variadics6(x: 1, 2, 3, y: 0) // expected-error{{missing argument for parameter 'z' in call}}
variadics6(x: 1, z: 1)
variadics6(z: 1)
variadics6(x: 1, 2, 3, z: 1)
variadics6(x: 1, z: 1)
variadics6(z: 1)
variadics6(x: 1, 2, 3) // expected-error{{missing argument for parameter 'z' in call}}
variadics6(x: 1) // expected-error{{missing argument for parameter 'z' in call}}
variadics6() // expected-error{{missing argument for parameter 'z' in call}}
func variadics7(_ x: Int..., y: Int...) { }
// Using multiple variadics (in order, complete)
variadics7(1, y: 2)
variadics7(1, 2, 3, y: 4, 5, 6)
variadics7(1, 2, y: 2)
variadics7(1, y: 2, 1)
// multiple variadics, in order, some missing
variadics7(y: 1)
variadics7(1)
variadics7(y: 4, 5, 6)
variadics7(1, 2, 3)
func variadics8(x: Int..., y: Int...) { }
// multiple variadics, out of order
variadics8(y: 1, x: 2) // expected-error {{argument 'x' must precede argument 'y'}} {{12-12=x: 2, }} {{16-22=}}
variadics8(y: 1, 2, 3, x: 4) // expected-error {{argument 'x' must precede argument 'y'}} {{12-12=x: 4, }} {{22-28=}}
variadics8(y: 1, x: 2, 3, 4) // expected-error {{argument 'x' must precede argument 'y'}} {{12-12=x: 2, 3, 4, }} {{16-28=}}
variadics8(y: 1, 2, 3, x: 4, 5, 6) // expected-error {{argument 'x' must precede argument 'y'}} {{12-12=x: 4, 5, 6, }} {{22-34=}}
func variadics9(_ a: Int..., b: Int, _ c: Int...) { } // expected-note {{'variadics9(_:b:_:)' declared here}}
// multiple split variadics, in order, complete
variadics9(1, b: 2, 3)
variadics9(1, 2, 3, b: 2, 3)
variadics9(1, b: 2, 3, 2, 1)
variadics9(1, 2, 3, b: 2, 3, 2, 1)
// multiple split variadics, in order, some missing
variadics9(b: 2, 3)
variadics9(1, b: 2)
variadics9(1, 2, b: 2)
variadics9(b: 2, 3, 2, 1)
// multiple split variadics, required missing
variadics9(1) // expected-error {{missing argument for parameter 'b' in call}}
func variadics10(_ a: Int..., b: Int = 2, _ c: Int...) { }
// multiple unlabeled variadics split by defaulted param, in order, complete
variadics10(1, b: 2, 3)
variadics10(1, 2, 3, b: 2, 3)
variadics10(1, b: 2, 3, 2, 1)
variadics10(1, 2, 3, b: 2, 3, 2, 1)
// multiple unlabeled variadics split by defaulted param, in order, some missing
variadics10(1, 2, 3)
variadics10(1, 2, 3, b: 3)
variadics10(b: 3)
func variadics11(_ a: Int..., b: Bool = false, _ c: String...) { }
variadics11(1, 2, 3, b: true, "hello", "world")
variadics11(b: true, "hello", "world")
variadics11(1, 2, 3, b: true)
variadics11(b: true)
variadics11()
variadics11(1, 2, 3, "hello", "world") // expected-error 2 {{cannot convert value of type 'String' to expected argument type 'Int'}}
func variadics12(a: Int..., b: Int, c: Int...) { }
variadics12(a: 1, 2, 3, b: 4, c: 5, 6, 7)
variadics12(b: 4, c: 5, 6, 7)
variadics12(a: 1, 2, 3, b: 4)
variadics12(c: 5, 6, 7, b: 4, a: 1, 2, 3) // expected-error {{incorrect argument labels in call (have 'c:_:_:b:a:_:_:', expected 'a:b:c:')}} {{13-14=a}} {{19-19=b: }} {{22-22=c: }} {{25-28=}} {{31-34=}}
// Edge cases involving multiple trailing closures and forward matching.
func variadics13(a: Int..., b: (()->Void)...) {}
variadics13()
variadics13(a: 1, 2, 3) {} _: {} _: {}
variadics13() {} _: {} _: {}
variadics13(a: 1, 2, 3)
variadics13(a: 1, 2, 3) {}
func variadics14(a: (()->Void)..., b: (()->Void)...) {} // expected-note {{'variadics14(a:b:)' declared here}}
variadics14(a: {}, {}, b: {}, {})
variadics14(a: {}, {}) {} _: {}
variadics14 {} _: {} b: {} _: {}
variadics14 {} b: {}
variadics14 {} // expected-warning {{backward matching of the unlabeled trailing closure is deprecated; label the argument with 'b' to suppress this warning}}
func outOfOrder(_ a : Int, b: Int) {
outOfOrder(b: 42, 52) // expected-error {{unnamed argument #2 must precede argument 'b'}} {{14-14=52, }} {{19-23=}}
}
struct Variadics7 {
func f(alpha: Int..., bravo: Int) {} // expected-note {{'f(alpha:bravo:)' declared here}}
// expected-note@-1 {{'f(alpha:bravo:)' declared here}}
func test() {
// no error
f(bravo: 0)
f(alpha: 0, bravo: 3)
f(alpha: 0, 1, bravo: 3)
f(alpha: 0, 1, 2, bravo: 3)
// OoO
f(bravo: 0, alpha: 1) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
f(bravo: 0, alpha: 1, 2) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
f(bravo: 0, alpha: 1, 2, 3) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
// typo A
f(alphax: 0, bravo: 3) // expected-error {{incorrect argument label in call (have 'alphax:bravo:', expected 'alpha:bravo:')}}
f(alphax: 0, 1, bravo: 3) // expected-error {{extra argument in call}}
f(alphax: 0, 1, 2, bravo: 3) // expected-error {{extra arguments at positions #2, #3 in call}}
// typo B
f(bravox: 0) // expected-error {{incorrect argument label in call (have 'bravox:', expected 'bravo:')}}
f(alpha: 0, bravox: 3) // expected-error {{incorrect argument label in call (have 'alpha:bravox:', expected 'alpha:bravo:')}}
f(alpha: 0, 1, bravox: 3) // expected-error {{incorrect argument label in call (have 'alpha:_:bravox:', expected 'alpha:_:bravo:')}}
f(alpha: 0, 1, 2, bravox: 3) // expected-error {{incorrect argument label in call (have 'alpha:_:_:bravox:', expected 'alpha:_:_:bravo:')}}
// OoO + typo A B
f(bravox: 0, alphax: 1) // expected-error {{incorrect argument labels in call (have 'bravox:alphax:', expected 'alpha:bravo:')}}
f(bravox: 0, alphax: 1, 2) // expected-error {{extra argument in call}}
f(bravox: 0, alphax: 1, 2, 3) // expected-error {{extra arguments at positions #3, #4 in call}}
}
}
struct Variadics8 {
func f(alpha: Int..., bravo: Int, charlie: Int) {} // expected-note {{'f(alpha:bravo:charlie:)' declared here}}
func test() {
// no error
f(bravo: 3, charlie: 4)
f(alpha: 0, bravo: 3, charlie: 4)
f(alpha: 0, 1, bravo: 3, charlie: 4)
f(alpha: 0, 1, 2, bravo: 3, charlie: 4)
// OoO ACB
f(charlie: 3, bravo: 4) // expected-error {{argument 'bravo' must precede argument 'charlie'}}
f(alpha: 0, charlie: 3, bravo: 4) // expected-error {{argument 'bravo' must precede argument 'charlie'}}
f(alpha: 0, 1, charlie: 3, bravo: 4) // expected-error {{argument 'bravo' must precede argument 'charlie'}}
f(alpha: 0, 1, 2, charlie: 3, bravo: 4) // expected-error {{argument 'bravo' must precede argument 'charlie'}}
// OoO CAB
f(charlie: 0, alpha: 1, bravo: 4) // expected-error {{incorrect argument labels in call (have 'charlie:alpha:bravo:', expected 'alpha:bravo:charlie:')}}
f(charlie: 0, alpha: 1, 2, bravo: 4) // expected-error {{incorrect argument labels in call (have 'charlie:alpha:_:bravo:', expected 'alpha:bravo:charlie:')}}
f(charlie: 0, alpha: 1, 2, 3, bravo: 4) // expected-error {{incorrect argument labels in call (have 'charlie:alpha:_:_:bravo:', expected 'alpha:bravo:charlie:')}}
// OoO BAC
f(bravo: 0, alpha: 1, charlie: 4) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
f(bravo: 0, alpha: 1, 2, charlie: 4) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
f(bravo: 0, alpha: 1, 2, 3, charlie: 4) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
// typo A
f(alphax: 0, bravo: 3, charlie: 4) // expected-error {{incorrect argument label in call (have 'alphax:bravo:charlie:', expected 'alpha:bravo:charlie:')}}
f(alphax: 0, 1, bravo: 3, charlie: 4) // expected-error {{extra argument in call}}
f(alphax: 0, 1, 2, bravo: 3, charlie: 4) // expected-error {{extra arguments at positions #2, #3 in call}}
// typo B
f(bravox: 3, charlie: 4) // expected-error {{incorrect argument label in call (have 'bravox:charlie:', expected 'bravo:charlie:')}}
f(alpha: 0, bravox: 3, charlie: 4) // expected-error {{incorrect argument label in call (have 'alpha:bravox:charlie:', expected 'alpha:bravo:charlie:')}}
f(alpha: 0, 1, bravox: 3, charlie: 4) // expected-error {{incorrect argument label in call (have 'alpha:_:bravox:charlie:', expected 'alpha:_:bravo:charlie:')}}
f(alpha: 0, 1, 2, bravox: 3, charlie: 4) // expected-error {{incorrect argument label in call (have 'alpha:_:_:bravox:charlie:', expected 'alpha:_:_:bravo:charlie:')}}
// typo C
f(bravo: 3, charliex: 4) // expected-error {{incorrect argument label in call (have 'bravo:charliex:', expected 'bravo:charlie:')}}
f(alpha: 0, bravo: 3, charliex: 4) // expected-error {{incorrect argument label in call (have 'alpha:bravo:charliex:', expected 'alpha:bravo:charlie:')}}
f(alpha: 0, 1, bravo: 3, charliex: 4) // expected-error {{incorrect argument label in call (have 'alpha:_:bravo:charliex:', expected 'alpha:_:bravo:charlie:')}}
f(alpha: 0, 1, 2, bravo: 3, charliex: 4) // expected-error {{incorrect argument label in call (have 'alpha:_:_:bravo:charliex:', expected 'alpha:_:_:bravo:charlie:')}}
// OoO ACB + typo B
f(alpha: 0, charlie: 3, bravox: 4) // expected-error {{incorrect argument labels in call (have 'alpha:charlie:bravox:', expected 'alpha:bravo:charlie:')}}
f(alpha: 0, 1, charlie: 3, bravox: 4) // expected-error {{incorrect argument labels in call (have 'alpha:_:charlie:bravox:', expected 'alpha:bravo:charlie:')}}
f(alpha: 0, 1, 2, charlie: 3, bravox: 4) // expected-error {{incorrect argument labels in call (have 'alpha:_:_:charlie:bravox:', expected 'alpha:bravo:charlie:')}}
// OoO ACB + typo C
f(charliex: 3, bravo: 4) // expected-error {{incorrect argument labels in call (have 'charliex:bravo:', expected 'alpha:bravo:charlie:')}}
f(alpha: 0, charliex: 3, bravo: 4) // expected-error {{incorrect argument labels in call (have 'alpha:charliex:bravo:', expected 'alpha:bravo:charlie:')}}
f(alpha: 0, 1, charliex: 3, bravo: 4) // expected-error {{incorrect argument labels in call (have 'alpha:_:charliex:bravo:', expected 'alpha:bravo:charlie:')}}
f(alpha: 0, 1, 2, charliex: 3, bravo: 4) // expected-error {{incorrect argument labels in call (have 'alpha:_:_:charliex:bravo:', expected 'alpha:bravo:charlie:')}}
// OoO BAC + typo B
f(bravox: 0, alpha: 1, charlie: 4) // expected-error {{incorrect argument labels in call (have 'bravox:alpha:charlie:', expected 'alpha:bravo:charlie:')}}
f(bravox: 0, alpha: 1, 2, charlie: 4) // expected-error {{incorrect argument labels in call (have 'bravox:alpha:_:charlie:', expected 'alpha:bravo:charlie:')}}
f(bravox: 0, alpha: 1, 2, 3, charlie: 4) // expected-error {{incorrect argument labels in call (have 'bravox:alpha:_:_:charlie:', expected 'alpha:bravo:charlie:')}}
// OoO BAC + typo C
f(bravo: 0, alpha: 1, charliex: 4) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
f(bravo: 0, alpha: 1, 2, charliex: 4) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
f(bravo: 0, alpha: 1, 2, 3, charliex: 4) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
}
}
func var_31849281(_ a: Int, _ b: Int..., c: Int) {}
var_31849281(1, c: 10, 3, 4, 5, 6, 7, 8, 9) // expected-error {{unnamed argument #3 must precede argument 'c'}} {{17-17=3, 4, 5, 6, 7, 8, 9, }} {{22-43=}}
func testLabelErrorVariadic() {
func f(aa: Int, bb: Int, cc: Int...) {}
f(aax: 0, bbx: 1, cc: 2, 3, 4)
// expected-error@-1 {{incorrect argument labels in call (have 'aax:bbx:cc:_:_:', expected 'aa:bb:cc:_:_:')}}
f(aax: 0, bbx: 1)
// expected-error@-1 {{incorrect argument labels in call (have 'aax:bbx:', expected 'aa:bb:')}}
}
// -------------------------------------------
// Positions around defaults and variadics
// -------------------------------------------
struct PositionsAroundDefaultsAndVariadics {
// unlabeled defaulted around labeled parameter
func f1(_ a: Bool = false, _ b: Int = 0, c: String = "", _ d: [Int] = []) {}
func test_f1() {
f1(true, 2, c: "3", [4])
f1(true, c: "3", 2, [4]) // expected-error {{unnamed argument #4 must precede argument 'c'}}
f1(true, c: "3", [4], 2) // expected-error {{unnamed argument #4 must precede argument 'c'}}
f1(true, c: "3", 2) // expected-error {{cannot convert value of type 'Int' to expected argument type '[Int]'}}
f1(true, c: "3", [4])
f1(c: "3", 2, [4]) // expected-error {{unnamed argument #3 must precede argument 'c'}}
f1(c: "3", [4], 2) // expected-error {{unnamed argument #3 must precede argument 'c'}}
f1(c: "3", 2) // expected-error {{cannot convert value of type 'Int' to expected argument type '[Int]'}}
f1(c: "3", [4])
f1(b: "2", [3]) // expected-error {{incorrect argument labels in call (have 'b:_:', expected '_:_:c:_:')}}
// expected-error@-1 {{cannot convert value of type '[Int]' to expected argument type 'Bool'}}
f1(b: "2", 1) // expected-error {{incorrect argument labels in call (have 'b:_:', expected '_:_:c:_:')}}
// expected-error@-1 {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}}
f1(b: "2", [3], 1) // expected-error {{incorrect argument labels in call (have 'b:_:_:', expected '_:_:c:_:')}}
// expected-error@-1 {{cannot convert value of type '[Int]' to expected argument type 'Bool'}}
f1(b: "2", 1, [3]) // expected-error {{incorrect argument labels in call (have 'b:_:_:', expected '_:_:c:_:')}}
// expected-error@-1 {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}}
// expected-error@-2 {{cannot convert value of type '[Int]' to expected argument type 'Int'}}
}
// unlabeled variadics before labeled parameter
func f2(_ a: Bool = false, _ b: Int..., c: String = "", _ d: [Int] = []) {}
func test_f2() {
f2(true, 21, 22, 23, c: "3", [4])
f2(true, "21", 22, 23, c: "3", [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f2(true, 21, "22", 23, c: "3", [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f2(true, 21, 22, "23", c: "3", [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f2(true, 21, 22, c: "3", [4])
f2(true, 21, c: "3", [4])
f2(true, c: "3", [4])
f2(true, c: "3", 21) // expected-error {{cannot convert value of type 'Int' to expected argument type '[Int]'}}
f2(true, c: "3", 21, [4]) // expected-error {{unnamed argument #4 must precede argument 'c'}}
// expected-error@-1 {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
// expected-note@-2 {{remove brackets to pass array elements directly}}
f2(true, c: "3", [4], 21) // expected-error {{unnamed argument #4 must precede argument 'c'}}
f2(true, [4]) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
// expected-note@-1 {{remove brackets to pass array elements directly}}
f2(true, 21, [4]) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
// expected-note@-1 {{remove brackets to pass array elements directly}}
f2(true, 21, 22, [4]) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
// expected-note@-1 {{remove brackets to pass array elements directly}}
f2(21, 22, 23, c: "3", [4]) // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}}
f2(21, 22, c: "3", [4]) // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}}
f2(21, c: "3", [4]) // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}}
f2(c: "3", [4])
f2(c: "3")
f2()
f2(c: "3", 21) // expected-error {{cannot convert value of type 'Int' to expected argument type '[Int]'}}
f2(c: "3", 21, [4]) // expected-error {{incorrect argument labels in call (have 'c:_:_:', expected '_:_:c:_:')}}
// expected-error@-1 {{cannot convert value of type 'Int' to expected argument type '[Int]'}}
// expected-error@-2 {{cannot convert value of type '[Int]' to expected argument type 'Bool'}}
f2(c: "3", [4], 21) // expected-error {{incorrect argument labels in call (have 'c:_:_:', expected '_:_:c:_:')}}
// expected-error@-1 {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}}
f2([4]) // expected-error {{cannot convert value of type '[Int]' to expected argument type 'Bool'}}
f2(21, [4]) // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}}
// expected-error@-1 {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
// expected-note@-2 {{remove brackets to pass array elements directly}}
f2(21, 22, [4]) // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}}
// expected-error@-1 {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
// expected-note@-2 {{remove brackets to pass array elements directly}}
}
// labeled variadics before labeled parameter
func f3(_ a: Bool = false, b: Int..., c: String = "", _ d: [Int] = []) {}
func test_f3() {
f3(true, b: 21, 22, 23, c: "3", [4])
f3(true, b: "21", 22, 23, c: "3", [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f3(true, b: 21, "22", 23, c: "3", [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f3(true, b: 21, 22, "23", c: "3", [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f3(true, b: 21, 22, c: "3", [4])
f3(true, b: 21, c: "3", [4])
f3(true, c: "3", [4])
f3(true, c: "3", b: 21) // expected-error {{argument 'b' must precede argument 'c'}}
f3(true, c: "3", b: 21, [4]) // expected-error {{argument 'b' must precede argument 'c'}}
// expected-error@-1 {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
// expected-note@-2 {{remove brackets to pass array elements directly}}
f3(true, c: "3", [4], b: 21) // expected-error {{argument 'b' must precede argument 'c'}}
f3(true, b: 21, [4]) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
// expected-note@-1 {{remove brackets to pass array elements directly}}
f3(b: 21, 22, 23, c: "3", [4])
f3(b: 21, 22, c: "3", [4])
f3(b: 21, c: "3", [4])
f3(c: "3", [4])
f3([4]) // expected-error {{cannot convert value of type '[Int]' to expected argument type 'Bool'}}
f3()
f3(c: "3", b: 21) // expected-error {{argument 'b' must precede argument 'c'}}
f3(c: "3", b: 21, [4]) // expected-error {{argument 'b' must precede argument 'c'}}
// expected-error@-1 {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
// expected-note@-2 {{remove brackets to pass array elements directly}}
f3(c: "3", [4], b: 21) // expected-error {{argument 'b' must precede argument 'c'}}
}
// unlabeled variadics after labeled parameter
func f4(_ a: Bool = false, b: String = "", _ c: Int..., d: [Int] = []) {}
func test_f4() {
f4(true, b: "2", 31, 32, 33, d: [4])
f4(true, b: "2", "31", 32, 33, d: [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f4(true, b: "2", 31, "32", 33, d: [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f4(true, b: "2", 31, 32, "33", d: [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f4(true, b: "2", 31, 32, d: [4])
f4(true, b: "2", 31, d: [4])
f4(true, b: "2", d: [4])
f4(true, 31, b: "2", d: [4]) // expected-error {{argument 'b' must precede unnamed argument #2}}
f4(true, b: "2", d: [4], 31) // expected-error {{unnamed argument #4 must precede argument 'd'}}
f4(true, b: "2", 31)
f4(true, b: "2")
f4(true)
f4(true, 31)
f4(true, 31, d: [4])
f4(true, 31, 32)
f4(true, 31, 32, d: [4])
f4(b: "2", 31, 32, 33, d: [4])
f4(b: "2", "31", 32, 33, d: [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f4(b: "2", 31, "32", 33, d: [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f4(b: "2", 31, 32, "33", d: [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f4(b: "2", 31, 32, d: [4])
f4(b: "2", 31, d: [4])
f4(b: "2", d: [4])
f4(31, b: "2", d: [4]) // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}}
f4(b: "2", d: [4], 31) // expected-error {{unnamed argument #3 must precede argument 'b'}}
f4(b: "2", 31)
f4(b: "2", 31, 32)
f4(b: "2")
f4()
f4(31) // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}}
f4(31, d: [4]) // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}}
f4(31, 32) // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}}
f4(31, 32, d: [4]) // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}}
}
// labeled variadics after labeled parameter
func f5(_ a: Bool = false, b: String = "", c: Int..., d: [Int] = []) {}
func test_f5() {
f5(true, b: "2", c: 31, 32, 33, d: [4])
f5(true, b: "2", c: "31", 32, 33, d: [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f5(true, b: "2", c: 31, "32", 33, d: [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f5(true, b: "2", c: 31, 32, "33", d: [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f5(true, b: "2", c: 31, 32, d: [4])
f5(true, b: "2", c: 31, d: [4])
f5(true, b: "2", d: [4])
f5(true, c: 31, b: "2", d: [4]) // expected-error {{argument 'b' must precede argument 'c'}}
f5(true, b: "2", d: [4], 31) // expected-error {{incorrect argument labels in call (have '_:b:d:_:', expected '_:b:c:d:')}}
f5(true, b: "2", c: 31)
f5(true, b: "2")
f5(true)
f5(true, c: 31)
f5(true, c: 31, d: [4])
f5(true, c: 31, 32)
f5(true, c: 31, 32, d: [4])
f5(b: "2", c: 31, 32, 33, d: [4])
f5(b: "2", c: "31", 32, 33, d: [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f5(b: "2", c: 31, "32", 33, d: [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f5(b: "2", c: 31, 32, "33", d: [4]) // expected-error {{cannot convert value of type 'String' to expected argument type 'Int'}}
f5(b: "2", c: 31, 32, d: [4])
f5(b: "2", c: 31, d: [4])
f5(b: "2", d: [4])
f5(c: 31, b: "2", d: [4]) // expected-error {{argument 'b' must precede argument 'c'}}
f5(b: "2", d: [4], c: 31) // expected-error {{argument 'c' must precede argument 'd'}}
f5(b: "2", c: 31)
f5(b: "2", c: 31, 32)
f5(b: "2")
f5()
f5(c: 31)
f5(c: 31, d: [4])
f5(c: 31, 32)
f5(c: 31, 32, d: [4])
}
}
// -------------------------------------------
// Matching position of unlabeled parameters
// -------------------------------------------
func testUnlabeledParameterBindingPosition() {
do {
func f(_ aa: Int) {}
f(1) // ok
f(xx: 1)
// expected-error@-1 {{extraneous argument label 'xx:' in call}}
f(0, 1)
// expected-error@-1:10 {{extra argument in call}}
f(xx: 1, 2)
// expected-error@-1:14 {{extra argument in call}}
f(1, xx: 2)
// expected-error@-1:14 {{extra argument 'xx' in call}}
f(xx: 1, yy: 2)
// expected-error@-1:18 {{extra argument 'yy' in call}}
}
do {
func f(aa: Int) { }
f(1)
// expected-error@-1:7 {{missing argument label 'aa:' in call}}
f(aa: 1) // ok
f(xx: 1)
// expected-error@-1 {{incorrect argument label in call (have 'xx:', expected 'aa:')}}
}
do {
func f(_ aa: Int, _ bb: Int) { }
// expected-note@-1 3 {{'f' declared here}}
f(1)
// expected-error@-1:8 {{missing argument for parameter #2 in call}}
f(xx: 1)
// expected-error@-1 {{extraneous argument label 'xx:' in call}}
// expected-error@-2:12 {{missing argument for parameter #2 in call}}
f(1, 2) // ok
f(1, xx: 2)
// expected-error@-1 {{extraneous argument label 'xx:' in call}}
f(xx: 1, 2)
// expected-error@-1 {{extraneous argument label 'xx:' in call}}
f(xx: 1, yy: 2)
// expected-error@-1 {{extraneous argument labels 'xx:yy:' in call}}
f(xx: 1, 2, 3)
// expected-error@-1:17 {{extra argument in call}}
f(1, xx: 2, 3)
// expected-error@-1:17 {{extra argument in call}}
f(1, 2, xx: 3)
// expected-error@-1:17 {{extra argument 'xx' in call}}
f(xx: 1, yy: 2, 3)
// expected-error@-1:21 {{extra argument in call}}
f(xx: 1, yy: 2, 3, 4)
// expected-error@-1:6 {{extra arguments at positions #3, #4 in call}}
}
do {
func f(_ aa: Int = 0, _ bb: Int) { }
// expected-note@-1 {{'f' declared here}}
f(1)
// expected-error@-1:8 {{missing argument for parameter #2 in call}}
f(1, 2) // ok
}
do {
func f(_ aa: Int, bb: Int) { }
// expected-note@-1 3 {{'f(_:bb:)' declared here}}
f(1)
// expected-error@-1:8 {{missing argument for parameter 'bb' in call}}
f(1, 2)
// expected-error@-1 {{missing argument label 'bb:' in call}}
f(1, bb: 2) // ok
f(xx: 1, 2)
// expected-error@-1 {{incorrect argument labels in call (have 'xx:_:', expected '_:bb:')}}
f(xx: 1, bb: 2)
// expected-error@-1 {{extraneous argument label 'xx:' in call}}
f(bb: 1, 2, 3)
// expected-error@-1:17 {{extra argument in call}}
f(1, bb: 2, 3)
// expected-error@-1:17 {{extra argument in call}}
f(1, 2, bb: 3)
// expected-error@-1:10 {{extra argument in call}}
f(xx: 1, 2, 3)
// expected-error@-1:17 {{extra argument in call}}
f(1, xx: 2, 3)
// expected-error@-1:6 {{extra arguments at positions #2, #3 in call}}
// expected-error@-2:8 {{missing argument for parameter 'bb' in call}}
f(1, 2, xx: 3)
// expected-error@-1:17 {{extra argument 'xx' in call}}
}
do {
// expected-note@+1 *{{'f(aa:_:)' declared here}}
func f(aa: Int, _ bb: Int) { }
f(1)
// expected-error@-1:7 {{missing argument for parameter 'aa' in call}}
f(0, 1)
// expected-error@-1:6 {{missing argument label 'aa:' in call}}
f(0, xx: 1)
// expected-error@-1:7 {{missing argument for parameter 'aa' in call}}
// expected-error@-2:14 {{extra argument 'xx' in call}}
f(xx: 0, 1)
// expected-error@-1:7 {{missing argument for parameter 'aa' in call}}
// expected-error@-2:14 {{extra argument in call}}
f(0, 1, 9)
// expected-error@-1:13 {{extra argument in call}}
f(0, 1, xx: 9)
// expected-error@-1:17 {{extra argument 'xx' in call}}
f(xx: 91, 1, 92)
// expected-error@-1:6 {{extra arguments at positions #2, #3 in call}}
// expected-error@-2:7 {{missing argument for parameter 'aa' in call}}
f(1, xx: 2, 3)
// expected-error@-1:6 {{extra arguments at positions #2, #3 in call}}
// expected-error@-2:7 {{missing argument for parameter 'aa' in call}}
f(1, 2, xx: 3)
// expected-error@-1:17 {{extra argument 'xx' in call}}
}
do {
func f(_ aa: Int, _ bb: Int = 82, _ cc: Int) { }
// expected-note@-1 {{'f' declared here}}
f(1, 2)
// expected-error@-1:11 {{missing argument for parameter #3 in call}}
f(1, 2, 3) // ok
}
do {
func f(_ aa: Int, _ bb: Int, cc: Int) { }
f(1, 2, cc: 3) // ok
f(1, 2, xx: 3)
// expected-error@-1 {{incorrect argument label in call (have '_:_:xx:', expected '_:_:cc:')}}
f(1, cc: 2, 3)
// expected-error@-1 {{unnamed argument #3 must precede argument 'cc'}}
f(1, xx: 2, 3)
// expected-error@-1 {{incorrect argument labels in call (have '_:xx:_:', expected '_:_:cc:')}}
f(cc: 1, 2, 3)
// expected-error@-1 {{incorrect argument labels in call (have 'cc:_:_:', expected '_:_:cc:')}}
f(xx: 1, 2, 3)
// expected-error@-1 {{incorrect argument labels in call (have 'xx:_:_:', expected '_:_:cc:')}}
f(xx: 1, yy: 2, 3)
// expected-error@-1 {{incorrect argument labels in call (have 'xx:yy:_:', expected '_:_:cc:')}}
f(xx: 1, 2, yy: 3)
// expected-error@-1 {{incorrect argument labels in call (have 'xx:_:yy:', expected '_:_:cc:')}}
f(1, xx: 2, yy: 3)
// expected-error@-1 {{incorrect argument labels in call (have '_:xx:yy:', expected '_:_:cc:')}}
}
do {
func f(_ aa: Int, bb: Int, _ cc: Int) { }
// expected-note@-1 4 {{'f(_:bb:_:)' declared here}}
f(1)
// expected-error@-1:7 {{missing arguments for parameters 'bb', #3 in call}}
f(1, 2)
// expected-error@-1:8 {{missing argument for parameter 'bb' in call}}
f(1, 2, 3)
// expected-error@-1 {{missing argument label 'bb:' in call}}
f(1, 2, bb: 3)
// expected-error@-1 {{argument 'bb' must precede unnamed argument #2}}
f(1, bb: 2, 3) // ok
f(bb: 1, 0, 2)
// expected-error@-1 {{unnamed argument #3 must precede argument 'bb'}}
f(xx: 1, 2, 3)
// expected-error@-1 {{incorrect argument labels in call (have 'xx:_:_:', expected '_:bb:_:')}}
f(1, xx: 2, 3)
// expected-error@-1:17 {{extra argument in call}}
// expected-error@-2:8 {{missing argument for parameter 'bb' in call}}
f(1, 2, xx: 3)
// expected-error@-1:8 {{missing argument for parameter 'bb' in call}}
// expected-error@-2:17 {{extra argument 'xx' in call}}
}
do {
func f(_ aa: Int = 80, bb: Int, _ cc: Int) {}
f(bb: 1, 2) // ok
}
do {
// expected-note@+1 *{{'f(_:bb:_:)' declared here}}
func f(_ aa: Int, bb: Int, _ cc: Int...) { }
f(bb: 1, 2, 3, 4)
// expected-error@-1:7 {{missing argument for parameter #1 in call}}
}
do {
func f(_ aa: Int, bb: Int = 81, _ cc: Int...) {}
f(0, 2, 3) // ok
}
do {
// expected-note@+1 *{{'f(aa:_:_:)' declared here}}
func f(aa: Int, _ bb: Int, _ cc: Int) {}
f(1)
// expected-error@-1:7 {{missing arguments for parameters 'aa', #3 in call}}
f(0, 1)
// expected-error@-1:7 {{missing argument for parameter 'aa' in call}}
f(1, 2, 3)
// expected-error@-1:6 {{missing argument label 'aa:' in call}}
f(1, aa: 2, 3)
// expected-error@-1:10 {{argument 'aa' must precede unnamed argument #1}}
f(1, xx: 2, 3)
// expected-error@-1:7 {{missing argument for parameter 'aa' in call}}
// expected-error@-2:17 {{extra argument in call}}
f(aa: 1, 2, 3) // ok
f(xx: 1, 2, 3)
// expected-error@-1:7 {{missing argument for parameter 'aa' in call}}
// expected-error@-2:17 {{extra argument in call}}
f(xx: 1, 2, yy: 3)
// expected-error@-1:7 {{missing argument for parameter 'aa' in call}}
// expected-error@-2:21 {{extra argument 'yy' in call}}
f(xx: 1, yy: 2, 3)
// expected-error@-1:7 {{missing argument for parameter 'aa' in call}}
// expected-error@-2:21 {{extra argument in call}}
f(1, xx: 2, yy: 3)
// expected-error@-1:7 {{missing argument for parameter 'aa' in call}}
// expected-error@-2:21 {{extra argument 'yy' in call}}
f(1, 2, 3, 4)
// expected-error@-1:16 {{extra argument in call}}
f(1, aa: 2, 3, 4)
// expected-error@-1:20 {{extra argument in call}}
f(1, aa: 2, 3, xx: 4)
// expected-error@-1:24 {{extra argument 'xx' in call}}
f(1, aa: 2, xx: 3, 4)
// expected-error@-1:24 {{extra argument in call}}
}
do {
// expected-note@+1 *{{'f(aa:_:_:)' declared here}}
func f(aa: Int, _ bb: Int = 81, _ cc: Int) {}
f(0, 1)
// expected-error@-1:7 {{missing argument for parameter 'aa' in call}}
}
do {
// expected-note@+1 *{{'f(aa:bb:_:)' declared here}}
func f(aa: Int, bb: Int, _ cc: Int) {}
f(0, 2)
// expected-error@-1:6 {{missing argument labels 'aa:bb:' in call}}
// expected-error@-2:8 {{missing argument for parameter 'bb' in call}}
f(0, bb: 1, 2)
// expected-error@-1:6 {{missing argument label 'aa:' in call}}
f(xx: 1, 2, 3)
// expected-error@-1:7 {{missing argument for parameter 'aa' in call}}
// expected-error@-2:17 {{extra argument in call}}
f(1, xx: 2, 3)
// expected-error@-1:7 {{missing argument for parameter 'aa' in call}}
// expected-error@-2:17 {{extra argument in call}}
f(1, 2, xx: 3)
// expected-error@-1:8 {{missing argument for parameter 'bb' in call}}
// expected-error@-2:17 {{extra argument 'xx' in call}}
}
do {
func f(aa: Int, bb: Int, cc: Int) { }
f(1, aa: 2, bb: 3)
// expected-error@-1 {{incorrect argument labels in call (have '_:aa:bb:', expected 'aa:bb:cc:')}}
f(1, bb: 2, aa: 3)
// expected-error@-1 {{incorrect argument labels in call (have '_:bb:aa:', expected 'aa:bb:cc:')}}
f(aa: 1, 2, bb: 3)
// expected-error@-1 {{incorrect argument labels in call (have 'aa:_:bb:', expected 'aa:bb:cc:')}}
f(aa: 1, bb: 2, 3)
// expected-error@-1 {{missing argument label 'cc:' in call}}
}
do {
func f(_ aa: Int, _ bb: Int = 81, cc: Int, _ dd: Int) {}
f(0, cc: 2, 3) // ok
}
do {
func f(_ aa: Int, _ bb: Int = 81, cc: Int = 82, _ dd: Int) {}
f(0, cc: 2, 3) // ok
f(cc: 1, 2, 3, 4)
// expected-error@-1 {{unnamed argument #3 must precede argument 'cc'}}
}
do {
func f(_ aa: Int, _ bb: Int, cc: Int, dd: Int) { }
// expected-note@-1 6 {{'f(_:_:cc:dd:)' declared here}}
f(1, xx: 2)
// expected-error@-1 {{extraneous argument label 'xx:' in call}}
// expected-error@-2:6 {{missing arguments for parameters 'cc', 'dd' in call}}
f(xx: 1, 2)
// expected-error@-1:6 {{missing arguments for parameters 'cc', 'dd' in call}}
// expected-error@-2 {{extraneous argument label 'xx:' in call}}
f(1, xx: 2, cc: 3)
// expected-error@-1 {{extraneous argument label 'xx:' in call}}
// expected-error@-2:22 {{missing argument for parameter 'dd' in call}}
f(1, xx: 2, dd: 3)
// expected-error@-1 {{incorrect argument labels in call (have '_:xx:dd:', expected '_:_:cc:dd:')}}
// expected-error@-2:15 {{missing argument for parameter 'cc' in call}}
f(xx: 1, 2, cc: 3)
// expected-error@-1 {{extraneous argument label 'xx:' in call}}
// expected-error@-2:22 {{missing argument for parameter 'dd' in call}}
f(xx: 1, 2, dd: 3)
// expected-error@-1 {{incorrect argument labels in call (have 'xx:_:dd:', expected '_:_:cc:dd:')}}
// expected-error@-2:15 {{missing argument for parameter 'cc' in call}}
f(1, xx: 2, cc: 3, dd: 4)
// expected-error@-1:6 {{extraneous argument label 'xx:' in call}}
f(xx: 1, 2, cc: 3, dd: 4)
// expected-error@-1:6 {{extraneous argument label 'xx:' in call}}
}
do {
func f(_ aa: Int, bb: Int = 82, _ cc: Int, _ dd: Int) { }
f(1, bb: 2, 3, 4) // ok
f(1, 2, bb: 3, 4)
// expected-error@-1 {{argument 'bb' must precede unnamed argument #2}}
}
do {
func f(aa: Int, _ bb: Int, cc: Int, _ dd: Int) { }
// expected-note@-1 3 {{'f(aa:_:cc:_:)' declared here}}
f(1)
// expected-error@-1:7 {{missing arguments for parameters 'aa', 'cc', #4 in call}}
f(1, 2)
// expected-error@-1:6 {{missing arguments for parameters 'aa', 'cc' in call}}
f(1, 2, 3)
// expected-error@-1 {{missing argument labels 'aa:cc:' in call}}
// expected-error@-2:11 {{missing argument for parameter 'cc' in call}}
f(1, 2, 3, 4)
// expected-error@-1:6 {{missing argument labels 'aa:cc:' in call}}
f(1, 2, 3, 4, 5)
// expected-error@-1:19 {{extra argument in call}}
}
do {
func f(aa: Int, bb: Int, _ cc: Int, _ dd: Int) { }
// expected-note@-1 6 {{'f(aa:bb:_:_:)' declared here}}
f(1, xx: 2)
// expected-error@-1:6 {{missing arguments for parameters 'aa', 'bb' in call}}
// expected-error@-2 {{incorrect argument labels in call (have '_:xx:', expected 'aa:bb:_:_:')}}
f(xx: 1, 2)
// expected-error@-1 {{incorrect argument labels in call (have 'xx:_:', expected 'aa:bb:_:_:')}}
// expected-error@-2:6 {{missing arguments for parameters 'aa', 'bb' in call}}
f(bb: 1, 2, xx: 3)
// expected-error@-1:7 {{missing argument for parameter 'aa' in call}}
f(bb: 1, xx: 2, 3)
// expected-error@-1:7 {{missing argument for parameter 'aa' in call}}
f(aa: 1, 2, xx: 3)
// expected-error@-1:12 {{missing argument for parameter 'bb' in call}}
f(aa: 1, xx: 2, 3)
// expected-error@-1 {{incorrect argument label in call (have 'aa:xx:_:', expected 'aa:bb:_:_:')}}
// expected-error@-2:12 {{missing argument for parameter 'bb' in call}}
f(aa: 1, bb: 2, 3, xx: 4)
// expected-error@-1 {{extraneous argument label 'xx:' in call}}
f(aa: 1, bb: 2, xx: 3, 4)
// expected-error@-1 {{extraneous argument label 'xx:' in call}}
}
do {
func f(_ aa: Int, bb: Int, _ cc: Int, dd: Int, _ ee: Int) { }
f(1, bb: 2, 3, 4, dd: 5)
// expected-error@-1:23 {{argument 'dd' must precede unnamed argument #4}}
f(1, dd: 2, 3, 4, bb: 5)
// expected-error@-1 {{incorrect argument labels in call (have '_:dd:_:_:bb:', expected '_:bb:_:dd:_:')}}
f(1, bb: 2, 3, dd: 4, 5) // ok
f(1, dd: 2, 3, bb: 4, 5)
// expected-error@-1 {{incorrect argument labels in call (have '_:dd:_:bb:_:', expected '_:bb:_:dd:_:')}}
f(1, 2, bb: 3, 4, dd: 5, 6)
// expected-error@-1:30 {{extra argument in call}}
f(1, bb: 2, 3, 4, dd: 5, 6)
// expected-error@-1:30 {{extra argument in call}}
f(1, dd: 2, 3, 4, bb: 5, 6)
// expected-error@-1:30 {{extra argument in call}}
}
}
// -------------------------------------------
// Missing arguments
// -------------------------------------------
// FIXME: Diagnostics could be improved with all missing names, or
// simply # of arguments required.
func missingargs1(x: Int, y: Int, z: Int) {} // expected-note {{'missingargs1(x:y:z:)' declared here}}
missingargs1(x: 1, y: 2) // expected-error{{missing argument for parameter 'z' in call}}
func missingargs2(x: Int, y: Int, _ z: Int) {} // expected-note {{'missingargs2(x:y:_:)' declared here}}
missingargs2(x: 1, y: 2) // expected-error{{missing argument for parameter #3 in call}}
// -------------------------------------------
// Extra arguments
// -------------------------------------------
func extraargs1(x: Int) {} // expected-note {{'extraargs1(x:)' declared here}}
extraargs1(x: 1, y: 2) // expected-error{{extra argument 'y' in call}}
extraargs1(x: 1, 2, 3) // expected-error{{extra arguments at positions #2, #3 in call}}
// -------------------------------------------
// Argument name mismatch
// -------------------------------------------
func mismatch1(thisFoo: Int = 0, bar: Int = 0, wibble: Int = 0) { } // expected-note {{'mismatch1(thisFoo:bar:wibble:)' declared here}}
mismatch1(foo: 5) // expected-error {{extra argument 'foo' in call}}
mismatch1(baz: 1, wobble: 2) // expected-error{{incorrect argument labels in call (have 'baz:wobble:', expected 'bar:wibble:')}} {{11-14=bar}} {{19-25=wibble}}
mismatch1(food: 1, zap: 2) // expected-error{{extra arguments at positions #1, #2 in call}}
// <rdar://problem/27891805> QoI: FailureDiagnosis doesn't look through 'try'
struct rdar27891805 {
init(contentsOf: String, encoding: String) throws {}
init(contentsOf: String, usedEncoding: inout String) throws {}
init<T>(_ t: T) {}
}
try rdar27891805(contentsOfURL: nil, usedEncoding: nil)
// expected-error@-1 {{incorrect argument label in call (have 'contentsOfURL:usedEncoding:', expected 'contentsOf:usedEncoding:')}}
// expected-error@-2 {{'nil' is not compatible with expected argument type 'String'}}
// expected-error@-3 {{'nil' is not compatible with expected argument type 'String'}}
// -------------------------------------------
// Out of order and default
// -------------------------------------------
struct OutOfOrderAndDefault {
func f11(alpha: Int, bravo: Int) {}
func f12(alpha: Int = -1, bravo: Int) {}
func f13(alpha: Int, bravo: Int = -1) {}
func f14(alpha: Int = -1, bravo: Int = -1) {}
func test1() {
// typo
f11(bravo: 0, alphax: 1) // expected-error {{incorrect argument labels in call (have 'bravo:alphax:', expected 'alpha:bravo:')}}
f11(bravox: 0, alpha: 1) // expected-error {{incorrect argument labels in call (have 'bravox:alpha:', expected 'alpha:bravo:')}}
f12(bravo: 0, alphax: 1) // expected-error {{incorrect argument labels in call (have 'bravo:alphax:', expected 'alpha:bravo:')}}
f12(bravox: 0, alpha: 1) // expected-error {{incorrect argument labels in call (have 'bravox:alpha:', expected 'alpha:bravo:')}}
f13(bravo: 0, alphax: 1) // expected-error {{incorrect argument labels in call (have 'bravo:alphax:', expected 'alpha:bravo:')}}
f13(bravox: 0, alpha: 1) // expected-error {{incorrect argument labels in call (have 'bravox:alpha:', expected 'alpha:bravo:')}}
f14(bravo: 0, alphax: 1) // expected-error {{incorrect argument labels in call (have 'bravo:alphax:', expected 'alpha:bravo:')}}
f14(bravox: 0, alpha: 1) // expected-error {{incorrect argument labels in call (have 'bravox:alpha:', expected 'alpha:bravo:')}}
}
func f21(alpha: Int, bravo: Int, charlie: Int) {}
func f22(alpha: Int = -1, bravo: Int, charlie: Int) {}
func f23(alpha: Int = -1, bravo: Int = -1, charlie: Int) {}
func test2() {
// BAC
f21(bravo: 0, alphax: 1, charlie: 2) // expected-error {{incorrect argument labels in call (have 'bravo:alphax:charlie:', expected 'alpha:bravo:charlie:')}}
f21(bravox: 0, alpha: 1, charlie: 2) // expected-error {{incorrect argument labels in call (have 'bravox:alpha:charlie:', expected 'alpha:bravo:charlie:')}}
f21(bravo: 0, alpha: 1, charliex: 2) // expected-error {{'alpha' must precede argument 'bravo'}}
f22(bravo: 0, alphax: 1, charlie: 2) // expected-error {{incorrect argument labels in call (have 'bravo:alphax:charlie:', expected 'alpha:bravo:charlie:')}}
f22(bravox: 0, alpha: 1, charlie: 2) // expected-error {{incorrect argument labels in call (have 'bravox:alpha:charlie:', expected 'alpha:bravo:charlie:')}}
f22(bravo: 0, alpha: 1, charliex: 2) // expected-error {{'alpha' must precede argument 'bravo'}}
f23(bravo: 0, alphax: 1, charlie: 2) // expected-error {{incorrect argument labels in call (have 'bravo:alphax:charlie:', expected 'alpha:bravo:charlie:')}}
f23(bravox: 0, alpha: 1, charlie: 2) // expected-error {{incorrect argument labels in call (have 'bravox:alpha:charlie:', expected 'alpha:bravo:charlie:')}}
f23(bravo: 0, alpha: 1, charliex: 2) // expected-error {{'alpha' must precede argument 'bravo'}}
// BCA
f21(bravo: 0, charlie: 1, alphax: 2) // expected-error {{incorrect argument labels in call (have 'bravo:charlie:alphax:', expected 'alpha:bravo:charlie:')}}
f21(bravox: 0, charlie: 1, alpha: 2) // expected-error {{incorrect argument labels in call (have 'bravox:charlie:alpha:', expected 'alpha:bravo:charlie:')}}
f21(bravo: 0, charliex: 1, alpha: 2) // expected-error {{'alpha' must precede argument 'bravo'}}
f22(bravo: 0, charlie: 1, alphax: 2) // expected-error {{incorrect argument labels in call (have 'bravo:charlie:alphax:', expected 'alpha:bravo:charlie:')}}
f22(bravox: 0, charlie: 1, alpha: 2) // expected-error {{incorrect argument labels in call (have 'bravox:charlie:alpha:', expected 'alpha:bravo:charlie:')}}
f22(bravo: 0, charliex: 1, alpha: 2) // expected-error {{'alpha' must precede argument 'bravo'}}
f23(bravo: 0, charlie: 1, alphax: 2) // expected-error {{incorrect argument labels in call (have 'bravo:charlie:alphax:', expected 'alpha:bravo:charlie:')}}
f23(bravox: 0, charlie: 1, alpha: 2) // expected-error {{incorrect argument labels in call (have 'bravox:charlie:alpha:', expected 'alpha:bravo:charlie:')}}
f23(bravo: 0, charliex: 1, alpha: 2) // expected-error {{'alpha' must precede argument 'bravo'}}
// CAB
f21(charlie: 0, alphax: 1, bravo: 2) // expected-error {{incorrect argument labels in call (have 'charlie:alphax:bravo:', expected 'alpha:bravo:charlie:')}}
f21(charlie: 0, alpha: 1, bravox: 2) // expected-error {{incorrect argument labels in call (have 'charlie:alpha:bravox:', expected 'alpha:bravo:charlie:')}}
f21(charliex: 0, alpha: 1, bravo: 2) // expected-error {{incorrect argument labels in call (have 'charliex:alpha:bravo:', expected 'alpha:bravo:charlie:')}}
f22(charlie: 0, alphax: 1, bravo: 2) // expected-error {{incorrect argument labels in call (have 'charlie:alphax:bravo:', expected 'alpha:bravo:charlie:')}}
f22(charlie: 0, alpha: 1, bravox: 2) // expected-error {{incorrect argument labels in call (have 'charlie:alpha:bravox:', expected 'alpha:bravo:charlie:')}}
f22(charliex: 0, alpha: 1, bravo: 2) // expected-error {{incorrect argument labels in call (have 'charliex:alpha:bravo:', expected 'alpha:bravo:charlie:')}}
f23(charlie: 0, alphax: 1, bravo: 2) // expected-error {{incorrect argument labels in call (have 'charlie:alphax:bravo:', expected 'alpha:bravo:charlie:')}}
f23(charlie: 0, alpha: 1, bravox: 2) // expected-error {{argument 'alpha' must precede argument 'charlie'}}
f23(charliex: 0, alpha: 1, bravo: 2) // expected-error {{incorrect argument labels in call (have 'charliex:alpha:bravo:', expected 'alpha:bravo:charlie:')}}
}
func f31(alpha: Int, bravo: Int, charlie: Int, delta: Int) {}
func f32(alpha: Int = -1, bravo: Int = -1, charlie: Int, delta: Int) {}
func f33(alpha: Int = -1, bravo: Int = -1, charlie: Int, delta: Int = -1) {}
func test3() {
// BACD
f31(bravo: 0, alphax: 2, charlie: 2, delta: 3) // expected-error {{incorrect argument labels in call (have 'bravo:alphax:charlie:delta:', expected 'alpha:bravo:charlie:delta:')}}
f31(bravox: 0, alpha: 2, charlie: 2, delta: 3) // expected-error {{incorrect argument labels in call (have 'bravox:alpha:charlie:delta:', expected 'alpha:bravo:charlie:delta:')}}
f31(bravo: 0, alpha: 2, charliex: 2, delta: 3) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
f31(bravo: 0, alpha: 2, charlie: 2, deltax: 3) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
f32(bravo: 0, alphax: 2, charlie: 2, delta: 3) // expected-error {{incorrect argument labels in call (have 'bravo:alphax:charlie:delta:', expected 'alpha:bravo:charlie:delta:')}}
f32(bravox: 0, alpha: 2, charlie: 2, delta: 3) // expected-error {{incorrect argument labels in call (have 'bravox:alpha:charlie:delta:', expected 'alpha:bravo:charlie:delta:')}}
f32(bravo: 0, alpha: 2, charliex: 2, delta: 3) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
f32(bravo: 0, alpha: 2, charlie: 2, deltax: 3) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
f33(bravo: 0, alphax: 2, charlie: 2, delta: 3) // expected-error {{incorrect argument labels in call (have 'bravo:alphax:charlie:delta:', expected 'alpha:bravo:charlie:delta:')}}
f33(bravox: 0, alpha: 2, charlie: 2, delta: 3) // expected-error {{incorrect argument labels in call (have 'bravox:alpha:charlie:delta:', expected 'alpha:bravo:charlie:delta:')}}
f33(bravo: 0, alpha: 2, charliex: 2, delta: 3) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
f33(bravo: 0, alpha: 2, charlie: 2, deltax: 3) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
// BCAD
f31(bravo: 0, charlie: 1, alphax: 2, delta: 3) // expected-error {{incorrect argument labels in call (have 'bravo:charlie:alphax:delta:', expected 'alpha:bravo:charlie:delta:')}}
f31(bravox: 0, charlie: 1, alpha: 2, delta: 3) // expected-error {{incorrect argument labels in call (have 'bravox:charlie:alpha:delta:', expected 'alpha:bravo:charlie:delta:')}}
f31(bravo: 0, charliex: 1, alpha: 2, delta: 3) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
f31(bravo: 0, charlie: 1, alpha: 2, deltax: 3) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
f32(bravo: 0, charlie: 1, alphax: 2, delta: 3) // expected-error {{incorrect argument labels in call (have 'bravo:charlie:alphax:delta:', expected 'alpha:bravo:charlie:delta:')}}
f32(bravox: 0, charlie: 1, alpha: 2, delta: 3) // expected-error {{incorrect argument labels in call (have 'bravox:charlie:alpha:delta:', expected 'alpha:bravo:charlie:delta:')}}
f32(bravo: 0, charliex: 1, alpha: 2, delta: 3) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
f32(bravo: 0, charlie: 1, alpha: 2, deltax: 3) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
f33(bravo: 0, charlie: 1, alphax: 2, delta: 3) // expected-error {{incorrect argument labels in call (have 'bravo:charlie:alphax:delta:', expected 'alpha:bravo:charlie:delta:')}}
f33(bravox: 0, charlie: 1, alpha: 2, delta: 3) // expected-error {{incorrect argument labels in call (have 'bravox:charlie:alpha:delta:', expected 'alpha:bravo:charlie:delta:')}}
f33(bravo: 0, charliex: 1, alpha: 2, delta: 3) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
f33(bravo: 0, charlie: 1, alpha: 2, deltax: 3) // expected-error {{argument 'alpha' must precede argument 'bravo'}}
}
}
// -------------------------------------------
// Subscript keyword arguments
// -------------------------------------------
struct Sub1 {
subscript (i: Int) -> Int {
get { return i }
}
}
var sub1 = Sub1()
var i: Int = 0
i = sub1[i]
i = sub1[i: i] // expected-error{{extraneous argument label 'i:' in subscript}} {{10-13=}}
struct Sub2 {
subscript (d d: Double) -> Double {
get { return d }
}
}
var sub2 = Sub2()
var d: Double = 0.0
d = sub2[d] // expected-error{{missing argument label 'd:' in subscript}} {{10-10=d: }}
d = sub2[d: d]
d = sub2[f: d] // expected-error{{incorrect argument label in subscript (have 'f:', expected 'd:')}} {{10-11=d}}
struct Sub3 {
subscript (a: Int..., b b: Int...) -> Int { 42 }
}
let sub3 = Sub3()
_ = sub3[1, 2, 3, b: 4, 5, 6]
_ = sub3[b: 4, 5, 6]
_ = sub3[1, 2, 3]
_ = sub3[1, c: 4] // expected-error {{incorrect argument label in subscript (have '_:c:', expected '_:b:')}}
struct Sub4 {
subscript (a: Int..., b b: Int = 0, c: Int...) -> Int { 42 }
}
let sub4 = Sub4()
_ = sub4[1, 2, 3, b: 2, 1, 2, 3]
_ = sub4[1, 2, 3, b: 2]
_ = sub4[1, 2, 3]
_ = sub4[]
// -------------------------------------------
// Closures
// -------------------------------------------
func intToInt(_ i: Int) -> Int { return i }
func testClosures() {
let c0 = { (x: Int, y: Int) in x + y }
_ = c0(1, 2)
let c1 = { x, y in intToInt(x + y) }
_ = c1(1, 2)
let c2 = { intToInt($0 + $1) }
_ = c2(1, 2)
}
func acceptAutoclosure(f: @autoclosure () -> Int) { }
func produceInt() -> Int { }
acceptAutoclosure(f: produceInt) // expected-error{{add () to forward @autoclosure parameter}} {{32-32=()}}
// -------------------------------------------
// Trailing closures
// -------------------------------------------
func trailingclosure1(x: Int, f: () -> Int) {}
trailingclosure1(x: 1) { return 5 }
trailingclosure1(1) { return 5 } // expected-error{{missing argument label 'x:' in call}}{{18-18=x: }}
trailingclosure1(x: 1, { return 5 }) // expected-error{{missing argument label 'f:' in call}} {{24-24=f: }}
func trailingclosure2(x: Int, f: (() -> Int)?...) {}
trailingclosure2(x: 5) { return 5 }
func trailingclosure3(x: Int, f: (() -> Int)!) {
var f = f
f = nil
_ = f
}
trailingclosure3(x: 5) { return 5 }
func trailingclosure4(f: () -> Int) {}
trailingclosure4 { 5 }
func trailingClosure5<T>(_ file: String = #file, line: UInt = #line, expression: () -> T?) { }
func trailingClosure6<T>(value: Int, expression: () -> T?) { }
trailingClosure5(file: "hello", line: 17) { // expected-error{{extraneous argument label 'file:' in call}}{{18-24=}}
return Optional.Some(5)
// expected-error@-1 {{enum type 'Optional<Wrapped>' has no case 'Some'; did you mean 'some'?}} {{19-23=some}}
// expected-error@-2 {{generic parameter 'Wrapped' could not be inferred}}
// expected-note@-3 {{explicitly specify the generic arguments to fix this issue}}
}
trailingClosure6(5) { // expected-error{{missing argument label 'value:' in call}}{{18-18=value: }}
return Optional.Some(5)
// expected-error@-1 {{enum type 'Optional<Wrapped>' has no case 'Some'; did you mean 'some'?}} {{19-23=some}}
// expected-error@-2 {{generic parameter 'Wrapped' could not be inferred}}
// expected-note@-3 {{explicitly specify the generic arguments to fix this issue}}
}
class MismatchOverloaded1 {
func method1(_ x: Int!, arg: ((Int) -> Int)!) { }
func method1(_ x: Int!, secondArg: ((Int) -> Int)!) { }
@available(*, unavailable)
func method2(_ x: Int!, arg: ((Int) -> Int)!) { }
func method2(_ x: Int!, secondArg: ((Int) -> Int)!) { }
}
var mismatchOverloaded1 = MismatchOverloaded1()
mismatchOverloaded1.method1(5, arg: nil)
mismatchOverloaded1.method1(5, secondArg: nil)
// Prefer available to unavailable declaration, if it comes up.
mismatchOverloaded1.method2(5) { $0 }
struct RelabelAndTrailingClosure {
func f1(aa: Int, bb: Int, cc: () -> Void = {}) {}
func f2(aa: Int, bb: Int, _ cc: () -> Void = {}) {}
func test() {
f1(aax: 1, bbx: 2) {} // expected-error {{incorrect argument labels in call (have 'aax:bbx:_:', expected 'aa:bb:_:')}} {{8-11=aa}} {{16-19=bb}} {{none}}
f2(aax: 1, bbx: 2) {} // expected-error {{incorrect argument labels in call (have 'aax:bbx:_:', expected 'aa:bb:_:')}} {{8-11=aa}} {{16-19=bb}} {{none}}
f1(aax: 1, bbx: 2) // expected-error {{incorrect argument labels in call (have 'aax:bbx:', expected 'aa:bb:')}} {{8-11=aa}} {{16-19=bb}} {{none}}
f2(aax: 1, bbx: 2) // expected-error {{incorrect argument labels in call (have 'aax:bbx:', expected 'aa:bb:')}} {{8-11=aa}} {{16-19=bb}} {{none}}
}
}
// -------------------------------------------
// Values of function type
// -------------------------------------------
func testValuesOfFunctionType(_ f1: (_: Int, _ arg: Int) -> () ) {
f1(3, arg: 5) // expected-error{{extraneous argument label 'arg:' in call}}{{9-14=}}
f1(x: 3, 5) // expected-error{{extraneous argument label 'x:' in call}} {{6-9=}}
f1(3, 5)
}
// -------------------------------------------
// Literals
// -------------------------------------------
func string_literals1(x: String) { }
string_literals1(x: "hello")
func int_literals1(x: Int) { }
int_literals1(x: 1)
func float_literals1(x: Double) { }
float_literals1(x: 5)
// -------------------------------------------
// Tuples as arguments
// -------------------------------------------
func produceTuple1() -> (Int, Bool) { return (1, true) }
func acceptTuple1<T>(_ x: (T, Bool)) { }
acceptTuple1(produceTuple1())
acceptTuple1((1, false))
acceptTuple1(1, false) // expected-error {{global function 'acceptTuple1' expects a single parameter of type '(T, Bool)' [with T = Int]}} {{14-14=(}} {{22-22=)}}
func acceptTuple2<T>(_ input : T) -> T { return input }
var tuple1 = (1, "hello")
_ = acceptTuple2(tuple1)
_ = acceptTuple2((1, "hello", 3.14159))
func generic_and_missing_label(x: Int) {} // expected-note {{incorrect labels for candidate (have: '(_:)', expected: '(x:)')}}
func generic_and_missing_label<T>(x: T) {} // expected-note {{incorrect labels for candidate (have: '(_:)', expected: '(x:)')}}
generic_and_missing_label(42)
// expected-error@-1 {{no exact matches in call to global function 'generic_and_missing_label'}}
// -------------------------------------------
// Curried functions
// -------------------------------------------
func f7(_ a: Int) -> (_ b: Int) -> Int {
return { b in a+b }
}
_ = f7(1)(1)
f7(1.0)(2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f7(1)(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f7(1)(b: 1.0) // expected-error{{extraneous argument label 'b:' in call}}
// expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Int'}}
let f10 = f7(2)
_ = f10(1)
f10(10) // expected-warning {{result of call to function returning 'Int' is unused}}
f10(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f10(b: 1.0) // expected-error {{extraneous argument label 'b:' in call}}
// expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Int'}}
class CurriedClass {
func method1() {}
func method2(_ a: Int) -> (_ b : Int) -> () { return { b in () } }
func method3(_ a: Int, b : Int) {} // expected-note 3 {{'method3(_:b:)' declared here}}
}
let c = CurriedClass()
_ = c.method1
c.method1(1) // expected-error {{argument passed to call that takes no arguments}}
_ = c.method2(1)
_ = c.method2(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1)(2)
c.method2(1)(c: 2) // expected-error {{extraneous argument label 'c:' in call}}
c.method2(1)(c: 2.0) // expected-error {{extraneous argument label 'c:' in call}}
// expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1)(2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1.0)(2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1.0)(2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
// expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method1(c)()
_ = CurriedClass.method1(c)
CurriedClass.method1(c)(1) // expected-error {{argument passed to call that takes no arguments}}
CurriedClass.method1(2.0)(1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'CurriedClass'}}
// expected-error@-1:27 {{argument passed to call that takes no arguments}}
CurriedClass.method2(c)(32)(b: 1) // expected-error{{extraneous argument label 'b:' in call}}
_ = CurriedClass.method2(c)
_ = CurriedClass.method2(c)(32)
_ = CurriedClass.method2(1,2) // expected-error {{extra argument in call}}
// expected-error@-1 {{instance member 'method2' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
CurriedClass.method2(c)(1.0)(b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
// expected-error@-1 {{extraneous argument label 'b:' in call}}
CurriedClass.method2(c)(1)(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method2(c)(2)(c: 1.0) // expected-error {{extraneous argument label 'c:'}}
// expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method3(c)(32, b: 1)
_ = CurriedClass.method3(c)
_ = CurriedClass.method3(c)(1, 2) // expected-error {{missing argument label 'b:' in call}} {{32-32=b: }}
_ = CurriedClass.method3(c)(1, b: 2)(32) // expected-error {{cannot call value of non-function type '()'}}
_ = CurriedClass.method3(1, 2) // expected-error {{instance member 'method3' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
// expected-error@-1 {{missing argument label 'b:' in call}}
CurriedClass.method3(c)(1.0, b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method3(c)(1) // expected-error {{missing argument for parameter 'b' in call}}
CurriedClass.method3(c)(c: 1.0) // expected-error {{incorrect argument labels in call (have 'c:', expected '_:b:')}}
// expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Int'}}
// expected-error@-2 {{missing argument for parameter #1 in call}}
extension CurriedClass {
func f() {
method3(1, b: 2)
method3() // expected-error {{missing arguments for parameters #1, 'b' in call}} {{13-13=<#Int#>, b: <#Int#>}}
method3(42) // expected-error {{missing argument for parameter 'b' in call}}
method3(self)
// expected-error@-1:13 {{cannot convert value of type 'CurriedClass' to expected argument type 'Int'}}
// expected-error@-2:17 {{missing argument for parameter 'b' in call}} {{17-17=, b: <#Int#>}}
}
}
extension CurriedClass {
func m1(_ a : Int, b : Int) {}
func m2(_ a : Int) {}
}
// <rdar://problem/23718816> QoI: "Extra argument" error when accidentally currying a method
CurriedClass.m1(2, b: 42) // expected-error {{instance member 'm1' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
// <rdar://problem/22108559> QoI: Confusing error message when calling an instance method as a class method
CurriedClass.m2(12) // expected-error {{instance member 'm2' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
// -------------------------------------------
// Multiple label errors
// -------------------------------------------
func testLabelErrorsBasic() {
func f(_ aa: Int, _ bb: Int, cc: Int, dd: Int, ee: Int, ff: Int) {}
// 1 wrong
f(0, 1, ccx: 2, dd: 3, ee: 4, ff: 5)
// expected-error@-1 {{incorrect argument label in call (have '_:_:ccx:dd:ee:ff:', expected '_:_:cc:dd:ee:ff:')}} {{11-14=cc}} {{none}}
// 1 missing
f(0, 1, 2, dd: 3, ee: 4, ff: 5)
// expected-error@-1 {{missing argument label 'cc:' in call}} {{11-11=cc: }} {{none}}
// 1 extra
f(aa: 0, 1, cc: 2, dd: 3, ee: 4, ff: 5)
// expected-error@-1 {{extraneous argument label 'aa:' in call}} {{5-9=}} {{none}}
// 1 ooo
f(0, 1, dd: 3, cc: 2, ee: 4, ff: 5)
// expected-error@-1 {{argument 'cc' must precede argument 'dd'}} {{16-23=}} {{11-11=cc: 2, }} {{none}}
// 2 wrong
f(0, 1, ccx: 2, ddx: 3, ee: 4, ff: 5)
// expected-error@-1 {{incorrect argument labels in call (have '_:_:ccx:ddx:ee:ff:', expected '_:_:cc:dd:ee:ff:')}} {{11-14=cc}} {{19-22=dd}} {{none}}
// 2 missing
f(0, 1, 2, 3, ee: 4, ff: 5)
// expected-error@-1 {{missing argument labels 'cc:dd:' in call}} {{11-11=cc: }} {{14-14=dd: }} {{none}}
// 2 extra
f(aa: 0, bb: 1, cc: 2, dd: 3, ee: 4, ff: 5)
// expected-error@-1 {{extraneous argument labels 'aa:bb:' in call}} {{5-9=}} {{12-16=}} {{none}}
// 2 ooo
f(0, 1, dd: 3, cc: 2, ff: 5, ee: 4)
// expected-error@-1 {{argument 'cc' must precede argument 'dd'}} {{16-23=}} {{11-11=cc: 2, }} {{none}}
// 1 wrong + 1 missing
f(0, 1, ccx: 2, 3, ee: 4, ff: 5)
// expected-error@-1 {{incorrect argument labels in call (have '_:_:ccx:_:ee:ff:', expected '_:_:cc:dd:ee:ff:')}} {{11-14=cc}} {{19-19=dd: }} {{none}}
// 1 wrong + 1 extra
f(aa: 0, 1, ccx: 2, dd: 3, ee: 4, ff: 5)
// expected-error@-1 {{incorrect argument labels in call (have 'aa:_:ccx:dd:ee:ff:', expected '_:_:cc:dd:ee:ff:')}} {{5-9=}} {{15-18=cc}} {{none}}
// 1 wrong + 1 ooo
f(0, 1, ccx: 2, dd: 3, ff: 5, ee: 4)
// expected-error@-1 {{incorrect argument labels in call (have '_:_:ccx:dd:ff:ee:', expected '_:_:cc:dd:ee:ff:')}} {{11-14=cc}} {{26-28=ee}} {{33-35=ff}} {{none}}
}
struct DiagnoseAllLabels {
func f(aa: Int, bb: Int, cc: Int..., dd: Int, ee: Int = 0, ff: Int = 0) {}
func test() {
f(aax: 0, bbx: 1, cc: 21, 22, 23, dd: 3, ff: 5) // expected-error {{incorrect argument labels in call (have 'aax:bbx:cc:_:_:dd:ff:', expected 'aa:bb:cc:_:_:dd:ff:')}} {{7-10=aa}} {{15-18=bb}} {{none}}
f(aax: 0, bbx: 1, dd: 3, ff: 5) // expected-error {{incorrect argument labels in call (have 'aax:bbx:dd:ff:', expected 'aa:bb:dd:ff:')}} {{7-10=aa}} {{15-18=bb}} {{none}}
}
}
// SR-13135: Type inference regression in Swift 5.3 - can't infer a type of @autoclosure result.
func sr13135() {
struct Foo {
var bar: [Int] = []
}
let baz: Int? = nil
func foo<T: Equatable>(
_ a: @autoclosure () throws -> T,
_ b: @autoclosure () throws -> T
) {}
foo(Foo().bar, [baz])
}
// SR-13240
func twoargs(_ x: String, _ y: String) {}
func test() {
let x = 1
twoargs(x, x) // expected-error 2 {{cannot convert value of type 'Int' to expected argument type 'String'}}
}
infix operator ---
func --- (_ lhs: String, _ rhs: String) -> Bool { true }
let x = 1
x --- x // expected-error 2 {{cannot convert value of type 'Int' to expected argument type 'String'}}
| apache-2.0 | c84a7d0eb138058b6ef0e6fc8e21b704 | 43.006297 | 204 | 0.595611 | 3.030431 | false | false | false | false |
chenchangqing/travelMapMvvm | travelMapMvvm/travelMapMvvm/Views/Controllers/ModifyUInfoViewController/ModifyUInfoViewController+ImagePicker.swift | 1 | 2136 | //
// ModifyUInfoViewController+ImagePicker.swift
// travelMapMvvm
//
// Created by green on 15/9/9.
// Copyright (c) 2015年 travelMapMvvm. All rights reserved.
//
import Foundation
extension ModifyUInfoViewController : UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
let selectedImage = info[UIImagePickerControllerEditedImage] as! UIImage
let compressedImage = PhotoHelper.compressImage(selectedImage)
// 上传头像
self.modifyUInfoViewModel.uploadHeadImageCommand.execute(compressedImage)
self.imagePickerVC.dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
self.imagePickerVC.dismissViewControllerAnimated(true, completion: nil)
}
// MARK: - imagePicker
/**
* 图片选择器设置
*/
func setupImagePickerVC() {
imagePickerVC = UIImagePickerController()
imagePickerVC.allowsEditing = true
imagePickerVC.delegate = self
}
/**
* 打开相册
*/
func openPhotoLibrary() {
if !PhotoHelper.isCanVisitPhotos(self) { return }
self.imagePickerVC.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
self.presentViewController(self.imagePickerVC, animated: true, completion: {})
}
}
/**
* 打开相机
*/
func openCamera() {
if !PhotoHelper.isCanVisitCamera(self) { return }
self.imagePickerVC.sourceType = UIImagePickerControllerSourceType.Camera
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) {
self.presentViewController(self.imagePickerVC, animated: true, completion: {})
}
}
} | apache-2.0 | 19e52a9e0e2e4691069ab800e6696e19 | 29.838235 | 125 | 0.67271 | 5.83844 | false | false | false | false |
honghaoz/CrackingTheCodingInterview | Swift/LeetCode/Linked List/203_Remove Linked List Elements.swift | 1 | 810 | // 203_Remove Linked List Elements
// https://leetcode.com/problems/remove-linked-list-elements/
//
// Created by Honghao Zhang on 9/7/19.
// Copyright © 2019 Honghaoz. All rights reserved.
//
// Description:
// Remove all elements from a linked list of integers that have value val.
//
//Example:
//
//Input: 1->2->6->3->4->5->6, val = 6
//Output: 1->2->3->4->5
//
import Foundation
class Num203 {
func removeElements(_ head: ListNode?, _ val: Int) -> ListNode? {
let root: ListNode? = ListNode(0)
root?.next = head
var prev = root
var current = head
while current != nil {
if current?.val == val {
prev?.next = current?.next
current = current?.next
continue
}
prev = current
current = current?.next
}
return root?.next
}
}
| mit | f007257c585efbd9ab180c6c20d6d074 | 21.472222 | 74 | 0.609394 | 3.563877 | false | false | false | false |
PlutoMa/EmployeeCard | EmployeeCard/EmployeeCard/Core/RecordVC/RecordVC.swift | 1 | 3185 | //
// RecordVC.swift
// EmployeeCard
//
// Created by PlutoMa on 2017/4/7.
// Copyright © 2017年 PlutoMa. All rights reserved.
//
import UIKit
class RecordVC: UIViewController {
@IBOutlet weak var tableView: UITableView!
var currentPage: Int = 0
let pageCount: Int = 10
var recordArr = [String]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView()
tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(loadData(hud:)))
loadData(hud: true)
}
func loadData(hud: Bool) -> Void {
currentPage = currentPage + 1
var mbhud: MBProgressHUD?
if hud == true {
mbhud = MBProgressHUD.showAdded(to: view, animated: true)
}
let param = ["page" : currentPage,
"count" : pageCount,
"empId" : (AppDelegate.getAppDelegate().currentEm?.userId) ?? ""] as [String : Any]
NetUtil.post(url: recordInfoUrl,
param: param,
success: { (data) in
let dataDic = data as! [String : Any]
if let result = dataDic["result"] as? String, result == "0" {
mbhud?.hide(true)
let his = dataDic["his"] as! [String]
if his.count == 0 {
self.tableView.mj_footer.endRefreshingWithNoMoreData()
} else {
self.recordArr.append(contentsOf: his)
self.tableView.mj_footer.endRefreshing()
self.tableView.reloadData()
}
} else {
mbhud?.mode = .text
mbhud?.labelText = (dataDic["errmsg"] as? String) ?? ""
mbhud?.hide(true, afterDelay: 2)
}
},
failure: { (error) in
mbhud?.mode = .text
mbhud?.labelText = "网络出错"
mbhud?.hide(true, afterDelay: 2)
})
}
@IBAction func backAction(_ sender: Any) {
_ = navigationController?.popViewController(animated: true)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
extension RecordVC: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return recordArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "RecordTableCell") as! RecordTableCell
let record = recordArr[indexPath.row]
cell.recordLabel.text = record
return cell
}
}
| mit | 64e541251ef78e80fd88ede2ced2c763 | 34.662921 | 124 | 0.52615 | 5.186275 | false | false | false | false |
Darshanptl7500/GPlaceAPI-Swift | GPlaceAPI/GPTextSearchResponse.swift | 1 | 3680 | //
// GPTextSearchResponse.swift
// GPlaceAPI-Swift
//
// Created by Darshan Patel on 7/24/15.
// Copyright (c) 2015 Darshan Patel. All rights reserved.
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Darshan Patel
//
// 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 CoreLocation
import Alamofire
class GPTextSearchResponse {
var html_attributions: String?
var next_page_token: String?
var error_message: String?
var results: [GPResult]!
var status: GPRequestStatus!
init(attributes: Dictionary<String, AnyObject>)
{
if let tmHtml_attributions = attributes["html_attributions"] as? String
{
self.html_attributions = tmHtml_attributions;
}
if let tmNext_page_token = attributes["next_page_token"] as? String
{
self.next_page_token = tmNext_page_token;
}
if let tmError_message = attributes["error_message"] as? String
{
self.error_message = tmError_message;
}
if let tmStatus = attributes["status"] as? String
{
self.status = self.requestStatus(tmStatus);
}
self.results = self.results(attributes)
}
private func results(info: Dictionary<String, AnyObject>) -> [GPResult]
{
let list = info["results"] as! [AnyObject]
var muList = [GPResult]();
for tempList in list
{
var dic = tempList as! Dictionary<String, AnyObject>
var result = GPResult(attributes: dic)
muList.append(result)
}
return muList
}
func requestStatus(string: String) -> GPRequestStatus
{
if string == GPRequestStatus.GPRequestStatusOK.rawValue
{
return .GPRequestStatusOK
}else if string == GPRequestStatus.GPRequestStatusZERORESULTS.rawValue
{
return .GPRequestStatusZERORESULTS
}
else if string == GPRequestStatus.GPRequestStatusOVERQUERYLIMIT.rawValue
{
return .GPRequestStatusOVERQUERYLIMIT
}
else if string == GPRequestStatus.GPRequestStatusREQUESTDENIED.rawValue
{
return .GPRequestStatusREQUESTDENIED
}
else if string == GPRequestStatus.GPRequestStatusINVALIDREQUEST.rawValue
{
return .GPRequestStatusINVALIDREQUEST
}
return .GPRequestStatusOK
}
} | mit | ecb8b64f2ebfdb520c6f54653c0b1dcb | 29.675 | 81 | 0.626902 | 4.681934 | false | false | false | false |
Quick/Nimble | Sources/Nimble/Matchers/Equal.swift | 2 | 8409 | internal func equal<T>(
_ expectedValue: T?,
by areEquivalent: @escaping (T, T) -> Bool
) -> Predicate<T> {
Predicate.define("equal <\(stringify(expectedValue))>") { actualExpression, msg in
let actualValue = try actualExpression.evaluate()
switch (expectedValue, actualValue) {
case (nil, _?):
return PredicateResult(status: .fail, message: msg.appendedBeNilHint())
case (_, nil):
return PredicateResult(status: .fail, message: msg)
case (let expected?, let actual?):
let matches = areEquivalent(expected, actual)
return PredicateResult(bool: matches, message: msg)
}
}
}
/// A Nimble matcher that succeeds when the actual value is equal to the expected value.
/// Values can support equal by supporting the Equatable protocol.
///
/// @see beCloseTo if you want to match imprecise types (eg - floats, doubles).
public func equal<T: Equatable>(_ expectedValue: T) -> Predicate<T> {
equal(expectedValue as T?)
}
/// A Nimble matcher allowing comparison of collection with optional type
public func equal<T: Equatable>(_ expectedValue: [T?]) -> Predicate<[T?]> {
Predicate.define("equal <\(stringify(expectedValue))>") { actualExpression, msg in
guard let actualValue = try actualExpression.evaluate() else {
return PredicateResult(
status: .fail,
message: msg.appendedBeNilHint()
)
}
let matches = expectedValue == actualValue
return PredicateResult(bool: matches, message: msg)
}
}
/// A Nimble matcher that succeeds when the actual value is equal to the expected value.
/// Values can support equal by supporting the Equatable protocol.
///
/// @see beCloseTo if you want to match imprecise types (eg - floats, doubles).
public func equal<T: Equatable>(_ expectedValue: T?) -> Predicate<T> {
equal(expectedValue, by: ==)
}
/// A Nimble matcher that succeeds when the actual set is equal to the expected set.
public func equal<T>(_ expectedValue: Set<T>) -> Predicate<Set<T>> {
equal(expectedValue as Set<T>?)
}
/// A Nimble matcher that succeeds when the actual set is equal to the expected set.
public func equal<T>(_ expectedValue: Set<T>?) -> Predicate<Set<T>> {
equal(expectedValue, stringify: { stringify($0) })
}
/// A Nimble matcher that succeeds when the actual set is equal to the expected set.
public func equal<T: Comparable>(_ expectedValue: Set<T>) -> Predicate<Set<T>> {
equal(expectedValue as Set<T>?)
}
/// A Nimble matcher that succeeds when the actual set is equal to the expected set.
public func equal<T: Comparable>(_ expectedValue: Set<T>?) -> Predicate<Set<T>> {
equal(expectedValue, stringify: { set in
stringify(set.map { Array($0).sorted(by: <) })
})
}
private func equal<T>(_ expectedValue: Set<T>?, stringify: @escaping (Set<T>?) -> String) -> Predicate<Set<T>> {
Predicate { actualExpression in
var errorMessage: ExpectationMessage =
.expectedActualValueTo("equal <\(stringify(expectedValue))>")
guard let expectedValue = expectedValue else {
return PredicateResult(
status: .fail,
message: errorMessage.appendedBeNilHint()
)
}
guard let actualValue = try actualExpression.evaluate() else {
return PredicateResult(
status: .fail,
message: errorMessage.appendedBeNilHint()
)
}
errorMessage = .expectedCustomValueTo(
"equal <\(stringify(expectedValue))>",
actual: "<\(stringify(actualValue))>"
)
if expectedValue == actualValue {
return PredicateResult(
status: .matches,
message: errorMessage
)
}
let missing = expectedValue.subtracting(actualValue)
if missing.count > 0 {
errorMessage = errorMessage.appended(message: ", missing <\(stringify(missing))>")
}
let extra = actualValue.subtracting(expectedValue)
if extra.count > 0 {
errorMessage = errorMessage.appended(message: ", extra <\(stringify(extra))>")
}
return PredicateResult(
status: .doesNotMatch,
message: errorMessage
)
}
}
/// A Nimble matcher that succeeds when the actual dictionary is equal to the expected dictionary
public func equal<K: Hashable, V: Equatable>(_ expectedValue: [K: V?]) -> Predicate<[K: V]> {
Predicate.define("equal <\(stringify(expectedValue))>") { actualExpression, msg in
guard let actualValue = try actualExpression.evaluate() else {
return PredicateResult(
status: .fail,
message: msg.appendedBeNilHint()
)
}
let matches = expectedValue == actualValue
return PredicateResult(bool: matches, message: msg)
}
}
public func ==<T: Equatable>(lhs: SyncExpectation<T>, rhs: T) {
lhs.to(equal(rhs))
}
public func ==<T: Equatable>(lhs: SyncExpectation<T>, rhs: T?) {
lhs.to(equal(rhs))
}
public func !=<T: Equatable>(lhs: SyncExpectation<T>, rhs: T) {
lhs.toNot(equal(rhs))
}
public func !=<T: Equatable>(lhs: SyncExpectation<T>, rhs: T?) {
lhs.toNot(equal(rhs))
}
public func ==<T: Equatable>(lhs: SyncExpectation<[T]>, rhs: [T]?) {
lhs.to(equal(rhs))
}
public func !=<T: Equatable>(lhs: SyncExpectation<[T]>, rhs: [T]?) {
lhs.toNot(equal(rhs))
}
public func == <T>(lhs: SyncExpectation<Set<T>>, rhs: Set<T>) {
lhs.to(equal(rhs))
}
public func == <T>(lhs: SyncExpectation<Set<T>>, rhs: Set<T>?) {
lhs.to(equal(rhs))
}
public func != <T>(lhs: SyncExpectation<Set<T>>, rhs: Set<T>) {
lhs.toNot(equal(rhs))
}
public func != <T>(lhs: SyncExpectation<Set<T>>, rhs: Set<T>?) {
lhs.toNot(equal(rhs))
}
public func ==<T: Comparable>(lhs: SyncExpectation<Set<T>>, rhs: Set<T>) {
lhs.to(equal(rhs))
}
public func ==<T: Comparable>(lhs: SyncExpectation<Set<T>>, rhs: Set<T>?) {
lhs.to(equal(rhs))
}
public func !=<T: Comparable>(lhs: SyncExpectation<Set<T>>, rhs: Set<T>) {
lhs.toNot(equal(rhs))
}
public func !=<T: Comparable>(lhs: SyncExpectation<Set<T>>, rhs: Set<T>?) {
lhs.toNot(equal(rhs))
}
public func ==<T, C: Equatable>(lhs: SyncExpectation<[T: C]>, rhs: [T: C]?) {
lhs.to(equal(rhs))
}
public func !=<T, C: Equatable>(lhs: SyncExpectation<[T: C]>, rhs: [T: C]?) {
lhs.toNot(equal(rhs))
}
public func ==<T: Equatable>(lhs: AsyncExpectation<T>, rhs: T) {
lhs.to(equal(rhs))
}
public func ==<T: Equatable>(lhs: AsyncExpectation<T>, rhs: T?) {
lhs.to(equal(rhs))
}
public func !=<T: Equatable>(lhs: AsyncExpectation<T>, rhs: T) {
lhs.toNot(equal(rhs))
}
public func !=<T: Equatable>(lhs: AsyncExpectation<T>, rhs: T?) {
lhs.toNot(equal(rhs))
}
public func ==<T: Equatable>(lhs: AsyncExpectation<[T]>, rhs: [T]?) {
lhs.to(equal(rhs))
}
public func !=<T: Equatable>(lhs: AsyncExpectation<[T]>, rhs: [T]?) {
lhs.toNot(equal(rhs))
}
public func == <T>(lhs: AsyncExpectation<Set<T>>, rhs: Set<T>) {
lhs.to(equal(rhs))
}
public func == <T>(lhs: AsyncExpectation<Set<T>>, rhs: Set<T>?) {
lhs.to(equal(rhs))
}
public func != <T>(lhs: AsyncExpectation<Set<T>>, rhs: Set<T>) {
lhs.toNot(equal(rhs))
}
public func != <T>(lhs: AsyncExpectation<Set<T>>, rhs: Set<T>?) {
lhs.toNot(equal(rhs))
}
public func ==<T: Comparable>(lhs: AsyncExpectation<Set<T>>, rhs: Set<T>) {
lhs.to(equal(rhs))
}
public func ==<T: Comparable>(lhs: AsyncExpectation<Set<T>>, rhs: Set<T>?) {
lhs.to(equal(rhs))
}
public func !=<T: Comparable>(lhs: AsyncExpectation<Set<T>>, rhs: Set<T>) {
lhs.toNot(equal(rhs))
}
public func !=<T: Comparable>(lhs: AsyncExpectation<Set<T>>, rhs: Set<T>?) {
lhs.toNot(equal(rhs))
}
public func ==<T, C: Equatable>(lhs: AsyncExpectation<[T: C]>, rhs: [T: C]?) {
lhs.to(equal(rhs))
}
public func !=<T, C: Equatable>(lhs: AsyncExpectation<[T: C]>, rhs: [T: C]?) {
lhs.toNot(equal(rhs))
}
#if canImport(Darwin)
import class Foundation.NSObject
extension NMBPredicate {
@objc public class func equalMatcher(_ expected: NSObject) -> NMBPredicate {
NMBPredicate { actualExpression in
try equal(expected).satisfies(actualExpression).toObjectiveC()
}
}
}
#endif
| apache-2.0 | b5a546388ae3b755c9313b67c26e6f31 | 29.915441 | 112 | 0.623974 | 3.820536 | false | false | false | false |
Xinext/RemainderCalc | src/RemainderCalc/ModelMgr.swift | 1 | 5215 | //
// ModelMgr.swift
// RemainderCalc
//
import Foundation
import CoreData
import UIKit
/**
モデルマネージャークラス
*/
class ModelMgr {
// MARK: - Const of attribute name
static public let CNS_M_I_ANSWER = "m_i_answer"
static public let CNS_M_I_DECIMAL_POSITION = "m_i_decimal_position"
static public let CNS_M_I_DIVIDEND = "m_i_dividend"
static public let CNS_M_I_DIVISOR = "m_i_divisor"
static public let CNS_M_I_EXPRESSION = "m_i_expression"
static public let CNS_M_K_UPDATE_TIME = "m_k_update_time"
// MARK: - Static function
/**
履歴データの保存
- parameter setModel: (D_History)-> Void データセット用クロージャー
*/
static func Save_D_History( setModel: ((D_History)-> Void) ) {
// コンテキストの取得
let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate
let context:NSManagedObjectContext = appDelegate.persistentContainer.viewContext
// モデルの作成
let model = D_History(context:context)
setModel(model) // クロージャー内でデータをセット
// 保存
do{
try context.save()
}catch{
print(error)
}
}
/**
履歴データの読出し
- parameter (AnyObject)-> Void データ取得用クロージャー
*/
static func Load_D_History(getModels: ((D_History)-> Void)) {
// コンテキストの取得
let appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
// クエリーの生成
let request: NSFetchRequest<D_History> = D_History.fetchRequest()
let sortDescripter = NSSortDescriptor(key: self.CNS_M_K_UPDATE_TIME, ascending: false) // 日付の降順で取り出す
request.sortDescriptors = [sortDescripter]
// データの取得
do {
let fetchResults = try context.fetch(request) as Array<D_History>
for result: D_History in fetchResults {
getModels(result) // クロージャー内でデータを取得
}
} catch {
print(error)
}
}
/**
履歴データの読出し
- returns: データ配列
*/
static func Load_D_History() -> Array<D_History> {
var resArray = Array<D_History>()
// コンテキストの取得
let appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
// クエリーの生成
let request: NSFetchRequest<D_History> = D_History.fetchRequest()
let sortDescripter = NSSortDescriptor(key: self.CNS_M_K_UPDATE_TIME, ascending: false) // 日付の降順で取り出す
request.sortDescriptors = [sortDescripter]
// データの取得
do {
resArray = try context.fetch(request) as Array<D_History>
} catch {
resArray.removeAll()
print(error)
}
return resArray
}
/**
データ件数の取得
- returns: データ件数
*/
static func GetCount_D_History() -> Int {
var result: Int = 0
// コンテキストの取得
let appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
// クエリーの生成
let request: NSFetchRequest<D_History> = D_History.fetchRequest()
// データ件数の取得
do {
let fetchResults = try context.fetch(request)
result = fetchResults.count
} catch {
result = 0
}
return result
}
/**
指定された件数より後を削除(保存時間の降順)
- parameter top: 残す件数 (0は全削除)
*/
static func DeleteDataWithOffset(offset: Int) {
// コンテキストの取得
let appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
// クエリーの生成
let request: NSFetchRequest<D_History> = D_History.fetchRequest()
let sortDescripter = NSSortDescriptor(key: self.CNS_M_K_UPDATE_TIME, ascending: false) // 日付の降順で取り出す
request.sortDescriptors = [sortDescripter]
request.fetchOffset = offset
request.sortDescriptors = [sortDescripter]
// データの取得
let fetchData = try! context.fetch(request) as Array<D_History>
if(!fetchData.isEmpty){
for i in 0..<fetchData.count{
let deleteObject = fetchData[i] as D_History
context.delete(deleteObject)
}
do{
try context.save()
}catch{
print(error)
}
}
}
}
| mit | 0c25c49b22c2f47669ed565d9e9e6d28 | 27.420732 | 109 | 0.574126 | 4.070742 | false | false | false | false |
wunshine/FoodStyle | FoodStyle/FoodStyle/Classes/Viewcontroller/MineViewController.swift | 1 | 10121 | //
// MineViewController.swift
// FoodStyle
//
// Created by Woz Wong on 16/3/6.
// Copyright © 2016年 code4Fun. All rights reserved.
//
import UIKit
import SnapKit
class MineViewController: UIViewController {
let ID = "cell"
var tableViewConstraint:Constraint?
var originOffset :CGFloat = 0
lazy var refresh : UIRefreshControl = {
var refresh = UIRefreshControl(frame: CGRectMake(0,0,30,30))
return refresh
}()
lazy var toolView:UIView = {
var tool = UIView()
tool.backgroundColor = UIColor.yellowColor()
return tool
}()
lazy var backImage:UIImageView = {
let back = UIImageView(image: UIImage(named: "lol"))
return back
}()
lazy var containView:UIView = {
var view = UIView()
let tap = UITapGestureRecognizer(target: self, action: "tapBackImage")
view.addGestureRecognizer(tap)
view.userInteractionEnabled = true
view.backgroundColor = UIColor.clearColor()
view.addSubview(self.icon)
view.addSubview(self.nameLabel)
view.addSubview(self.timeLabel)
view.addSubview(self.scoreLabel)
return view
}()
lazy var icon : UIButton = {
let image = UIImage(named: "captcha_refresh_hl")
let conerImage = image!.imageWithCorner()
var icon = UIButton()
icon.addTarget(self, action: "iconClick", forControlEvents: .TouchUpInside)
icon.setImage(conerImage, forState: UIControlState.Normal)
return icon
}()
lazy var nameLabel : UILabel = {
var name = UILabel()
name.sizeToFit()
name.text = "AssKicking"
name.textColor = UIColor.whiteColor()
return name
}()
lazy var timeLabel: UILabel = {
var time = UILabel()
time.sizeToFit()
time.font = UIFont.systemFontOfSize(10)
time.textColor = UIColor.whiteColor()
time.text = "2016-02-29 加入"
return time
}()
lazy var scoreLabel:UIButton = {
var score = UIButton()
score.titleLabel?.font = UIFont.systemFontOfSize(8)
score.layer.cornerRadius = 15
score.titleEdgeInsets = UIEdgeInsetsMake(0,3,0,3)
let image = UIImage().imageWithColor(GLOBAL_COLOR())
score.setBackgroundImage(image, forState: UIControlState.Normal)
score.addTarget(self, action:"scoreMarket", forControlEvents: .TouchUpInside)
score.setTitle("39 积分", forState: UIControlState.Normal)
score.sizeToFit()
return score
}()
lazy var tableView:UITableView = {
var tab = UITableView(frame:CGRectZero, style: UITableViewStyle.Grouped)
tab.tableFooterView = UIView()
tab.scrollEnabled = false
tab.contentInset = UIEdgeInsetsMake(-40,0,0,0)
tab.sectionHeaderHeight = 0
tab.sectionFooterHeight = 10
tab.delegate = self
tab.dataSource = self
return tab
}()
lazy var scrollView:UIScrollView = {
var s = UIScrollView(frame: SCREEN_RECT())
s.contentSize = CGSizeMake(SCREEN_RECT().size.width,SCREEN_RECT().size.height*1.01)
s.userInteractionEnabled = true
s.showsVerticalScrollIndicator = false
s.backgroundColor = UIColor.whiteColor()
s.delegate = self
return s
}()
@objc func tapBackImage(){
let alertVC = UIAlertController(title: "修改封面", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
let camero = UIAlertAction(title: "拍照", style: UIAlertActionStyle.Default, handler: nil)
let pickPhoto = UIAlertAction(title: "从相册挑选", style: UIAlertActionStyle.Default, handler: nil)
let cancel = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
alertVC.addAction(camero)
alertVC.addAction(pickPhoto)
alertVC.addAction(cancel)
self.presentViewController(alertVC, animated: true, completion: nil)
}
@objc private func iconClick(){
let alertVC = UIAlertController(title: "修改封面", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
let seeBigImage = UIAlertAction(title: "查看大图", style: UIAlertActionStyle.Default, handler: nil)
let camero = UIAlertAction(title: "拍照", style: UIAlertActionStyle.Default, handler: nil)
let pickPhoto = UIAlertAction(title: "从相册挑选", style: UIAlertActionStyle.Default, handler: nil)
let cancel = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
alertVC.addAction(seeBigImage)
alertVC.addAction(camero)
alertVC.addAction(pickPhoto)
alertVC.addAction(cancel)
self.presentViewController(alertVC, animated: true, completion: nil)
}
@objc private func scoreMarket(){
navigationController?.presentViewController(WXNavigationController(rootViewController:ScoreController()), animated: true , completion: nil)
}
@objc func set(){
presentViewController(WXNavigationController(rootViewController:AccountSetController()), animated: true , completion: nil)
}
@objc func add(){
presentViewController(WXNavigationController(rootViewController:AddFriendController()), animated: true, completion: nil)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
backImage.snp_makeConstraints { (make) -> Void in
make.width.equalTo(SCREEN_RECT().width)
make.height.equalTo(SCREEN_RECT().width)
make.top.equalTo(-44)
}
tableView.snp_makeConstraints { (make) -> Void in
make.width.equalTo(SCREEN_RECT().width)
make.height.equalTo(200)
tableViewConstraint = make.top.equalTo(backImage.snp_bottom).offset(-65).constraint
}
containView.snp_makeConstraints { (make) -> Void in
make.width.equalTo(SCREEN_RECT().width)
make.height.equalTo(SCREEN_RECT().width*0.6)
make.bottom.equalTo(tableView.snp_top)
}
icon.snp_makeConstraints { (make) -> Void in
make.centerX.equalTo(containView.snp_centerX)
make.top.equalTo(containView).offset(50)
}
nameLabel.snp_makeConstraints { (make) -> Void in
make.top.equalTo(icon.snp_bottom)
make.centerX.equalTo(containView.snp_centerX)
}
timeLabel.snp_makeConstraints { (make) -> Void in
make.centerX.equalTo(containView.snp_centerX)
make.top.equalTo(nameLabel.snp_bottom).offset(20)
}
scoreLabel.snp_makeConstraints { (make) -> Void in
make.width.equalTo(35)
make.height.equalTo(15)
make.centerX.equalTo(containView.snp_centerX)
make.top.equalTo(timeLabel.snp_bottom).offset(5)
}
// toolView.snp_makeConstraints { (make) -> Void in
// make.width.equalTo(SCREEN_RECT().width)
// make.height.equalTo(44)
//// make.top.equalTo(containView.snp_bottom)
// }
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.clearColor()
self.automaticallyAdjustsScrollViewInsets = false
navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "my_center_setting_icon"), style: UIBarButtonItemStyle.Plain, target: self, action: "set")
navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "add_friend_normal"), style: UIBarButtonItemStyle.Plain, target: self, action: "add")
view.backgroundColor = UIColor.lightGrayColor()
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: ID)
view.addSubview(scrollView)
// scrollView.addSubview(refresh)
scrollView.addSubview(backImage)
scrollView.addSubview(tableView)
scrollView.addSubview(containView)
// scrollView.didAddSubview(toolView)
}
}
extension MineViewController: UITableViewDelegate,UITableViewDataSource{
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 3
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier(ID)
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: ID)
}
cell?.textLabel?.text = "test"
return cell!
}
}
extension MineViewController : UIScrollViewDelegate{
func scrollViewDidScroll(scrollView: UIScrollView) {
let offset = scrollView.contentOffset.y
if offset < 0 {
if abs(offset) < 45 {
tableViewConstraint?.uninstall()
tableView.snp_updateConstraints(closure: { (make) -> Void in
make.top.equalTo(backImage.snp_bottom).offset(-45+abs(offset))
})
}
else if abs(offset) > 45{
tableViewConstraint?.uninstall()
tableView.snp_updateConstraints { (make) -> Void in
make.top.equalTo(backImage.snp_bottom)
}
}
}else if offset > 0 {
tableViewConstraint?.uninstall()
tableView.snp_updateConstraints(closure: { (make) -> Void in
make.top.equalTo(backImage.snp_bottom).offset(-45-abs(offset))
})
}
}
// func scrollViewWillBeginDecelerating(scrollView: UIScrollView) {
// self.refresh.beginRefreshing()
// }
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
// self.refresh.beginRefreshing()
backImage.frame.origin.y = 0
tableViewConstraint?.uninstall()
tableView.snp_updateConstraints { (make) -> Void in
make.top.equalTo(backImage.snp_bottom).offset(-45)
}
}
} | mit | 6bcec8f74a4662b1cbe27c794c62db47 | 35.549091 | 171 | 0.645572 | 4.722744 | false | false | false | false |
BigZhanghan/DouYuLive | DouYuLive/DouYuLive/Classes/PCH/common.swift | 1 | 573 | //
// common.swift
// DouYuLive
//
// Created by zhanghan on 2017/9/28.
// Copyright © 2017年 zhanghan. All rights reserved.
//
import UIKit
//screen_size
let Screen_width : CGFloat = UIScreen.main.bounds.size.width;
let Screen_height : CGFloat = UIScreen.main.bounds.size.height;
let StatusBarH : CGFloat = 20
let NavigationBarH :CGFloat = 44
let TabBarH : CGFloat = 49
extension NSDate {
class func getCurrentTime() -> String {
let nowDate = NSDate()
let interval = Int(nowDate.timeIntervalSince1970)
return "\(interval)"
}
}
| mit | 3f73c010bead752b9be6a189ddc90afc | 19.357143 | 63 | 0.678947 | 3.677419 | false | false | false | false |
paritoshmmmec/IBM-Ready-App-for-Healthcare | iOS/ReadyAppPT/Controllers/RoutineOptionsViewController.swift | 2 | 3635 | /*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2014, 2015. All Rights Reserved.
*/
import UIKit
/**
View controller to show all the individual exercises.
*/
class RoutineOptionsViewController: UIViewController, UIGestureRecognizerDelegate {
@IBOutlet weak var videoRoutineTableView: UITableView!
@IBOutlet weak var routineLabel: UILabel!
var routineTitle = ""
var currentExercises = ExerciseDataManager.exerciseDataManager.exercises
var selectedCell: VideoTableViewCell?
var selectedIndex: Int = 0
// MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.interactivePopGestureRecognizer.delegate = self
routineLabel.text = routineTitle
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func popRoutineOptionsViewController(sender: AnyObject) {
self.navigationController?.popViewControllerAnimated(true)
}
// MARK: UITableView delegate methods
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.currentExercises.count
}
/**
This table view sets all the info on each videoTableViewCell
*/
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("videoCell") as! VideoTableViewCell
if var exercises = self.currentExercises {
var exercise = exercises[indexPath.row]
// Configure cell with video information
// All data pulled from server except images, which are local
var imageFile = "exercise_thumb\(indexPath.row + 1)"
cell.thumbNail.image = UIImage(named: imageFile)
cell.exerciseTitle.text = exercise.exerciseTitle == nil ? "" : exercise.exerciseTitle
cell.exerciseDescription.text = exercise.exerciseDescription == nil ? "" : exercise.exerciseDescription
cell.videoID = exercise.videoURL == nil ? "" : exercise.videoURL
cell.tools = exercise.tools
cell.setExerciseStats(exercise.minutes.integerValue, rep: exercise.repetitions.integerValue, sets: exercise.sets.integerValue)
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
selectedCell = tableView.cellForRowAtIndexPath(indexPath) as? VideoTableViewCell
selectedIndex = indexPath.row
self.performSegueWithIdentifier("videoSegue", sender: nil)
}
// 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?) {
if segue.identifier == "videoSegue" {
var videoVC = segue.destinationViewController as! VideoPlayerViewController
if var cell = selectedCell {
videoVC.exerciseName = cell.exerciseDescription.text!
videoVC.videoStats = cell.videoStats
videoVC.tools = cell.tools
videoVC.currentExercise = selectedIndex + 1
videoVC.totalExercises = self.currentExercises.count
videoVC.currentVideoID = cell.videoID
}
}
}
}
| epl-1.0 | a41039c3a902c82b19159c22001d1979 | 37.252632 | 138 | 0.675014 | 5.678125 | false | false | false | false |
codeliling/DesignResearch | DesignBase/DesignBase/Controllers/MenuViewController.swift | 1 | 21701 | //
// MenuViewController.swift
// DesignBase
//
// Created by lotusprize on 15/4/19.
// Copyright (c) 2015年 geekTeam. All rights reserved.
//
import UIKit
class MenuViewController:UIViewController,UITableViewDataSource,UITableViewDelegate, UIScrollViewDelegate{
@IBOutlet weak var typeMenuScrollView: UIScrollView!
@IBOutlet weak var tableListView: UITableView!
var view1:UIView?
var view2:UIView?
var view3:UIView?
var methodMenuList:NSMutableArray!
var theorySubMenuList:NSArray?
var currentType = MenuType.METHOD
var isEyeClicked:Bool = false
var isAboutIconClicked:Bool = false
let blueBg = UIColor(red: 102/255.0, green: 59/255.0, blue: 209/255.0, alpha: 1)
var baiduStatistic:BaiduMobStat = BaiduMobStat.defaultStat()
@IBOutlet weak var backIcon: UIImageView!
@IBOutlet weak var eysImageView: UIImageView!
@IBOutlet weak var aboutIcon: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
tableListView.delegate = self;
tableListView.dataSource = self;
//tableListView.registerNib(UINib(nibName: "menuCell", bundle: nil), forCellReuseIdentifier: "Cell")
//tableListView.registerClass(MenuCell.classForCoder(), forCellReuseIdentifier: "Cell")
let plistpath = NSBundle.mainBundle().pathForResource("methodMenuList", ofType: "plist")!
//读取plist内容放到NSMutableArray内
methodMenuList = NSMutableArray(contentsOfFile: plistpath)
var view = UIView()
view.backgroundColor = UIColor.clearColor()
tableListView.tableFooterView = view
//tableListView.backgroundView = nil
tableListView.backgroundColor = blueBg
tableListView.bounces = false
self.initMainMenu()
var tabBackIcon:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "clickBackIcon:")
backIcon.addGestureRecognizer(tabBackIcon)
var tapEyeIcon:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "clickEyeIcon:")
eysImageView.addGestureRecognizer(tapEyeIcon)
var tapAboutIcon:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "clickAboutIcon:")
aboutIcon.addGestureRecognizer(tapAboutIcon)
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
if currentType == MenuType.THEORY{
return methodMenuList.count
}
else
{
return 1
}
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if currentType == MenuType.THEORY{
if (section == 0){
return 55
}
else
{
return 80
}
}
else
{
return 0
}
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if currentType == MenuType.THEORY{
var view:UIView = UIView(frame: CGRectMake(0, 0, 210, 80))
var dict:NSDictionary = methodMenuList.objectAtIndex(section) as! NSDictionary
theorySubMenuList = dict.objectForKey("list") as? NSArray
var cnName:String = dict.objectForKey("cnName") as! String
var enName:String = dict.objectForKey("enName") as! String
var frame:CGRect?
var lineFrame:CGRect?
if (section == 0){
frame = CGRectMake(0, 0, 180, 40)
lineFrame = CGRectMake(15, 45, 180, 1)
}
else{
frame = CGRectMake(0, 30, 180, 40)
lineFrame = CGRectMake(15, 75, 180, 1)
}
var titleSection:MenuView = MenuView(frame:frame!, chineseTitle: cnName, enTitle: enName)
titleSection.backgroundColor = UIColor.clearColor()
view.addSubview(titleSection)
view.backgroundColor = blueBg
return view
}
else
{
return nil
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cellIdentifier:NSString = "Cell";
//var cell:MenuCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? MenuCell;
var cell:MenuCell? = NSBundle.mainBundle().loadNibNamed("menuCell", owner: nil, options: nil)[0] as? MenuCell
var dict:NSDictionary!
if currentType == MenuType.THEORY{
var tempDict:NSDictionary = methodMenuList.objectAtIndex(indexPath.section) as! NSDictionary
theorySubMenuList = tempDict.objectForKey("list") as? NSArray
dict = theorySubMenuList?.objectAtIndex(indexPath.row) as! NSDictionary
}
else
{
dict = methodMenuList.objectAtIndex(indexPath.row) as? NSDictionary
}
var cnName:String = dict?.objectForKey("cnName") as! String
var enName:String = dict?.objectForKey("enName") as! String
var menuView:MenuView = MenuView(frame: CGRectMake(0, 0, 210, 54), chineseTitle: cnName, enTitle: enName)
menuView.backgroundColor = UIColor(red: 102/255.0, green: 59/255.0, blue: 209/255.0, alpha: 1)
menuView.updateTextColor(UIColor.whiteColor())
cell?.contentView.addSubview(menuView)
var viewFrame:CGRect? = cell?.frame
cell?.selectedBackgroundView = UIView(frame: viewFrame!)
cell?.selectedBackgroundView.backgroundColor = UIColor.whiteColor()
cell?.separatorInset = UIEdgeInsetsMake(0, 15, 0, 0)
cell?.layoutMargins = UIEdgeInsetsMake(0, 15, 0, 0)
cell?.preservesSuperviewLayoutMargins = false
return cell!;
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 55
}
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
var cell:MenuCell? = tableView.cellForRowAtIndexPath(indexPath) as? MenuCell
if let views = cell?.contentView.subviews{
for subView in views{
if (subView.isKindOfClass(MenuView.classForCoder()))
{
var view:MenuView = subView as! MenuView
view.updateTextColor(UIColor.whiteColor())
}
}
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if currentType == MenuType.THEORY{
var dict:NSDictionary = methodMenuList.objectAtIndex(section) as! NSDictionary
var list:NSArray = dict.objectForKey("list") as! NSArray
return list.count
}
else
{
return methodMenuList.count;
}
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
//cell.backgroundColor = UIColor(red: 102/255.0, green: 59/255.0, blue: 209/255.0, alpha: 1)
if (currentType == MenuType.THEORY) && indexPath.row == 0 && indexPath.section == 0{
for subView in cell.contentView.subviews{
if (subView.isKindOfClass(MenuView.classForCoder()))
{
var view:MenuView = subView as! MenuView
view.updateTextColor(UIColor(red: 102/255.0, green: 59/255.0, blue: 209/255.0, alpha: 1))
view.backgroundColor = UIColor.whiteColor()
}
}
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
println(indexPath.row)
if ((currentType == MenuType.THEORY) && ((indexPath.row != 0) || (indexPath.section != 0))){
var first:NSIndexPath = NSIndexPath(forRow: 0, inSection: 0)
var firstCell:MenuCell? = tableView.cellForRowAtIndexPath(first) as? MenuCell
if let views = firstCell?.contentView.subviews{
for subView in views{
if (subView.isKindOfClass(MenuView.classForCoder()))
{
var view:MenuView = subView as! MenuView
view.updateTextColor(UIColor.whiteColor())
view.backgroundColor = UIColor(red: 102/255.0, green: 59/255.0, blue: 209/255.0, alpha: 1)
}
}
}
}
var cell:MenuCell? = tableView.cellForRowAtIndexPath(indexPath) as? MenuCell
if let views = cell?.contentView.subviews{
for subView in views{
if (subView.isKindOfClass(MenuView.classForCoder()))
{
var view:MenuView = subView as! MenuView
view.updateTextColor(UIColor(red: 102/255.0, green: 59/255.0, blue: 209/255.0, alpha: 1))
}
}
}
var subMenuModel:SubMenuModel = SubMenuModel()
switch currentType{
case .CASE://案例
println("case")
subMenuModel.type = MenuType.CASE
case .THEORY:
println("theory")
subMenuModel.type = MenuType.THEORY
case .METHOD:
println("method")
subMenuModel.type = MenuType.METHOD
}
if (currentType.rawValue != MenuType.THEORY.rawValue){
var dict:NSDictionary = methodMenuList.objectAtIndex(indexPath.row) as! NSDictionary
subMenuModel.cnName = dict.objectForKey("cnName") as! String
subMenuModel.enName = dict.objectForKey("enName") as! String
var flag: AnyObject? = dict.objectForKey("flag")
if (flag != nil){
subMenuModel.tableIndex = Int(flag!.integerValue)
}
else{
subMenuModel.tableIndex = 0
}
NSNotificationCenter.defaultCenter().postNotificationName("SubAnimationMenuNotification", object: "OPEN")
NSNotificationCenter.defaultCenter().postNotificationName("addSubMenuNotification", object: subMenuModel)
}
else{
var fatherDict:NSDictionary = methodMenuList.objectAtIndex(indexPath.section) as! NSDictionary
var subList:NSArray = fatherDict.objectForKey("list") as! NSArray
var dict:NSDictionary = subList.objectAtIndex(indexPath.row) as! NSDictionary
subMenuModel.chapterID = dict.objectForKey("flag") as? String
NSNotificationCenter.defaultCenter().postNotificationName("TheoryContentNotification", object: subMenuModel)
}
if (currentType.rawValue == MenuType.METHOD.rawValue){
var plistpath:String?
switch indexPath.row{
case 0:
plistpath = NSBundle.mainBundle().pathForResource("methodStage", ofType: "plist")
case 1:
plistpath = NSBundle.mainBundle().pathForResource("methodRequirement", ofType: "plist")
case 2:
plistpath = NSBundle.mainBundle().pathForResource("methodCategory", ofType: "plist")
case 3:
plistpath = NSBundle.mainBundle().pathForResource("methodObject", ofType: "plist")
case 4:
plistpath = NSBundle.mainBundle().pathForResource("methodDomain", ofType: "plist")
default:
break
}
var methodList:NSMutableArray = NSMutableArray(contentsOfFile: plistpath!)!
var methodArray:Array = [MethodModel]()
var methodModel:MethodModel?
if methodList.count > 0{
var dict:NSDictionary = methodList.objectAtIndex(0) as! NSDictionary
var list:NSArray = dict.objectForKey("list") as! NSArray
for tempDict in list{
methodModel = MethodModel()
methodModel?.cnName = tempDict.objectForKey("cnName") as? String
methodModel?.iconName = tempDict.objectForKey("iconName") as! String
methodModel?.flag = tempDict.objectForKey("flag") as? String
methodArray.append(methodModel!)
}
}
NSNotificationCenter.defaultCenter().postNotificationName("ListContentNotification", object: methodArray)
}
else if (currentType.rawValue == MenuType.CASE.rawValue){
var plistpath:String?
switch indexPath.row{
case 0:
plistpath = NSBundle.mainBundle().pathForResource("caseStage", ofType: "plist")
case 1:
plistpath = NSBundle.mainBundle().pathForResource("caseRequirement", ofType: "plist")
case 2:
plistpath = NSBundle.mainBundle().pathForResource("caseCategory", ofType: "plist")
case 3:
plistpath = NSBundle.mainBundle().pathForResource("caseObject", ofType: "plist")
case 4:
plistpath = NSBundle.mainBundle().pathForResource("caseDomain", ofType: "plist")
default:
break
}
var caseList:NSMutableArray = NSMutableArray(contentsOfFile: plistpath!)!
var caseArray:Array = [MethodModel]()
var caseModel:MethodModel?
if caseList.count > 0{
var dict:NSDictionary = caseList.objectAtIndex(0) as! NSDictionary
var list:NSArray = dict.objectForKey("list") as! NSArray
for tempDict in list{
caseModel = MethodModel()
caseModel?.cnName = tempDict.objectForKey("cnName") as? String
caseModel?.iconName = tempDict.objectForKey("iconName") as? String
caseModel?.flag = tempDict.objectForKey("flag") as? String
caseModel?.enName = tempDict.objectForKey("enName") as? String
caseArray.append(caseModel!)
}
}
NSNotificationCenter.defaultCenter().postNotificationName("ListContentNotification", object: caseArray)
}
}
func initMainMenu(){
view1 = UIView(frame: CGRectMake(0, 0, 210, 100))
var theoryBtn1:UIImageView = UIImageView(image: UIImage(named:"theoryBtn"))
theoryBtn1.frame = CGRectMake(20, 17, 38, 65)
theoryBtn1.contentMode = UIViewContentMode.ScaleAspectFit
view1!.addSubview(theoryBtn1)
var methodBtn1:UIImageView = UIImageView(image: UIImage(named:"methodBtn"))
methodBtn1.frame = CGRectMake(85, 17, 38, 65)
methodBtn1.contentMode = UIViewContentMode.ScaleAspectFit
methodBtn1.tag = MenuType.CASE.rawValue
view1!.addSubview(methodBtn1)
var caseBtn1:UIImageView = UIImageView(image: UIImage(named:"caseBtn"))
caseBtn1.frame = CGRectMake(150, 17, 38, 65)
caseBtn1.contentMode = UIViewContentMode.ScaleAspectFit
view1!.addSubview(caseBtn1)
typeMenuScrollView.addSubview(view1!)
view2 = UIView(frame: CGRectMake(210, 0, 210, 100))
var theoryBtn2:UIImageView = UIImageView(image: UIImage(named:"theoryBtn"))
theoryBtn2.frame = CGRectMake(150, 17, 38, 65)
theoryBtn2.contentMode = UIViewContentMode.ScaleAspectFit
view2!.addSubview(theoryBtn2)
var methodBtn2:UIImageView = UIImageView(image: UIImage(named:"methodBtn"))
methodBtn2.frame = CGRectMake(20, 17, 38, 65)
methodBtn2.contentMode = UIViewContentMode.ScaleAspectFit
methodBtn2.tag = MenuType.THEORY.rawValue
view2!.addSubview(methodBtn2)
var caseBtn2:UIImageView = UIImageView(image: UIImage(named:"caseBtn"))
caseBtn2.frame = CGRectMake(85, 17, 38, 65)
caseBtn2.contentMode = UIViewContentMode.ScaleAspectFit
view2!.addSubview(caseBtn2)
typeMenuScrollView.addSubview(view2!)
view3 = UIView(frame: CGRectMake(420, 0, 210, 100))
var theoryBtn3:UIImageView = UIImageView(image: UIImage(named:"theoryBtn"))
theoryBtn3.frame = CGRectMake(85, 17, 38, 65)
theoryBtn3.contentMode = UIViewContentMode.ScaleAspectFit
view3!.addSubview(theoryBtn3)
var methodBtn3:UIImageView = UIImageView(image: UIImage(named:"methodBtn"))
methodBtn3.frame = CGRectMake(150, 17, 38, 65)
methodBtn3.contentMode = UIViewContentMode.ScaleAspectFit
methodBtn3.tag = MenuType.METHOD.rawValue
view3!.addSubview(methodBtn3)
var caseBtn3:UIImageView = UIImageView(image: UIImage(named:"caseBtn"))
caseBtn3.frame = CGRectMake(20, 17, 38, 65)
caseBtn3.contentMode = UIViewContentMode.ScaleAspectFit
view3!.addSubview(caseBtn3)
typeMenuScrollView.addSubview(view3!)
typeMenuScrollView.contentSize = CGSizeMake(630, 0)
typeMenuScrollView.delegate = self
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
if (!scrollView.isKindOfClass(UITableView))
{
var pageWidth:CGFloat = scrollView.frame.size.width
var currentPage:Int = Int(floor((scrollView.contentOffset.x * 2.0 + pageWidth) / (pageWidth * 2.0)))
if (currentPage == 0)
{
var view:UIView = view3!;
self.view3 = self.view2;
self.view2 = self.view1;
self.view1 = view;
}
if (currentPage == 2)
{
//换指针
var view:UIView = view1!;
self.view1 = self.view2;
self.view2 = self.view3;
self.view3 = view;
}
//恢复原位
self.view1!.frame = CGRectMake(0, 0, 210, 130)
self.view2!.frame = CGRectMake(210, 0, 210, 130)
self.view3!.frame = CGRectMake(420, 0, 210, 130)
self.typeMenuScrollView.contentOffset = CGPointMake(210, 0);
if let views = view1?.subviews{
for view in views{
if view.isKindOfClass(UIImageView.classForCoder()){
if view.tag == MenuType.CASE.rawValue{
//案例
let plistpath = NSBundle.mainBundle().pathForResource("caseMenuList", ofType: "plist")!
methodMenuList = NSMutableArray(contentsOfFile: plistpath)
currentType = MenuType.CASE
eysImageView.hidden = true
aboutIcon.hidden = true
NSNotificationCenter.defaultCenter().postNotificationName("TypeMenuNotification", object: MenuType.CASE.rawValue)
}
else if view.tag == MenuType.THEORY.rawValue{
//理论
let plistpath = NSBundle.mainBundle().pathForResource("theoryMenuList", ofType: "plist")!
methodMenuList = NSMutableArray(contentsOfFile: plistpath)
currentType = MenuType.THEORY
eysImageView.hidden = true
aboutIcon.hidden = true
NSNotificationCenter.defaultCenter().postNotificationName("TypeMenuNotification", object: MenuType.THEORY.rawValue)
}
else if view.tag == MenuType.METHOD.rawValue{
//方法
let plistpath = NSBundle.mainBundle().pathForResource("methodMenuList", ofType: "plist")!
methodMenuList = NSMutableArray(contentsOfFile: plistpath)
currentType = MenuType.METHOD
eysImageView.hidden = false
aboutIcon.hidden = false
NSNotificationCenter.defaultCenter().postNotificationName("TypeMenuNotification", object: MenuType.METHOD.rawValue)
}
tableListView.reloadData()
baiduStatistic.logEvent("ScrollMenuType", eventLabel: "滚动类型菜单")
}
}
}
}
}
func clickBackIcon(recognizer:UITapGestureRecognizer){
println("Back...")
NSNotificationCenter.defaultCenter().postNotificationName("SubAnimationMenuNotification", object: "CLOSE")
}
func clickAboutIcon(recognizer:UITapGestureRecognizer){
if (!isAboutIconClicked){
aboutIcon.alpha = 0.8
self.isAboutIconClicked=true
}
else{
aboutIcon.alpha = 0.5
self.isAboutIconClicked=false
}
NSNotificationCenter.defaultCenter().postNotificationName("EyeAnimationMenuNotification", object: "ABOUT")
}
func clickEyeIcon(recognizer:UITapGestureRecognizer){
if (!isEyeClicked){
eysImageView.alpha = 0.8
isEyeClicked=true
}
else{
eysImageView.alpha = 0.5
isEyeClicked=false
}
NSNotificationCenter.defaultCenter().postNotificationName("EyeAnimationMenuNotification", object: "EYE")
}
} | apache-2.0 | 60f032c98b2a87dbc25b8c608515f0f6 | 42.813765 | 143 | 0.592062 | 5.129889 | false | false | false | false |
sharath-cliqz/browser-ios | Client/Cliqz/Frontend/Browser/ControlCenter/AntiPhishingPanel.swift | 2 | 5081 | //
// AntiPhishingPanel.swift
// Client
//
// Created by Mahmoud Adam on 12/29/16.
// Copyright © 2016 Mozilla. All rights reserved.
//
import UIKit
class AntiPhishingPanel: ControlCenterPanel {
//MARK: - Instance variables
//MARK: Views
fileprivate let descriptionLabel = UILabel()
//MARK: - View LifeCycle
override func viewDidLoad() {
super.viewDidLoad()
// panel title
descriptionLabel.text = NSLocalizedString("Anti-Phishing technology identifies and blocks potentially deceptive websites that try to get your password or account data before you visit the site.", tableName: "Cliqz", comment: "Anti-Phishing panel description")
descriptionLabel.textColor = textColor()
descriptionLabel.font = UIFont.systemFont(ofSize: 15)
descriptionLabel.numberOfLines = 0
self.view.addSubview(descriptionLabel)
}
//MARK: - Abstract methods implementation
override func getPanelTitle() -> String {
if isFeatureEnabledForCurrentWebsite {
return NSLocalizedString("You are safe", tableName: "Cliqz", comment: "Anti-Phishing panel title in the control center if the current website is safe.")
} else {
return NSLocalizedString("Your data is not protected", tableName: "Cliqz", comment: "Anti-Phishing panel title in the control center if the current website is a phishing one.")
}
}
override func getPanelSubTitle() -> String {
if isFeatureEnabledForCurrentWebsite {
return NSLocalizedString("No suspicious activities detected", tableName: "Cliqz", comment: "Anti-Phishing panel subtitle in the control center if the current website is safe.")
} else {
return NSLocalizedString("Suspicious activities were detected", tableName: "Cliqz", comment: "Anti-Phishing panel subtitle in the control center if the current website is a phishing one.")
}
}
override func getPanelIcon() -> UIImage? {
return UIImage(named: "hookIcon")
}
override func getLearnMoreURL() -> URL? {
return URL(string: "https://cliqz.com/whycliqz/anti-phishing")
}
override func setupConstraints() {
super.setupConstraints()
let panelLayout = OrientationUtil.controlPanelLayout()
if panelLayout == .portrait {
panelIcon.snp.updateConstraints { (make) in
make.height.equalTo(70)
make.width.equalTo(70 * 0.72)
}
subtitleLabel.snp.updateConstraints({ (make) in
make.top.equalTo(panelIcon.snp.bottom).offset(20)
})
descriptionLabel.snp.remakeConstraints { make in
make.left.equalTo(self.view).offset(30)
make.right.equalTo(self.view).offset(-30)
make.top.equalTo(subtitleLabel.snp.bottom).offset(20)
}
}
else if panelLayout == .landscapeCompactSize {
subtitleLabel.snp.remakeConstraints { make in
make.top.equalTo(panelIcon.snp.bottom).offset(20)
make.left.equalTo(self.view.bounds.width/2).offset(20)
}
panelIcon.snp.remakeConstraints { (make) in
make.top.equalTo(titleLabel.snp.bottom).offset(20)
make.centerX.equalTo(titleLabel)
make.height.equalTo(70)
make.width.equalTo(70 * 0.72)
}
descriptionLabel.snp.remakeConstraints { make in
make.left.equalTo(self.view.bounds.width/2 + 20)
make.width.equalTo(self.view.bounds.width/2 - 40)
make.top.equalTo(self.view).offset(25)
}
okButton.snp.remakeConstraints { (make) in
make.size.equalTo(CGSize(width: 80, height: 40))
make.bottom.equalTo(self.view).offset(-12)
make.centerX.equalTo(descriptionLabel)
}
}
else{
subtitleLabel.snp.remakeConstraints { make in
make.top.equalTo(panelIcon.snp.bottom).offset(25)
make.left.equalTo(self.view).offset(20)
make.width.equalTo(self.view.frame.width - 40)
make.height.equalTo(20)
}
panelIcon.snp.updateConstraints { (make) in
make.height.equalTo(44)
make.width.equalTo(44 * 0.72)
}
descriptionLabel.snp.remakeConstraints { make in
make.left.equalTo(self.view).offset(30)
make.right.equalTo(self.view).offset(-30)
make.top.equalTo(subtitleLabel.snp.bottom).offset(15)
}
}
}
override func evaluateIsFeatureEnabledForCurrentWebsite() {
isFeatureEnabledForCurrentWebsite = !AntiPhishingDetector.isDetectedPhishingURL(self.currentURL)
}
override func getViewName() -> String {
return "atphish"
}
}
| mpl-2.0 | baf8be1f32173bee009217667e9c0b75 | 36.080292 | 267 | 0.605906 | 4.597285 | false | false | false | false |
billhu1996/HBHexagon | HBHexagon/HBHexagon.swift | 1 | 1587 | //
// HBHexagon.swift
// HBHexagon
//
// Created by 胡博 on 15/6/4.
// Copyright (c) 2015年 bill. All rights reserved.
//
import UIKit
@objc enum ImageShape: NSInteger {
case circle = 0
case hexagon = 1
}
extension UIImage {
@objc var hb_hexagonImage: UIImage {
let rect = CGRect(origin: CGPoint.zero, size: size)
UIGraphicsBeginImageContextWithOptions(size, false, scale)
let context = UIGraphicsGetCurrentContext()
context?.beginPath();
context?.setStrokeColor(red: 0, green: 0, blue: 0, alpha: 1)
context?.setLineWidth(1)
let center = CGPoint(x: rect.size.width / 2, y: rect.size.height / 2)
context?.move(to: CGPoint(x: rect.size.width, y: rect.size.height / 2))
for i in 0..<6 {
let i = CGFloat(i)
let x = rect.size.width * sin((3 + 2 * i) * CGFloat(M_PI) / 6) / 2
let y = rect.size.height * cos((-3 + 2 * i) * CGFloat(M_PI) / 6) / 2
context?.addLine(to: CGPoint(x: center.x + x, y: center.y + y))
}
context?.closePath()
UIBezierPath(cgPath: (context?.path!)!).addClip()
draw(in: rect)
let hexagonImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return hexagonImage!
}
}
@objc class HBHexagonImageView: UIImageView {
@objc var shape: ImageShape = ImageShape.hexagon
override var image: UIImage? {
set {
super.image = newValue?.hb_hexagonImage
}
get {
return super.image
}
}
}
| gpl-2.0 | 08d61846a7cb28f40fa56ef741a4b6c3 | 30 | 80 | 0.588235 | 3.809639 | false | false | false | false |
leo-lp/LPIM | LPIM/Classes/Card/LPTeamListViewController.swift | 1 | 3123 | //
// LPTeamListViewController.swift
// LPIM
//
// Created by lipeng on 2017/6/28.
// Copyright © 2017年 lipeng. All rights reserved.
//
import UIKit
class LPTeamListViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 12bc1fcb380b22fd77686749e7266e19 | 31.842105 | 136 | 0.670192 | 5.27027 | false | false | false | false |
ksco/swift-algorithm-club-cn | GCD/GCD.playground/Contents.swift | 1 | 575 | //: Playground - noun: a place where people can play
// Recursive version
func gcd(a: Int, _ b: Int) -> Int {
let r = a % b
if r != 0 {
return gcd(b, r)
} else {
return b
}
}
/*
// Iterative version
func gcd(m: Int, _ n: Int) -> Int {
var a = 0
var b = max(m, n)
var r = min(m, n)
while r != 0 {
a = b
b = r
r = a % b
}
return b
}
*/
func lcm(m: Int, _ n: Int) -> Int {
return m*n / gcd(m, n)
}
gcd(52, 39) // 13
gcd(228, 36) // 12
gcd(51357, 3819) // 57
gcd(841, 299) // 1
lcm(2, 3) // 6
lcm(10, 8) // 40
| mit | dc4d5c89edbfca23b1f60a03931f7fd7 | 13.74359 | 52 | 0.469565 | 2.415966 | false | false | false | false |
JadenGeller/Axiomatic | Tests/AxiomaticTests/PredicateTests.swift | 1 | 3090 | //
// PredicateTests.swift
// PredicateTests
//
// Created by Jaden Geller on 1/18/16.
// Copyright © 2016 Jaden Geller. All rights reserved.
//
@testable import Axiomatic
import Gluey
import XCTest
class PredicateTests: XCTestCase {
func testUnifyPredicate() throws {
let a = Binding<Term<Int>>()
let b = Binding<Term<Int>>()
// 100(a, 0, 1).
let p1 = Term(name: 100, arguments: [.variable(a), .literal(Term(atom: 0)), .literal(Term(atom: 1))])
// 100(-1, 0, b).
let p2 = Term(name: 100, arguments: [.literal(Term(atom: -1)), .literal(Term(atom: 0)), .variable(b)])
try? Term.unify(p1, p2)
XCTAssertEqual(-1, a.value?.name)
XCTAssertEqual(1, b.value?.name)
}
func testUnifyPredicateNested() throws {
let a = Binding<Term<Int>>()
// 100(10(1)).
let p1 = Term(name: 100, arguments: [.literal(Term(name: 10, arguments: [.literal(Term(atom: 1))]))])
// 100(10(a)).
let p2 = Term(name: 100, arguments: [.literal(Term(name: 10, arguments: [.variable(a)]))])
try Term.unify(p1, p2)
XCTAssertEqual(1, a.value?.name)
}
func testUnifyPredicateNestedVariable() throws {
let a = Binding<Term<Int>>()
let b = Binding<Term<Int>>()
let p1 = Term(name: 100, arguments: [.literal(Term(name: 10, arguments: [.variable(a)]))])
let p2 = Term(name: 100, arguments: [.literal(Term(name: 10, arguments: [.variable(b)]))])
try Term.unify(p1, p2)
b.value = Term(atom: 100)
XCTAssertEqual(100, a.value?.name)
}
func testUnifyPredicateMismatchName() {
let p1 = Term(name: 100, arguments: [.literal(Term(atom: 10))])
let p2 = Term(name: 101, arguments: [.literal(Term(atom: 10))])
XCTAssertNil(try? Term.unify(p1, p2))
}
func testUnifyPredicateMismatchArity() {
let p1 = Term(name: 100, arguments: [.literal(Term(atom: 10))])
let p2 = Term(name: 100, arguments: [.literal(Term(atom: 10)), .literal(Term(atom: 10))])
XCTAssertNil(try? Term.unify(p1, p2))
}
func testCopy() throws {
var a = Term<Int>(name: 100, arguments: [.variable(Binding())])
var b = Term<Int>(name: 100, arguments: [.variable(Binding())])
try Term.unify(a, b)
let context = CopyContext()
var aa = Term.copy(a, withContext: context)
var bb = Term.copy(b, withContext: context)
try Term.unify(a, Term<Int>(name: 100, arguments: [.literal(Term(atom: 5))]))
XCTAssertEqual(5, a.arguments[0].value?.name)
XCTAssertEqual(5, b.arguments[0].value?.name)
XCTAssertEqual(nil, aa.arguments[0].value?.name)
XCTAssertEqual(nil, bb.arguments[0].value?.name)
try Term.unify(aa, Term<Int>(name: 100, arguments: [.literal(Term(atom: -5))]))
XCTAssertEqual(5, a.arguments[0].value?.name)
XCTAssertEqual(5, b.arguments[0].value?.name)
XCTAssertEqual(-5, aa.arguments[0].value?.name)
XCTAssertEqual(-5, bb.arguments[0].value?.name)
}
}
| mit | c158139a22772f65d4e78e581e7fe1fc | 34.505747 | 110 | 0.596957 | 3.41326 | false | true | false | false |
bravelocation/yeltzland-ios | yeltzland/Models/LeagueTable.swift | 1 | 1509 | //
// LeagueTable.swift
// Yeltzland
//
// Created by John Pollard on 28/05/2022.
// Copyright © 2022 John Pollard. All rights reserved.
//
import Foundation
struct LeagueTableFeedData: Codable {
var table: LeagueTable
enum CodingKeys: String, CodingKey {
case table = "league-table"
}
}
struct LeagueTable: Codable {
var teams: [Team]
var description: String
var competition: Competition
}
struct Team: Codable, Identifiable {
var name: String
var id: Int
var allMatches: Results
var homeMatches: Results
var awayMatches: Results
var position: Int
var totalPoints: Int
var zone: String?
var outcome: String?
enum CodingKeys: String, CodingKey {
case name = "name"
case id = "id"
case allMatches = "all-matches"
case homeMatches = "home-matches"
case awayMatches = "away-matches"
case position = "position"
case totalPoints = "total-points"
case zone = "zone"
case outcome = "outcome"
}
}
struct Results: Codable {
var played: Int
var won: Int
var drawn: Int
var lost: Int
var goalsFor: Int
var goalsAgainst: Int
enum CodingKeys: String, CodingKey {
case played = "played"
case won = "won"
case drawn = "drawn"
case lost = "lost"
case goalsFor = "for"
case goalsAgainst = "against"
}
}
struct Competition: Codable {
var name: String
var id: Int
}
| mit | fe46ec7b540d668d813a1e369b2f4692 | 20.542857 | 55 | 0.612732 | 4.010638 | false | false | false | false |
kean/Nuke | Sources/Nuke/Tasks/TaskFetchOriginalImageData.swift | 1 | 7450 | // The MIT License (MIT)
//
// Copyright (c) 2015-2022 Alexander Grebenyuk (github.com/kean).
import Foundation
/// Fetches original image from the data loader (`DataLoading`) and stores it
/// in the disk cache (`DataCaching`).
final class TaskFetchOriginalImageData: ImagePipelineTask<(Data, URLResponse?)> {
private var urlResponse: URLResponse?
private var resumableData: ResumableData?
private var resumedDataCount: Int64 = 0
private var data = Data()
override func start() {
guard let urlRequest = request.urlRequest else {
// A malformed URL prevented a URL request from being initiated.
send(error: .dataLoadingFailed(error: URLError(.badURL)))
return
}
if let rateLimiter = pipeline.rateLimiter {
// Rate limiter is synchronized on pipeline's queue. Delayed work is
// executed asynchronously also on the same queue.
rateLimiter.execute { [weak self] in
guard let self = self, !self.isDisposed else {
return false
}
self.loadData(urlRequest: urlRequest)
return true
}
} else { // Start loading immediately.
loadData(urlRequest: urlRequest)
}
}
private func loadData(urlRequest: URLRequest) {
if request.options.contains(.skipDataLoadingQueue) {
loadData(urlRequest: urlRequest, finish: { /* do nothing */ })
} else {
// Wrap data request in an operation to limit the maximum number of
// concurrent data tasks.
operation = pipeline.configuration.dataLoadingQueue.add { [weak self] finish in
guard let self = self else {
return finish()
}
self.async {
self.loadData(urlRequest: urlRequest, finish: finish)
}
}
}
}
// This methods gets called inside data loading operation (Operation).
private func loadData(urlRequest: URLRequest, finish: @escaping () -> Void) {
guard !isDisposed else {
return finish()
}
// Read and remove resumable data from cache (we're going to insert it
// back in the cache if the request fails to complete again).
var urlRequest = urlRequest
if pipeline.configuration.isResumableDataEnabled,
let resumableData = ResumableDataStorage.shared.removeResumableData(for: request, pipeline: pipeline) {
// Update headers to add "Range" and "If-Range" headers
resumableData.resume(request: &urlRequest)
// Save resumable data to be used later (before using it, the pipeline
// verifies that the server returns "206 Partial Content")
self.resumableData = resumableData
}
signpost(self, "LoadImageData", .begin, "URL: \(urlRequest.url?.absoluteString ?? ""), resumable data: \(Formatter.bytes(resumableData?.data.count ?? 0))")
let dataLoader = pipeline.delegate.dataLoader(for: request, pipeline: pipeline)
let dataTask = dataLoader.loadData(with: urlRequest, didReceiveData: { [weak self] data, response in
guard let self = self else { return }
self.async {
self.dataTask(didReceiveData: data, response: response)
}
}, completion: { [weak self] error in
finish() // Finish the operation!
guard let self = self else { return }
signpost(self, "LoadImageData", .end, "Finished with size \(Formatter.bytes(self.data.count))")
self.async {
self.dataTaskDidFinish(error: error)
}
})
onCancelled = { [weak self] in
guard let self = self else { return }
signpost(self, "LoadImageData", .end, "Cancelled")
dataTask.cancel()
finish() // Finish the operation!
self.tryToSaveResumableData()
}
}
private func dataTask(didReceiveData chunk: Data, response: URLResponse) {
// Check if this is the first response.
if urlResponse == nil {
// See if the server confirmed that the resumable data can be used
if let resumableData = resumableData, ResumableData.isResumedResponse(response) {
data = resumableData.data
resumedDataCount = Int64(resumableData.data.count)
signpost(self, "LoadImageData", .event, "Resumed with data \(Formatter.bytes(resumedDataCount))")
}
resumableData = nil // Get rid of resumable data
}
// Append data and save response
data.append(chunk)
urlResponse = response
let progress = TaskProgress(completed: Int64(data.count), total: response.expectedContentLength + resumedDataCount)
send(progress: progress)
// If the image hasn't been fully loaded yet, give decoder a change
// to decode the data chunk. In case `expectedContentLength` is `0`,
// progressive decoding doesn't run.
guard data.count < response.expectedContentLength else { return }
send(value: (data, response))
}
private func dataTaskDidFinish(error: Swift.Error?) {
if let error = error {
tryToSaveResumableData()
send(error: .dataLoadingFailed(error: error))
return
}
// Sanity check, should never happen in practice
guard !data.isEmpty else {
send(error: .dataIsEmpty)
return
}
// Store in data cache
storeDataInCacheIfNeeded(data)
send(value: (data, urlResponse), isCompleted: true)
}
private func tryToSaveResumableData() {
// Try to save resumable data in case the task was cancelled
// (`URLError.cancelled`) or failed to complete with other error.
if pipeline.configuration.isResumableDataEnabled,
let response = urlResponse, !data.isEmpty,
let resumableData = ResumableData(response: response, data: data) {
ResumableDataStorage.shared.storeResumableData(resumableData, for: request, pipeline: pipeline)
}
}
}
extension ImagePipelineTask where Value == (Data, URLResponse?) {
func storeDataInCacheIfNeeded(_ data: Data) {
guard let dataCache = pipeline.delegate.dataCache(for: request, pipeline: pipeline), shouldStoreDataInDiskCache() else {
return
}
let key = pipeline.cache.makeDataCacheKey(for: request)
pipeline.delegate.willCache(data: data, image: nil, for: request, pipeline: pipeline) {
guard let data = $0 else { return }
// Important! Storing directly ignoring `ImageRequest.Options`.
dataCache.storeData(data, for: key)
}
}
private func shouldStoreDataInDiskCache() -> Bool {
guard (request.url?.isCacheable ?? false) || (request.publisher != nil) else {
return false
}
let policy = pipeline.configuration.dataCachePolicy
guard imageTasks.contains(where: { !$0.request.options.contains(.disableDiskCacheWrites) }) else {
return false
}
return policy == .storeOriginalData || policy == .storeAll || (policy == .automatic && imageTasks.contains { $0.request.processors.isEmpty })
}
}
| mit | 6eeb90640c0a8ad0de4a0015c85620ca | 40.620112 | 163 | 0.616242 | 4.901316 | false | false | false | false |
Fenrikur/ef-app_ios | Eurofurence/Modules/Preload/Presenter/PreloadPresenter.swift | 1 | 1945 | struct PreloadPresenter: SplashSceneDelegate, PreloadInteractorDelegate {
private let delegate: PreloadModuleDelegate
private let preloadScene: SplashScene
private let preloadService: PreloadInteractor
private let alertRouter: AlertRouter
init(delegate: PreloadModuleDelegate,
preloadScene: SplashScene,
preloadService: PreloadInteractor,
alertRouter: AlertRouter) {
self.delegate = delegate
self.preloadScene = preloadScene
self.preloadService = preloadService
self.alertRouter = alertRouter
preloadScene.delegate = self
}
func splashSceneWillAppear(_ splashScene: SplashScene) {
beginPreloading()
}
func preloadInteractorDidFailToPreload() {
let tryAgainAction = AlertAction(title: .tryAgain, action: beginPreloading)
let cancelAction = AlertAction(title: .cancel, action: notifyDelegatePreloadingCancelled)
let alert = Alert(title: .downloadError,
message: .preloadFailureMessage,
actions: [tryAgainAction, cancelAction])
alertRouter.show(alert)
}
func preloadInteractorDidFinishPreloading() {
delegate.preloadModuleDidFinishPreloading()
}
func preloadInteractorFailedToLoadDueToOldAppDetected() {
preloadScene.showStaleAppAlert()
delegate.preloadModuleDidCancelPreloading()
}
func preloadInteractorDidProgress(currentUnitCount: Int, totalUnitCount: Int, localizedDescription: String) {
let fractionalProgress = Float(currentUnitCount) / Float(totalUnitCount)
preloadScene.showProgress(fractionalProgress, progressDescription: localizedDescription)
}
private func beginPreloading() {
preloadService.beginPreloading(delegate: self)
}
private func notifyDelegatePreloadingCancelled() {
delegate.preloadModuleDidCancelPreloading()
}
}
| mit | 18fc2293f6b26f873c594bb57f26c3ca | 34.363636 | 113 | 0.713111 | 5.49435 | false | false | false | false |
lanjing99/iOSByTutorials | iOS 8 by tutorials/Chapter 15 - Beginning CloudKit/BabiFud-Starter/BabiFud/DetailViewController.swift | 2 | 9527 | /*
* Copyright (c) 2014 Razeware 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 UIKit
import UIWidgets
import CloudKit
class DetailViewController: UITableViewController, UISplitViewControllerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var masterPopoverController: UIPopoverController? = nil
@IBOutlet var coverView: UIImageView!
@IBOutlet var titleLabel: UILabel!
@IBOutlet var starRating: StarRatingControl!
@IBOutlet var kidsMenuButton: CheckedButton!
@IBOutlet var healthyChoiceButton: CheckedButton!
@IBOutlet var womensRoomButton: UIButton!
@IBOutlet var mensRoomButton: UIButton!
@IBOutlet var boosterButton: UIButton!
@IBOutlet var highchairButton: UIButton!
@IBOutlet var addPhotoButton: UIButton!
@IBOutlet var photoScrollView: UIScrollView!
@IBOutlet var noteTextView: UITextView!
var detailItem: Establishment! {
didSet {
if self.masterPopoverController != nil {
self.masterPopoverController!.dismissPopoverAnimated(true)
}
}
}
func configureView() {
// Update the user interface for the detail item.
if let detail: Establishment = self.detailItem {
title = detail.name
detail.loadCoverPhoto() { image in
dispatch_async(dispatch_get_main_queue()) {
self.coverView.image = image
}
}
titleLabel.text = detail.name
starRating.maxRating = 5
starRating.enabled = false
Model.sharedInstance().userInfo.loggedInToICloud() {
accountStatus, error in
let enabled = accountStatus == .Available || accountStatus == .CouldNotDetermine
self.starRating.enabled = enabled
self.healthyChoiceButton.enabled = enabled
self.kidsMenuButton.enabled = enabled
self.mensRoomButton.enabled = enabled
self.womensRoomButton.enabled = enabled
self.boosterButton.enabled = enabled
self.highchairButton.enabled = enabled
self.addPhotoButton.enabled = enabled
}
self.kidsMenuButton.checked = detailItem.kidsMenu
self.healthyChoiceButton.checked = detailItem.healthyChoice
self.womensRoomButton.selected = (detailItem.changingTable() & ChangingTableLocation.Womens).boolValue
self.mensRoomButton.selected = (detailItem.changingTable() & ChangingTableLocation.Mens).boolValue
self.highchairButton.selected = (detailItem.seatingType() & SeatingType.HighChair).boolValue
self.boosterButton.selected = (detailItem.seatingType() & SeatingType.Booster).boolValue
detail.fetchRating() { rating, isUser in
dispatch_async(dispatch_get_main_queue()) {
self.starRating.maxRating = 5
self.starRating.rating = Float(rating)
self.starRating.setNeedsDisplay()
self.starRating.emptyColor = isUser ? UIColor.yellowColor() : UIColor.whiteColor()
self.starRating.solidColor = isUser ? UIColor.yellowColor() : UIColor.whiteColor()
}
}
detail.fetchPhotos() { assets in
if assets != nil {
var x = 10
for record in assets {
if let asset = record.objectForKey("Photo") as? CKAsset {
let image: UIImage? = UIImage(contentsOfFile: asset.fileURL.path!)
if image != nil {
let imView = UIImageView(image: image)
imView.frame = CGRect(x: x, y: 0, width: 60, height: 60)
imView.clipsToBounds = true
imView.layer.cornerRadius = 8
x += 70
imView.layer.borderWidth = 0.0
//if the user has discovered the photo poster, color the photo with a green border
if let photoUserRef = record.objectForKey("User") as? CKReference {
let photoUserId = photoUserRef.recordID
let contactList = Model.sharedInstance().userInfo.contacts
let contacts = contactList.filter {$0.userRecordID == photoUserId}
if contacts.count > 0 {
imView.layer.borderWidth = 1.0
imView.layer.borderColor = UIColor.greenColor().CGColor
}
}
dispatch_async(dispatch_get_main_queue()) {
self.photoScrollView.addSubview(imView)
}
}
}
}
}
}
detail.fetchNote() { note in
println("note \(note)")
if let noteText = note {
dispatch_async(dispatch_get_main_queue()) {
self.noteTextView.text = noteText
}
}
}
}
}
func saveRating(rating: NSNumber) {
//replace this stub method
}
override func viewDidLoad() {
super.viewDidLoad()
coverView.clipsToBounds = true
coverView.layer.cornerRadius = 10.0
//add star rating block here
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
configureView()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if segue.identifier == "EditNote" {
let noteController = segue.destinationViewController as NotesViewController
noteController.establishment = self.detailItem
}
}
// #pragma mark - Split view
func splitViewController(splitController: UISplitViewController, willHideViewController viewController: UIViewController, withBarButtonItem barButtonItem: UIBarButtonItem, forPopoverController popoverController: UIPopoverController) {
barButtonItem.title = NSLocalizedString("Places", comment: "Places")
self.navigationItem.setLeftBarButtonItem(barButtonItem, animated: true)
self.masterPopoverController = popoverController
}
func splitViewController(splitController: UISplitViewController, willShowViewController viewController: UIViewController, invalidatingBarButtonItem barButtonItem: UIBarButtonItem) {
// Called when the view is shown again in the split view, invalidating the button and popover controller.
self.navigationItem.setLeftBarButtonItem(nil, animated: true)
self.masterPopoverController = nil
}
func splitViewController(splitController: UISplitViewController, collapseSecondaryViewController secondaryViewController: UIViewController, ontoPrimaryViewController primaryViewController: UIViewController) -> Bool {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
// #pragma mark - Image Picking
@IBAction func addPhoto(sender: AnyObject) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .SavedPhotosAlbum
self.presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController!, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]!) {
dismissViewControllerAnimated(true, completion: nil)
if let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
self.addPhotoToEstablishment(selectedImage)
}
}
}
func generateFileURL() -> NSURL {
let fileManager = NSFileManager.defaultManager()
let fileArray: NSArray = fileManager.URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask)
let fileURL = fileArray.lastObject?.URLByAppendingPathComponent(NSUUID().UUIDString).URLByAppendingPathExtension("jpg")
if let filePath = fileArray.lastObject?.path {
if !fileManager.fileExistsAtPath(filePath!) {
fileManager.createDirectoryAtPath(filePath!, withIntermediateDirectories: true, attributes: nil, error: nil)
}
}
return fileURL!
}
func addNewPhotoToScrollView(photo:UIImage) {
let newImView = UIImageView(image: photo)
let offset = self.detailItem.assetCount * 70 + 10
var frame: CGRect = CGRect(x: offset, y: 0, width: 60, height: 60)
newImView.frame = frame
newImView.clipsToBounds = true
newImView.layer.cornerRadius = 8
dispatch_async(dispatch_get_main_queue()) {
self.photoScrollView.addSubview(newImView)
self.photoScrollView.contentSize = CGSize(width: CGRectGetMaxX(frame), height: CGRectGetHeight(frame));
}
}
func addPhotoToEstablishment(photo: UIImage) {
//replace this stub
}
}
| mit | ea6faa289408be97013509c913fe82e4 | 39.368644 | 236 | 0.696652 | 5.019494 | false | false | false | false |
306244907/Weibo | JLSina/JLSina/Classes/View(视图和控制器)/Main(主要的)/JLBaseViewController.swift | 1 | 8189 | //
// JLBaseViewController.swift
// JLSina
//
// Created by 盘赢 on 2017/9/29.
// Copyright © 2017年 JinLong. All rights reserved.
//
import UIKit
//面试题:OC中支持多继承吗?如果不支持,如何替代
//答案:使用协议替代
//Swift的写法更类似于多继承!
//class JLBaseViewController: UIViewController , UITableViewDataSource , UITableViewDelegate {
//Swift中,利用extension 可以把函数按照功能分类管理,便于阅读和维护
//注意:
//1,extension 中不能有属性
//2,extension 不能重写"父类"本类的方法!重写父类方法,是子类的职责,扩展是对类的扩展!
//所有主控制器的基类控制器
class JLBaseViewController: UIViewController {
//访客视图信息字典
var visitorInfoDictionary: [String: String]?
//表格视图 - 如果用户没有登录,就不创建
var tableView: UITableView?
//刷新控件
var refreshControl: JLRefreshControl?
//上拉刷新标记
var isPullup = false
//自定义导航条
lazy var navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 20, width: UIScreen.cz_screenWidth(), height: 44))
//自定义的导航项 - 以后使用导航栏内容,统一使用navItem
lazy var navItem = UINavigationItem()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
JLNetworkManager.shared.userLogon ? loadData() : ()
//注册登录成功通知
NotificationCenter.default.addObserver(
self,
selector: #selector(loginSucess),
name: NSNotification.Name(rawValue: WBUserLoginSuccessedNotification),
object: nil)
}
deinit {
//注销通知
NotificationCenter.default.removeObserver(self)
}
//重写title的didSet
override var title: String? {
didSet {
navItem.title = title
}
}
//加载数据 - 具体实现,由子类负责
@objc func loadData() {
//如果子类不实现任何方法,默认关闭刷新
refreshControl?.endRefreshing()
}
}
//访客视图监听方法
extension JLBaseViewController {
//登录成功处理
@objc private func loginSucess(n: Notification) {
print("登录成功\(n)")
//登录前左边是注册,右边是登录
navItem.rightBarButtonItem = nil
navItem.leftBarButtonItem = nil
//更新UI => 将访客视图替换为表格视图
//需要重新设置View
//在访问 view == nil 的getter时,如果view == nil,会调用loadView ->viewDidLoad
view = nil
//注销通知 ->重新执行viewDidLoad会再次注册!(注册几次发送几次通知消息),避免通知被重复注册
NotificationCenter.default.removeObserver(self)
}
@objc private func login() {
//发送通知
NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
}
@objc private func register() {
print("用户注册")
}
}
// MARK: - 设置界面
extension JLBaseViewController {
private func setupUI() {
view.backgroundColor = UIColor.white
//取消自动缩进 - 如果隐藏了导航栏,会缩进20个点(目前版本不设置也好)
automaticallyAdjustsScrollViewInsets = false
setUpNavigationBar()
JLNetworkManager.shared.userLogon ? setupTableView() : setupVisitorView()
}
//设置表格视图 - 用户登录之后执行(子类重写此类方法)
//因为子类不需要关心用户登录之前的逻辑
@objc dynamic func setupTableView() {
tableView = UITableView(frame: view.bounds, style: .plain)
view.insertSubview(tableView!, belowSubview: navigationBar)
//设置数据源和代理 ->让子类直接实现数据源方法
tableView?.dataSource = self
tableView?.delegate = self
// tableView?.showsVerticalScrollIndicator = false
// tableView?.separatorStyle = .none
//设置内容缩进
tableView?.contentInset = UIEdgeInsets(top: navigationBar.bounds.height, left: 0, bottom: 0, right: 0)
//修改指示器缩进 - 强行解包是为了拿到一个必有的inset
tableView?.scrollIndicatorInsets = tableView!.contentInset
//设置刷新控件
//1,实例化控件
refreshControl = JLRefreshControl()
// let str = NSAttributedString(string: "正在刷新")
// refreshControl?.attributedTitle = str
refreshControl?.tintColor = UIColor.orange
//2,添加到表格视图
tableView?.addSubview(refreshControl!)
//3,添加监听方法
refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
}
//设置访客视图
private func setupVisitorView() {
let visitorView = JLVisitorView(frame: view.bounds)
view.insertSubview(visitorView, belowSubview: navigationBar)
//1,设置访客视图信息
visitorView.visitorInfo = visitorInfoDictionary
print("访客视图\(visitorView)")
//2,添加访客视图按钮监听方法
visitorView.loginBtn.addTarget(self, action: #selector(login), for: .touchUpInside)
visitorView.registerBtn.addTarget(self, action: #selector(register), for: .touchUpInside)
//3,设置导航条按钮
navItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: .plain, target: self, action: #selector(register))
navItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: .plain, target: self, action: #selector(login))
}
//设置导航条
private func setUpNavigationBar() {
//添加导航条
view.addSubview(navigationBar)
//将item设置给bar
navigationBar.items = [navItem]
//1>设置navbar整个背景的渲染颜色
navigationBar.barTintColor = UIColor.cz_color(withHex: 0xF6F6F6)
//2>设置navbar的字体颜色
navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.darkGray]
//3>设置item按钮的文字渲染颜色
navigationBar.tintColor = UIColor.orange
// navigationBar.backgroundColor = UIColor.white
//设置状态栏背景颜色
let a = UIApplication.shared.value(forKey: "statusBarWindow") as! UIView
let v = a .value(forKeyPath: "statusBar") as! UIView
v.backgroundColor = navigationBar.barTintColor
}
}
//MARK: - UITableViewDelegate , UITableViewDataSource
extension JLBaseViewController: UITableViewDelegate , UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
//基类只是准备方法,子类负责具体实现
//子类的数据源方法不需要 super
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//只是保证没有语法错误
return UITableViewCell()
}
//在显示最后一行的时候,做上拉刷新
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
//1,判断indexPath是否是最后一行
//(indexPath.section(最大) / indexPath.row(最后一行))
//1>row
let row = indexPath.row
//2> section
let section = tableView.numberOfSections - 1
if row < 0 || section < 0 {
return
}
//3,行数
let count = tableView.numberOfRows(inSection: section)
//如果是最后一行,同时没有开始上拉刷新
if row == count - 1 && !isPullup {
print("上拉刷新")
isPullup = true
//开始刷新
loadData()
}
// print("section--\(section)")
}
}
| mit | f32a585afae3ccef1dccf2cf5b218fdd | 28.5671 | 122 | 0.624158 | 4.38946 | false | false | false | false |
lllyyy/LY | ScrollableGraphView-master(折线图)/Classes/ScrollableGraphView.swift | 2 | 38192 | import UIKit
// MARK: - ScrollableGraphView
@IBDesignable
@objc open class ScrollableGraphView: UIScrollView, UIScrollViewDelegate, ScrollableGraphViewDrawingDelegate {
// MARK: - Public Properties
// Use these to customise the graph.
// #################################
// Fill Styles
// ###########
/// The background colour for the entire graph view, not just the plotted graph.
@IBInspectable open var backgroundFillColor: UIColor = UIColor.white
// Spacing
// #######
/// How far the "maximum" reference line is from the top of the view's frame. In points.
@IBInspectable open var topMargin: CGFloat = 10
/// How far the "minimum" reference line is from the bottom of the view's frame. In points.
@IBInspectable open var bottomMargin: CGFloat = 10
/// How far the first point on the graph should be placed from the left hand side of the view.
@IBInspectable open var leftmostPointPadding: CGFloat = 50
/// How far the final point on the graph should be placed from the right hand side of the view.
@IBInspectable open var rightmostPointPadding: CGFloat = 50
/// How much space should be between each data point.
@IBInspectable open var dataPointSpacing: CGFloat = 40
@IBInspectable var direction_: Int {
get { return direction.rawValue }
set {
if let enumValue = ScrollableGraphViewDirection(rawValue: newValue) {
direction = enumValue
}
}
}
/// Which side of the graph the user is expected to scroll from.
open var direction = ScrollableGraphViewDirection.leftToRight
// Graph Range
// ###########
/// Forces the graph's minimum to always be zero. Used in conjunction with shouldAutomaticallyDetectRange or shouldAdaptRange, if you want to force the minimum to stay at 0 rather than the detected minimum.
@IBInspectable open var shouldRangeAlwaysStartAtZero: Bool = false
/// The minimum value for the y-axis. This is ignored when shouldAutomaticallyDetectRange or shouldAdaptRange = true
@IBInspectable open var rangeMin: Double = 0
/// The maximum value for the y-axis. This is ignored when shouldAutomaticallyDetectRange or shouldAdaptRange = true
@IBInspectable open var rangeMax: Double = 100
// Adapting & Animations
// #####################
/// Whether or not the y-axis' range should adapt to the points that are visible on screen. This means if there are only 5 points visible on screen at any given time, the maximum on the y-axis will be the maximum of those 5 points. This is updated automatically as the user scrolls along the graph.
@IBInspectable open var shouldAdaptRange: Bool = false
/// If shouldAdaptRange is set to true then this specifies whether or not the points on the graph should animate to their new positions. Default is set to true.
@IBInspectable open var shouldAnimateOnAdapt: Bool = true
/// Whether or not the graph should animate to their positions when the graph is first displayed.
@IBInspectable open var shouldAnimateOnStartup: Bool = true
// Reference Line Settings
// #######################
var referenceLines: ReferenceLines? = nil
// MARK: - Private State
// #####################
private var isInitialSetup = true
private var isCurrentlySettingUp = false
private var viewportWidth: CGFloat = 0 {
didSet { if(oldValue != viewportWidth) { viewportDidChange() }}
}
private var viewportHeight: CGFloat = 0 {
didSet { if(oldValue != viewportHeight) { viewportDidChange() }}
}
private var totalGraphWidth: CGFloat = 0
private var offsetWidth: CGFloat = 0
// Graph Line
private var zeroYPosition: CGFloat = 0
// Graph Drawing
private var drawingView = UIView()
private var plots: [Plot] = [Plot]()
// Reference Lines
private var referenceLineView: ReferenceLineDrawingView?
// Labels
private var labelsView = UIView()
private var labelPool = LabelPool()
// Data Source
open var dataSource: ScrollableGraphViewDataSource? {
didSet {
if(plots.count > 0) {
reload()
}
}
}
// Active Points & Range Calculation
private var previousActivePointsInterval: CountableRange<Int> = -1 ..< -1
private var activePointsInterval: CountableRange<Int> = -1 ..< -1 {
didSet {
if(oldValue.lowerBound != activePointsInterval.lowerBound || oldValue.upperBound != activePointsInterval.upperBound) {
if !isCurrentlySettingUp { activePointsDidChange() }
}
}
}
private var range: (min: Double, max: Double) = (0, 100) {
didSet {
if(oldValue.min != range.min || oldValue.max != range.max) {
if !isCurrentlySettingUp { rangeDidChange() }
}
}
}
// MARK: - INIT, SETUP & VIEWPORT RESIZING
// #######################################
public override init(frame: CGRect) {
super.init(frame: frame)
}
public init(frame: CGRect, dataSource: ScrollableGraphViewDataSource) {
self.dataSource = dataSource
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// You can change how you want the graph to appear in interface builder here.
// This ONLY changes how it appears in interface builder, you will still need
// to setup the graph properly in your view controller for it to change in the
// actual application.
open override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
self.dataSource = self as? ScrollableGraphViewDataSource
self.shouldAnimateOnStartup = false
// Customise how the reference lines look in IB
let referenceLines = ReferenceLines()
self.addReferenceLines(referenceLines: referenceLines)
}
private func setup() {
clipsToBounds = true
isCurrentlySettingUp = true
// 0.
// Save the viewport, that is, the size of the rectangle through which we view the graph.
self.viewportWidth = self.frame.width
self.viewportHeight = self.frame.height
let viewport = CGRect(x: 0, y: 0, width: viewportWidth, height: viewportHeight)
// 1.
// Add the subviews we will use to draw everything.
// Add the drawing view in which we draw all the plots.
drawingView = UIView(frame: viewport)
drawingView.backgroundColor = backgroundFillColor
self.addSubview(drawingView)
// Add the x-axis labels view.
self.insertSubview(labelsView, aboveSubview: drawingView)
// 2.
// Calculate the total size of the graph, need to know this for the scrollview.
// Calculate the drawing frames
let numberOfDataPoints = dataSource?.numberOfPoints() ?? 0
totalGraphWidth = graphWidth(forNumberOfDataPoints: numberOfDataPoints)
self.contentSize = CGSize(width: totalGraphWidth, height: viewportHeight)
// Scrolling direction.
#if TARGET_INTERFACE_BUILDER
self.offsetWidth = 0
#else
if (direction == .rightToLeft) {
self.offsetWidth = self.contentSize.width - viewportWidth
}
// Otherwise start of all the way to the left.
else {
self.offsetWidth = 0
}
#endif
// Set the scrollview offset.
self.contentOffset.x = self.offsetWidth
// 3.
// Calculate the points that we will be able to see when the view loads.
let initialActivePointsInterval = calculateActivePointsInterval()
// 4.
// Add the plots to the graph, we need these to calculate the range.
while(queuedPlots.count > 0) {
if let plot = queuedPlots.dequeue() {
addPlotToGraph(plot: plot, activePointsInterval: initialActivePointsInterval)
}
}
// 5.
// Calculate the range for the points we can actually see.
#if TARGET_INTERFACE_BUILDER
self.range = (min: rangeMin, max: rangeMax)
#else
// Need to calculate the range across all plots to get the min and max for all plots.
if (shouldAdaptRange) { // This overwrites anything specified by rangeMin and rangeMax
let range = calculateRange(forActivePointsInterval: initialActivePointsInterval)
self.range = range
}
else {
self.range = (min: rangeMin, max: rangeMax) // just use what the user specified instead.
}
#endif
// If the graph was given all 0s as data, we can't use a range of 0->0, so make sure we have a sensible range at all times.
if (self.range.min == 0 && self.range.max == 0) {
self.range = (min: 0, max: rangeMax)
}
// 6.
// Add the reference lines, can only add this once we know the range.
if(referenceLines != nil) {
addReferenceViewDrawingView()
}
// 7.
// We're now done setting up, update the offsets and change the flag.
updateOffsetWidths()
isCurrentlySettingUp = false
// Set the first active points interval. These are the points that are visible when the view loads.
self.activePointsInterval = initialActivePointsInterval
}
// TODO in 4.1: Plot layer ordering.
// TODO in 4.1: Plot removal.
private func addDrawingLayersForPlots(inViewport viewport: CGRect) {
for plot in plots {
addSubLayers(layers: plot.layers(forViewport: viewport))
}
}
private func addSubLayers(layers: [ScrollableGraphViewDrawingLayer?]) {
for layer in layers {
if let layer = layer {
drawingView.layer.addSublayer(layer)
}
}
}
private func addReferenceViewDrawingView() {
guard let referenceLines = self.referenceLines else {
// We can want to add this if the settings arent nil.
return
}
if(referenceLines.shouldShowReferenceLines) {
let viewport = CGRect(x: 0, y: 0, width: viewportWidth, height: viewportHeight)
var referenceLineBottomMargin = bottomMargin
// Have to adjust the bottom line if we are showing data point labels (x-axis).
if(referenceLines.shouldShowLabels && referenceLines.dataPointLabelFont != nil) {
referenceLineBottomMargin += (referenceLines.dataPointLabelFont!.pointSize + referenceLines.dataPointLabelTopMargin + referenceLines.dataPointLabelBottomMargin)
}
referenceLineView?.removeFromSuperview()
referenceLineView = ReferenceLineDrawingView(
frame: viewport,
topMargin: topMargin,
bottomMargin: referenceLineBottomMargin,
referenceLineColor: referenceLines.referenceLineColor,
referenceLineThickness: referenceLines.referenceLineThickness,
referenceLineSettings: referenceLines)
referenceLineView?.set(range: self.range)
self.addSubview(referenceLineView!)
}
}
// If the view has changed we have to make sure we're still displaying the right data.
override open func layoutSubviews() {
super.layoutSubviews()
// while putting the view on the IB, we may get calls with frame too small
// if frame height is too small we won't be able to calculate zeroYPosition
// so make sure to proceed only if there is enough space
var availableGraphHeight = frame.height
availableGraphHeight = availableGraphHeight - topMargin - bottomMargin
if let referenceLines = referenceLines {
if(referenceLines.shouldShowLabels && referenceLines.dataPointLabelFont != nil) {
availableGraphHeight -= (referenceLines.dataPointLabelFont!.pointSize + referenceLines.dataPointLabelTopMargin + referenceLines.dataPointLabelBottomMargin)
}
}
if availableGraphHeight > 0 {
updateUI()
}
}
private func updateUI() {
// Make sure we have data, if don't, just get out. We can't do anything without any data.
guard let dataSource = dataSource else {
return
}
guard dataSource.numberOfPoints() > 0 else {
return
}
if (isInitialSetup) {
setup()
if(shouldAnimateOnStartup) {
startAnimations(withStaggerValue: 0.15)
}
// We're done setting up.
isInitialSetup = false
}
// Otherwise, the user is just scrolling and we just need to update everything.
else {
// Needs to update the viewportWidth and viewportHeight which is used to calculate which
// points we can actually see.
viewportWidth = self.frame.width
viewportHeight = self.frame.height
// If the scrollview has scrolled anywhere, we need to update the offset
// and move around our drawing views.
offsetWidth = self.contentOffset.x
updateOffsetWidths()
// Recalculate active points for this size.
// Recalculate range for active points.
let newActivePointsInterval = calculateActivePointsInterval()
self.previousActivePointsInterval = self.activePointsInterval
self.activePointsInterval = newActivePointsInterval
// If adaption is enabled we want to
if(shouldAdaptRange) {
// TODO: This is currently called every single frame...
// We need to only calculate the range if the active points interval has changed!
#if !TARGET_INTERFACE_BUILDER
let newRange = calculateRange(forActivePointsInterval: newActivePointsInterval)
self.range = newRange
#endif
}
}
}
private func updateOffsetWidths() {
drawingView.frame.origin.x = offsetWidth
drawingView.bounds.origin.x = offsetWidth
updateOffsetsForGradients(offsetWidth: offsetWidth)
referenceLineView?.frame.origin.x = offsetWidth
}
private func updateOffsetsForGradients(offsetWidth: CGFloat) {
guard let sublayers = drawingView.layer.sublayers else {
return
}
for layer in sublayers {
switch(layer) {
case let layer as GradientDrawingLayer:
layer.offset = offsetWidth
default: break
}
}
}
private func updateFrames() {
// Drawing view needs to always be the same size as the scrollview.
drawingView.frame.size.width = viewportWidth
drawingView.frame.size.height = viewportHeight
// Gradient should extend over the entire viewport
updateFramesForGradientLayers(viewportWidth: viewportWidth, viewportHeight: viewportHeight)
// Reference lines should extend over the entire viewport
referenceLineView?.set(viewportWidth: viewportWidth, viewportHeight: viewportHeight)
self.contentSize.height = viewportHeight
}
private func updateFramesForGradientLayers(viewportWidth: CGFloat, viewportHeight: CGFloat) {
guard let sublayers = drawingView.layer.sublayers else {
return
}
for layer in sublayers {
switch(layer) {
case let layer as GradientDrawingLayer:
layer.frame.size.width = viewportWidth
layer.frame.size.height = viewportHeight
default: break
}
}
}
// MARK: - Public Methods
// ######################
public func addPlot(plot: Plot) {
// If we aren't setup yet, save the plot to be added during setup.
if(isInitialSetup) {
enqueuePlot(plot)
}
// Otherwise, just add the plot directly.
else {
addPlotToGraph(plot: plot, activePointsInterval: self.activePointsInterval)
}
}
public func addReferenceLines(referenceLines: ReferenceLines) {
// If we aren't setup yet, just save the reference lines and the setup will take care of it.
if(isInitialSetup) {
self.referenceLines = referenceLines
}
// Otherwise, add the reference lines, reload everything.
else {
addReferenceLinesToGraph(referenceLines: referenceLines)
}
}
// Limitation: Can only be used when reloading the same number of data points!
public func reload() {
stopAnimations()
rangeDidChange()
updateUI()
updatePaths()
updateLabelsForCurrentInterval()
}
// The functions for adding plots and reference lines need to be able to add plots
// both before and after the graph knows its viewport/size.
// This needs to be the case so we can use it in interface builder as well as
// just adding it programatically.
// These functions add the plots and reference lines to the graph.
// The public functions will either save the plots and reference lines (in the case
// don't have the required viewport information) or add it directly to the graph
// (the case where we already know the viewport information).
private func addPlotToGraph(plot: Plot, activePointsInterval: CountableRange<Int>) {
plot.graphViewDrawingDelegate = self
self.plots.append(plot)
initPlot(plot: plot, activePointsInterval: activePointsInterval)
startAnimations(withStaggerValue: 0.15)
}
private func addReferenceLinesToGraph(referenceLines: ReferenceLines) {
self.referenceLines = referenceLines
addReferenceViewDrawingView()
updateLabelsForCurrentInterval()
}
private func initPlot(plot: Plot, activePointsInterval: CountableRange<Int>) {
#if !TARGET_INTERFACE_BUILDER
plot.setup() // Only init the animations for plots if we are not in IB
#endif
plot.createPlotPoints(numberOfPoints: dataSource!.numberOfPoints(), range: range) // TODO: removed forced unwrap
// If we are not animating on startup then just set all the plot positions to their respective values
if(!shouldAnimateOnStartup) {
let dataForInitialPoints = getData(forPlot: plot, andActiveInterval: activePointsInterval)
plot.setPlotPointPositions(forNewlyActivatedPoints: activePointsInterval, withData: dataForInitialPoints)
}
addSubLayers(layers: plot.layers(forViewport: currentViewport()))
}
private var queuedPlots: SGVQueue<Plot> = SGVQueue<Plot>()
private func enqueuePlot(_ plot: Plot) {
queuedPlots.enqueue(element: plot)
}
// MARK: - Private Methods
// #######################
// MARK: Layout Calculations
// #########################
private func calculateActivePointsInterval() -> CountableRange<Int> {
// Calculate the "active points"
let min = Int((offsetWidth) / dataPointSpacing)
let max = Int(((offsetWidth + viewportWidth)) / dataPointSpacing)
// Add and minus two so the path goes "off the screen" so we can't see where it ends.
let minPossible = 0
var maxPossible = 0
if let numberOfPoints = dataSource?.numberOfPoints() {
maxPossible = numberOfPoints - 1
}
let numberOfPointsOffscreen = 2
let actualMin = clamp(value: min - numberOfPointsOffscreen, min: minPossible, max: maxPossible)
let actualMax = clamp(value: max + numberOfPointsOffscreen, min: minPossible, max: maxPossible)
return actualMin..<actualMax.advanced(by: 1)
}
// Calculate the range across all plots.
private func calculateRange(forActivePointsInterval interval: CountableRange<Int>) -> (min: Double, max: Double) {
// This calculates the range across all plots for the active points.
// So the maximum will be the max of all plots, same goes for min.
var ranges = [(min: Double, max: Double)]()
for plot in plots {
let rangeForPlot = calculateRange(forPlot: plot, forActivePointsInterval: interval)
ranges.append(rangeForPlot)
}
let minOfRanges = min(ofAllRanges: ranges)
let maxOfRanges = max(ofAllRanges: ranges)
return (min: minOfRanges, max: maxOfRanges)
}
private func max(ofAllRanges ranges: [(min: Double, max: Double)]) -> Double {
var max: Double = ranges[0].max
for range in ranges {
if(range.max > max) {
max = range.max
}
}
return max
}
private func min(ofAllRanges ranges: [(min: Double, max: Double)]) -> Double {
var min: Double = ranges[0].min
for range in ranges {
if(range.min < min) {
min = range.min
}
}
return min
}
// Calculate the range for a single plot.
private func calculateRange(forPlot plot: Plot, forActivePointsInterval interval: CountableRange<Int>) -> (min: Double, max: Double) {
let dataForActivePoints = getData(forPlot: plot, andActiveInterval: interval)
// We don't have any active points, return defaults.
if(dataForActivePoints.count == 0) {
return (min: self.rangeMin, max: self.rangeMax)
}
else {
let range = calculateRange(for: dataForActivePoints)
return clean(range: range)
}
}
private func calculateRange<T: Collection>(for data: T) -> (min: Double, max: Double) where T.Iterator.Element == Double {
var rangeMin: Double = Double(Int.max)
var rangeMax: Double = Double(Int.min)
for dataPoint in data {
if (dataPoint > rangeMax) {
rangeMax = dataPoint
}
if (dataPoint < rangeMin) {
rangeMin = dataPoint
}
}
return (min: rangeMin, max: rangeMax)
}
private func clean(range: (min: Double, max: Double)) -> (min: Double, max: Double){
if(range.min == range.max) {
let min = shouldRangeAlwaysStartAtZero ? 0 : range.min
let max = range.max + 1
return (min: min, max: max)
}
else if (shouldRangeAlwaysStartAtZero) {
let min: Double = 0
var max: Double = range.max
// If we have all negative numbers and the max happens to be 0, there will cause a division by 0. Return the default height.
if(range.max == 0) {
max = rangeMax
}
return (min: min, max: max)
}
else {
return range
}
}
private func graphWidth(forNumberOfDataPoints numberOfPoints: Int) -> CGFloat {
let width: CGFloat = (CGFloat(numberOfPoints - 1) * dataPointSpacing) + (leftmostPointPadding + rightmostPointPadding)
return width
}
private func clamp<T: Comparable>(value:T, min:T, max:T) -> T {
if (value < min) {
return min
}
else if (value > max) {
return max
}
else {
return value
}
}
private func getData(forPlot plot: Plot, andActiveInterval activeInterval: CountableRange<Int>) -> [Double] {
var dataForInterval = [Double]()
for i in activeInterval.startIndex ..< activeInterval.endIndex {
let dataForIndexI = dataSource?.value(forPlot: plot, atIndex: i) ?? 0
dataForInterval.append(dataForIndexI)
}
return dataForInterval
}
private func getData(forPlot plot: Plot, andNewlyActivatedPoints activatedPoints: [Int]) -> [Double] {
var dataForActivatedPoints = [Double]()
for activatedPoint in activatedPoints {
let dataForActivatedPoint = dataSource?.value(forPlot: plot, atIndex: activatedPoint) ?? 0
dataForActivatedPoints.append(dataForActivatedPoint)
}
return dataForActivatedPoints
}
// MARK: Events
// ############
// If the active points (the points we can actually see) change, then we need to update the path.
private func activePointsDidChange() {
let deactivatedPoints = determineDeactivatedPoints()
let activatedPoints = determineActivatedPoints()
// The plots need to know which points became active and what their values
// are so the plots can display them properly.
if(!isInitialSetup) {
for plot in plots {
let newData = getData(forPlot: plot, andNewlyActivatedPoints: activatedPoints)
plot.setPlotPointPositions(forNewlyActivatedPoints: activatedPoints, withData: newData)
}
}
updatePaths()
if let ref = self.referenceLines {
if(ref.shouldShowLabels) {
let deactivatedLabelPoints = filterPointsForLabels(fromPoints: deactivatedPoints)
let activatedLabelPoints = filterPointsForLabels(fromPoints: activatedPoints)
updateLabels(deactivatedPoints: deactivatedLabelPoints, activatedPoints: activatedLabelPoints)
}
}
}
private func rangeDidChange() {
// If shouldAnimateOnAdapt is enabled it will kickoff any animations that need to occur.
if(shouldAnimateOnAdapt) {
startAnimations()
}
else {
// Otherwise we should simple just move the data to their positions.
for plot in plots {
let newData = getData(forPlot: plot, andActiveInterval: activePointsInterval)
plot.setPlotPointPositions(forNewlyActivatedPoints: intervalForActivePoints(), withData: newData)
}
}
referenceLineView?.set(range: range)
}
private func viewportDidChange() {
// We need to make sure all the drawing views are the same size as the viewport.
updateFrames()
// Basically this recreates the paths with the new viewport size so things are in sync, but only
// if the viewport has changed after the initial setup. Because the initial setup will use the latest
// viewport anyway.
if(!isInitialSetup) {
updatePaths()
// Need to update the graph points so they are in their right positions for the new viewport.
// Animate them into position if animation is enabled, but make sure to stop any current animations first.
#if !TARGET_INTERFACE_BUILDER
stopAnimations()
#endif
startAnimations()
// The labels will also need to be repositioned if the viewport has changed.
repositionActiveLabels()
}
}
// Returns the indices of any points that became inactive (that is, "off screen"). (No order)
private func determineDeactivatedPoints() -> [Int] {
let prevSet = Set(previousActivePointsInterval)
let currSet = Set(activePointsInterval)
let deactivatedPoints = prevSet.subtracting(currSet)
return Array(deactivatedPoints)
}
// Returns the indices of any points that became active (on screen). (No order)
private func determineActivatedPoints() -> [Int] {
let prevSet = Set(previousActivePointsInterval)
let currSet = Set(activePointsInterval)
let activatedPoints = currSet.subtracting(prevSet)
return Array(activatedPoints)
}
// Animations
private func startAnimations(withStaggerValue stagger: Double = 0) {
var pointsToAnimate = 0 ..< 0
#if !TARGET_INTERFACE_BUILDER
if (shouldAnimateOnAdapt || (isInitialSetup && shouldAnimateOnStartup)) {
pointsToAnimate = activePointsInterval
}
#endif
for plot in plots {
let dataForPointsToAnimate = getData(forPlot: plot, andActiveInterval: pointsToAnimate)
plot.startAnimations(forPoints: pointsToAnimate, withData: dataForPointsToAnimate, withStaggerValue: stagger)
}
}
private func stopAnimations() {
for plot in plots {
plot.dequeueAllAnimations()
}
}
// Labels
// TODO in 4.1: refactor all label adding & positioning code.
// Update any labels for any new points that have been activated and deactivated.
private func updateLabels(deactivatedPoints: [Int], activatedPoints: [Int]) {
guard let ref = self.referenceLines else {
return
}
// Disable any labels for the deactivated points.
for point in deactivatedPoints {
labelPool.deactivateLabel(forPointIndex: point)
}
// Grab an unused label and update it to the right position for the newly activated poitns
for point in activatedPoints {
let label = labelPool.activateLabel(forPointIndex: point)
label.text = (dataSource?.label(atIndex: point) ?? "")
label.textColor = ref.dataPointLabelColor
label.font = ref.dataPointLabelFont
label.sizeToFit()
// self.range.min is the current ranges minimum that has been detected
// self.rangeMin is the minimum that should be used as specified by the user
let rangeMin = (shouldAdaptRange) ? self.range.min : self.rangeMin
let position = calculatePosition(atIndex: point, value: rangeMin)
label.frame = CGRect(origin: CGPoint(x: position.x - label.frame.width / 2, y: position.y + ref.dataPointLabelTopMargin), size: label.frame.size)
let _ = labelsView.subviews.filter { $0.frame == label.frame }.map { $0.removeFromSuperview() }
labelsView.addSubview(label)
}
}
private func updateLabelsForCurrentInterval() {
// Have to ensure that the labels are added if we are supposed to be showing them.
if let ref = self.referenceLines {
if(ref.shouldShowLabels) {
var activatedPoints: [Int] = []
for i in activePointsInterval {
activatedPoints.append(i)
}
let filteredPoints = filterPointsForLabels(fromPoints: activatedPoints)
updateLabels(deactivatedPoints: filteredPoints, activatedPoints: filteredPoints)
}
}
}
private func repositionActiveLabels() {
guard let ref = self.referenceLines else {
return
}
for label in labelPool.activeLabels {
let rangeMin = (shouldAdaptRange) ? self.range.min : self.rangeMin
let position = calculatePosition(atIndex: 0, value: rangeMin)
label.frame.origin.y = position.y + ref.dataPointLabelTopMargin
}
}
private func filterPointsForLabels(fromPoints points:[Int]) -> [Int] {
guard let ref = self.referenceLines else {
return points
}
if(ref.dataPointLabelsSparsity == 1) {
return points
}
return points.filter({ $0 % ref.dataPointLabelsSparsity == 0 })
}
// MARK: - Drawing Delegate
// ########################
internal func calculatePosition(atIndex index: Int, value: Double) -> CGPoint {
// Set range defaults based on settings:
// self.range.min/max is the current ranges min/max that has been detected
// self.rangeMin/Max is the min/max that should be used as specified by the user
let rangeMax = (shouldAdaptRange) ? self.range.max : self.rangeMax
let rangeMin = (shouldAdaptRange) ? self.range.min : self.rangeMin
// y = the y co-ordinate in the view for the value in the graph
// value = the value on the graph for which we want to know its
// ( ( value - max ) ) corresponding location on the y axis in the view
// y = ( ( ----------- ) * graphHeight ) + topMargin t = the top margin
// ( ( min - max ) ) h = the height of the graph space without margins
// min = the range's current mininum
// max = the range's current maximum
// Calculate the position on in the view for the value specified.
var graphHeight = viewportHeight - topMargin - bottomMargin
if let ref = self.referenceLines {
if(ref.shouldShowLabels && ref.dataPointLabelFont != nil) {
graphHeight -= (ref.dataPointLabelFont!.pointSize + ref.dataPointLabelTopMargin + ref.dataPointLabelBottomMargin)
}
}
let x = (CGFloat(index) * dataPointSpacing) + leftmostPointPadding
let y = (CGFloat((value - rangeMax) / (rangeMin - rangeMax)) * graphHeight) + topMargin
return CGPoint(x: x, y: y)
}
internal func intervalForActivePoints() -> CountableRange<Int> {
return activePointsInterval
}
internal func rangeForActivePoints() -> (min: Double, max: Double) {
return range
}
internal func paddingForPoints() -> (leftmostPointPadding: CGFloat, rightmostPointPadding: CGFloat) {
return (leftmostPointPadding: leftmostPointPadding, rightmostPointPadding: rightmostPointPadding)
}
internal func currentViewport() -> CGRect {
return CGRect(x: 0, y: 0, width: viewportWidth, height: viewportHeight)
}
// Update any paths with the new path based on visible data points.
internal func updatePaths() {
zeroYPosition = calculatePosition(atIndex: 0, value: self.range.min).y
if let drawingLayers = drawingView.layer.sublayers {
for layer in drawingLayers {
if let layer = layer as? ScrollableGraphViewDrawingLayer {
// The bar layer needs the zero Y position to set the bottom of the bar
layer.zeroYPosition = zeroYPosition
// Need to make sure this is set in createLinePath
assert (layer.zeroYPosition > 0);
layer.updatePath()
}
}
}
}
}
// MARK: - ScrollableGraphView Settings Enums
// ##########################################
@objc public enum ScrollableGraphViewDirection : Int {
case leftToRight
case rightToLeft
}
// Simple queue data structure for keeping track of which
// plots have been added.
fileprivate class SGVQueue<T> {
var storage: [T]
public var count: Int {
get {
return storage.count
}
}
init() {
storage = [T]()
}
public func enqueue(element: T) {
storage.insert(element, at: 0)
}
public func dequeue() -> T? {
return storage.popLast()
}
}
// We have to be our own data source for interface builder.
#if TARGET_INTERFACE_BUILDER
public extension ScrollableGraphView : ScrollableGraphViewDataSource {
var numberOfDisplayItems: Int {
get {
return 30
}
}
var linePlotData: [Double] {
get {
return self.generateRandomData(numberOfDisplayItems, max: 100, shouldIncludeOutliers: false)
}
}
public func value(forPlot plot: Plot, atIndex pointIndex: Int) -> Double {
return linePlotData[pointIndex]
}
public func label(atIndex pointIndex: Int) -> String {
return "\(pointIndex)"
}
public func numberOfPoints() -> Int {
return numberOfDisplayItems
}
private func generateRandomData(_ numberOfItems: Int, max: Double, shouldIncludeOutliers: Bool = true) -> [Double] {
var data = [Double]()
for _ in 0 ..< numberOfItems {
var randomNumber = Double(arc4random()).truncatingRemainder(dividingBy: max)
if(shouldIncludeOutliers) {
if(arc4random() % 100 < 10) {
randomNumber *= 3
}
}
data.append(randomNumber)
}
return data
}
}
#endif
| mit | d514e86e2e1d2cc237658f9acdfbf617 | 36.406464 | 302 | 0.596251 | 5.169464 | false | false | false | false |
wj2061/ios7ptl-swift3.0 | ch21-Text/ScribbleLayout/ScribbleLayout/PTLScribbleLayoutManager.swift | 1 | 3739 | //
// PTLScribbleLayoutManager.swift
// ScribbleLayout
//
// Created by wj on 15/11/27.
// Copyright © 2015年 wj. All rights reserved.
//
import UIKit
class PTLScribbleLayoutManager: NSLayoutManager {
override func drawGlyphs(forGlyphRange glyphsToShow: NSRange, at origin: CGPoint) {
let characterRange = self.characterRange(forGlyphRange: glyphsToShow, actualGlyphRange: nil)
textStorage?.enumerateAttribute(PTLDefault.RedactStyleAttributeName, in: characterRange, options: [], using: { (value, attributeCharacterRange, stop) -> Void in
if let value = value as? Bool{
self.redactCharacterRange(attributeCharacterRange, ifTrue: value, atPoint:origin)
}
})
}
func redactCharacterRange(_ characterRange:NSRange,ifTrue:Bool,atPoint origin:CGPoint){
let glyphRange = self.glyphRange(forCharacterRange: characterRange, actualCharacterRange: nil)
if ifTrue{
let context = UIGraphicsGetCurrentContext()
context?.saveGState()
context?.translateBy(x: origin.x, y: origin.y)
UIColor.black.setStroke()
let container = textContainer(forGlyphAt: glyphRange.location, effectiveRange: nil)
enumerateEnclosingRects(forGlyphRange: glyphRange, withinSelectedGlyphRange: NSMakeRange(NSNotFound, 0), in: container!, using: { (rect , stop ) -> Void in
self.drawRedactionInRect(rect)
})
context?.restoreGState()
}else{
super.drawGlyphs(forGlyphRange: glyphRange, at: origin)
}
}
func drawRedactionInRect(_ rect:CGRect){
let path = UIBezierPath(rect: rect)
let minX = rect.minX
let minY = rect.minY
let maxX = rect.maxX
let maxY = rect.maxY
path.move(to: CGPoint(x: minX, y: minY))
path.addLine(to: CGPoint(x: maxX, y: maxY))
path.move(to: CGPoint(x: maxX, y: minY))
path.addLine(to: CGPoint(x: minX, y: maxY))
path.stroke()
}
override func drawBackground(forGlyphRange glyphsToShow: NSRange, at origin: CGPoint) {
super.drawGlyphs(forGlyphRange: glyphsToShow, at: origin)
let context = UIGraphicsGetCurrentContext()
let characterRange = self.characterRange(forGlyphRange: glyphsToShow, actualGlyphRange: nil)
textStorage?.enumerateAttribute(PTLDefault.HighlightColorAttributeName, in: characterRange, options: [], using: { (value , highlightedCharacterRange, stop) -> Void in
if let color = value as? UIColor{
self.highlightCharacterRange(highlightedCharacterRange, color: color, origin: origin, context: context!)
}
})
}
func highlightCharacterRange(_ highlightedCharacterRange:NSRange,color:UIColor,origin:CGPoint,context:CGContext){
context.saveGState()
color.setFill()
context.translateBy(x: origin.x, y: origin.y)
let highlightedGlyphRange = self.glyphRange(forCharacterRange: highlightedCharacterRange, actualCharacterRange: nil)
let container = self.textContainer(forGlyphAt: highlightedGlyphRange.location, effectiveRange: nil)
self.enumerateEnclosingRects(forGlyphRange: highlightedGlyphRange, withinSelectedGlyphRange: NSMakeRange(NSNotFound, 0), in: container!) { (rect , stop ) -> Void in
self.drawHighlightInRect(rect)
}
context.restoreGState()
}
func drawHighlightInRect(_ rect :CGRect){
let highlightRect = rect.insetBy(dx: -3, dy: -3)
UIRectFill(highlightRect)
UIBezierPath(ovalIn: highlightRect).stroke()
}
}
| mit | 0e493b23c061dfed7074bb91bf457fa8 | 41.942529 | 174 | 0.659529 | 4.789744 | false | false | false | false |
liutongchao/LCRefresh | Source/LCRefreshGifHeader.swift | 1 | 3123 | //
// LCRefreshGifHeader.swift
// LCCFD
//
// Created by 刘通超 on 2017/8/3.
// Copyright © 2017年 北京京师乐学教育科技有限公司. All rights reserved.
//
import UIKit
public final class LCRefreshGifHeader: LCBaseRefreshHeader {
public let image = UIImageView()
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public init(frame: CGRect) {
super.init(frame: frame)
configView()
}
public init(refreshBlock:@escaping (()->Void)) {
super.init(frame: CGRect(x: LCRefresh.Const.Header.X, y: LCRefresh.Const.Header.Y, width: LCRefresh.Const.Common.screenWidth, height: LCRefresh.Const.Header.height))
self.backgroundColor = UIColor.clear
self.refreshBlock = refreshBlock
configView()
}
public init(width:CGFloat ,refreshBlock:@escaping (()->Void)) {
super.init(frame: CGRect(x: LCRefresh.Const.Header.X, y: LCRefresh.Const.Header.Y, width:width , height: LCRefresh.Const.Header.height))
self.backgroundColor = UIColor.clear
self.refreshBlock = refreshBlock
configView()
}
func configView() {
addSubview(image)
image.frame = CGRect.init(x: 0, y: 0, width: 50, height: 50)
image.center = CGPoint.init(x: LCRefresh.Const.Common.screenWidth/2, y: LCRefresh.Const.Header.height/2)
image.contentMode = .scaleAspectFit
let bundle = "LCRefresh.bundle/"
let imagesStr = ["huhu_1.png","huhu_2.png","huhu_3.png","huhu_4.png","huhu_5.png","huhu_6.png","huhu_7.png","huhu_8.png"]
var images = [UIImage]()
for item in imagesStr {
if let temp1 = UIImage.init(named: bundle+item) {
images.append(temp1)
}else{
if let temp2 = UIImage.init(named: "Frameworks/LCRefresh.framework/"+bundle+item) {
images.append(temp2)
}
}
}
image.animationImages = images
image.animationDuration = 0.5
}
public override func setRefreshStatus(status: LCRefreshHeaderStatus) {
refreshStatus = status
switch status {
case .normal:
setNomalStatus()
break
case .waitRefresh:
setWaitRefreshStatus()
break
case .refreshing:
setRefreshingStatus()
break
case .end:
setEndStatus()
break
}
}
}
extension LCRefreshGifHeader{
/** 各种状态切换 */
func setNomalStatus() {
if image.isAnimating {
image.stopAnimating()
}
}
func setWaitRefreshStatus() {
if !image.isAnimating {
image.startAnimating()
}
}
func setRefreshingStatus() {
if !image.isAnimating {
image.startAnimating()
}
}
func setEndStatus() {
if image.isAnimating {
image.stopAnimating()
}
}
}
| mit | 187b602230442eb019fcbdadc0e78ba1 | 27.201835 | 173 | 0.572544 | 4.188011 | false | false | false | false |
letvargo/LVGSwiftSystemSoundServices | Source/SystemSound.swift | 1 | 5174 | //
// SystemsSound.swift
// Pods
//
// Created by doof nugget on 4/24/16.
//
//
import AudioToolbox
import LVGUtilities
/// A wrapper around AudioToolbox's SystemSoundID.
open class SystemSound {
// sound is private so only certain SystemSoundType methods can be exposed
// through SystemSound's public interface.
fileprivate let sound: SystemSoundID
// Plays the delegate's didFinishPlaying(_:) method.
fileprivate lazy var systemSoundCompletionProc: AudioServicesSystemSoundCompletionProc = {
_, inClientData in
guard let inClientData = inClientData else { return }
let systemSound: SystemSound = fromPointerConsume(inClientData)
systemSound.delegate?.didFinishPlaying(systemSound)
}
/**
Initialize a `SystemSound` using an `NSURL`.
- parameter url: The url of the sound file that will be played.
- throws: `SystemSoundError`
*/
// MARK: Initializing a SystemSound
public init(url: URL) throws {
self.sound = try SystemSoundID(url: url)
}
// MARK: The delegate property
/**
A `delegate` with a `didFinsishPlaying(_:)` method that is called
when the system sound finishes playing.
*/
open weak var delegate: SystemSoundDelegate? {
didSet {
self.sound.removeCompletion()
if let _ = self.delegate {
do {
try self.sound.addCompletion(
inClientData: UnsafeMutableRawPointer(mutating: toPointerRetain(self)),
inCompletionRoutine: systemSoundCompletionProc)
} catch {
print("\(error)")
}
}
}
}
// MARK: Playing Sounds and Alerts
/// Play the system sound assigned to the `soundID` property.
open func play() {
self.sound.play()
}
/**
Play the system sound assigned to the `soundID` property as an alert.
On `iOS` this may cause the device to vibrate. The actual sound played
is dependent on the device.
On `OS X` this may cause the screen to flash.
*/
open func playAsAlert() {
self.sound.playAsAlert()
}
#if os(iOS)
/// Cause the phone to vibrate.
open static func vibrate() {
SystemSoundID.vibrate()
}
#endif
#if os(OSX)
/// Play the system-defined alert sound on OS X.
public static func playSystemAlert() {
SystemSoundID.playSystemAlert()
}
/// Flash the screen.
public static func flashScreen() {
SystemSoundID.flashScreen()
}
#endif
// MARK: Working with Properties
/**
Get the value of the `.IsUISound` property.
If `true`, the system sound respects the user setting in the Sound Effects
preference and the sound will be silent when the user turns off sound effects.
The default value is `true`.
- throws: `SystemSoundError`
- returns: A `Bool` that indicates whether or not the sound will play
when the user has turned of sound effects in the Sound Effects preferences.
*/
open func isUISound() throws -> Bool {
return try self.sound.isUISound()
}
/**
Set the value of the `.IsUISound` property.
If `true`, the system sound respects the user setting in the Sound Effects
preference and the sound will be silent when the user turns off sound effects.
The default value is `true`.
- parameter value: The `Bool` value that is to be set.
- throws: `SystemSoundError`
*/
open func isUISound(_ value: Bool) throws {
try self.sound.isUISound(value)
}
/**
Get the value of the `.CompletePlaybackIfAppDies` property.
If `true`, the system sound will finish playing even if the application
dies unexpectedly.
The default value is `true`.
- throws: `SystemSoundError`
*/
open func completePlaybackIfAppDies() throws -> Bool {
return try self.sound.completePlaybackIfAppDies()
}
/**
Set the value of the `.CompletePlaybackIfAppDies` property.
If `true`, the system sound will finish playing even if the application
dies unexpectedly.
The default value is `true`.
- parameter value: The `Bool` value that is to be set.
- throws: `SystemSoundError`
*/
open func completePlaybackIfAppDies(_ value: Bool) throws {
try self.sound.completePlaybackIfAppDies(value)
}
// Dispose of the sound during deinitialization.
deinit {
do {
try self.sound.dispose()
} catch {
print("\(error)")
}
}
}
| mit | eb08a1a418742ec1fc8484ed18fc29e3 | 23.29108 | 95 | 0.566873 | 5.023301 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Rocket.Chat/Models/Mapping/AttachmentModelMapping.swift | 1 | 2859 | //
// AttachmentModelMapping.swift
// Rocket.Chat
//
// Created by Rafael Kellermann Streit on 16/01/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import Foundation
import SwiftyJSON
import RealmSwift
extension AttachmentField: ModelMappeable {
func map(_ values: JSON, realm: Realm?) {
self.short = values["short"].boolValue
self.title = values["title"].stringValue
self.value = values["value"].stringValue
}
}
extension Attachment: ModelMappeable {
func map(_ values: JSON, realm: Realm?) {
if self.identifier == nil {
self.identifier = values.rawString()?.md5() ?? String.random(30)
}
if let authorName = values["author_name"].string {
self.title = "\(authorName)"
}
if let title = values["title"].string {
self.title = title.removingNewLines()
}
if let titleLink = values["title_link"].string {
self.titleLink = titleLink
}
self.collapsed = values["collapsed"].bool ?? false
self.text = values["text"].string
self.descriptionText = values["description"].string
self.thumbURL = values["thumb_url"].string
self.color = values["color"].string
self.titleLinkDownload = values["title_link_download"].boolValue
if let imageURL = values["image_url"].string {
if imageURL.contains("https://") || imageURL.contains("http://") {
self.imageURL = imageURL
} else {
self.imageURL = encode(url: imageURL)
}
}
self.imageType = values["image_type"].string
self.imageSize = values["image_size"].int ?? 0
self.audioURL = encode(url: values["audio_url"].string)
self.audioType = values["audio_type"].string
self.audioSize = values["audio_size"].int ?? 0
self.videoURL = encode(url: values["video_url"].string)
self.videoType = values["video_type"].string
self.videoSize = values["video_size"].int ?? 0
// Mentions
if let fields = values["fields"].array {
self.fields.removeAll()
for field in fields {
let obj = AttachmentField()
obj.map(field, realm: realm)
self.fields.append(obj)
}
}
}
fileprivate func encode(url: String?) -> String? {
guard let url = url else { return nil }
let parts = url.components(separatedBy: "/")
var encoded: [String] = []
for part in parts {
if let string = part.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) {
encoded.append(string)
} else {
encoded.append(part)
}
}
return encoded.joined(separator: "/")
}
}
| mit | eeb6661845154689c5c59f5414313ce9 | 29.084211 | 96 | 0.571728 | 4.493711 | false | false | false | false |
MaxHasADHD/TraktKit | Common/Models/Users/UserStats.swift | 1 | 2375 | //
// UserStats.swift
// TraktKit
//
// Created by Maximilian Litteral on 8/12/17.
// Copyright © 2017 Maximilian Litteral. All rights reserved.
//
import Foundation
public struct UserStats: Codable, Hashable {
public let movies: Movies
public let shows: Shows
public let seasons: Seasons
public let episodes: Episodes
public let network: Network
public let ratings: UserStatsRatingsDistribution
public struct Movies: Codable, Hashable {
public let plays: Int
public let watched: Int
public let minutes: Int
public let collected: Int
public let ratings: Int
public let comments: Int
}
public struct Shows: Codable, Hashable {
public let watched: Int
public let collected: Int
public let ratings: Int
public let comments: Int
}
public struct Seasons: Codable, Hashable {
public let ratings: Int
public let comments: Int
}
public struct Episodes: Codable, Hashable {
public let plays: Int
public let watched: Int
public let minutes: Int
public let collected: Int
public let ratings: Int
public let comments: Int
}
public struct Network: Codable, Hashable {
public let friends: Int
public let followers: Int
public let following: Int
}
public struct UserStatsRatingsDistribution: Codable, Hashable {
public let total: Int
public let distribution: Distribution
public struct Distribution: Codable, Hashable {
public let one: Int
public let two: Int
public let three: Int
public let four: Int
public let five: Int
public let six: Int
public let seven: Int
public let eight: Int
public let nine: Int
public let ten: Int
enum CodingKeys: String, CodingKey {
case one = "1"
case two = "2"
case three = "3"
case four = "4"
case five = "5"
case six = "6"
case seven = "7"
case eight = "8"
case nine = "9"
case ten = "10"
}
}
}
}
| mit | 296f1154420affe8bb4e998fd4d378b2 | 26.929412 | 67 | 0.551811 | 5.029661 | false | false | false | false |
ben-ng/swift | stdlib/public/SDK/Foundation/String.swift | 1 | 1958 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
//===----------------------------------------------------------------------===//
// New Strings
//===----------------------------------------------------------------------===//
//
// Conversion from NSString to Swift's native representation
//
extension String {
public init(_ cocoaString: NSString) {
self = String(_cocoaString: cocoaString)
}
}
extension String : _ObjectiveCBridgeable {
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSString {
// This method should not do anything extra except calling into the
// implementation inside core. (These two entry points should be
// equivalent.)
return unsafeBitCast(_bridgeToObjectiveCImpl() as AnyObject, to: NSString.self)
}
public static func _forceBridgeFromObjectiveC(
_ x: NSString,
result: inout String?
) {
result = String(x)
}
public static func _conditionallyBridgeFromObjectiveC(
_ x: NSString,
result: inout String?
) -> Bool {
self._forceBridgeFromObjectiveC(x, result: &result)
return result != nil
}
public static func _unconditionallyBridgeFromObjectiveC(
_ source: NSString?
) -> String {
// `nil` has historically been used as a stand-in for an empty
// string; map it to an empty string.
if _slowPath(source == nil) { return String() }
return String(source!)
}
}
extension String: CVarArg {}
| apache-2.0 | 96f38de6320907ad333a654395fde376 | 30.079365 | 83 | 0.585802 | 5.207447 | false | false | false | false |
radical-experiments/AIMES-Swift | viveks_workflow/512/vivek.swift | 2 | 6134 |
type file;
int N = toInt(arg("N", "512")); # 64 ... 2048
int chunk_size = 64; # chunksize for stage 3
int n_chunks = 8; # number of chunks
int verb = 1;
# -----------------------------------------------------------------------------
#
# Stage 1
#
app (file output_1_1_i,
file output_1_2_i,
file output_1_3_i) stage_1 (int i,
file input_shared_1_1,
file input_shared_1_2,
file input_shared_1_3,
file input_shared_1_4,
file input_shared_1_5)
{
stage_1_exe i filename(input_shared_1_1)
filename(input_shared_1_2)
filename(input_shared_1_3)
filename(input_shared_1_4)
filename(input_shared_1_5);
}
file input_shared_1_1 <"input_shared_1_1.txt">;
file input_shared_1_2 <"input_shared_1_2.txt">;
file input_shared_1_3 <"input_shared_1_3.txt">;
file input_shared_1_4 <"input_shared_1_4.txt">;
file input_shared_1_5 <"input_shared_1_5.txt">;
file output_1_1[];
file output_1_2[];
file output_1_3[];
foreach i in [1:N] {
file output_1_1_i <single_file_mapper; file=strcat("output_1_1_",i,".txt")>;
file output_1_2_i <single_file_mapper; file=strcat("output_1_2_",i,".txt")>;
file output_1_3_i <single_file_mapper; file=strcat("output_1_3_",i,".txt")>;
if (verb == 1) {
# trace("stage 1");
# trace(filename(input_shared_1_1));
# trace(filename(input_shared_1_2));
# trace(filename(input_shared_1_3));
# trace(filename(input_shared_1_4));
# trace(filename(input_shared_1_5));
}
(output_1_1_i,
output_1_2_i,
output_1_3_i) = stage_1(i,
input_shared_1_1,
input_shared_1_2,
input_shared_1_3,
input_shared_1_4,
input_shared_1_5);
output_1_1[i] = output_1_1_i;
output_1_2[i] = output_1_2_i;
output_1_3[i] = output_1_3_i;
}
# -----------------------------------------------------------------------------
#
# Stage 2
#
app (file output_2_1_i,
file output_2_2_i,
file output_2_3_i,
file output_2_4_i) stage_2 (int i,
file input_shared_1_3,
file input_shared_1_4,
file output_1_1_i)
{
stage_2_exe i filename(input_shared_1_3)
filename(input_shared_1_4)
filename(output_1_1_i);
}
file output_2_1[];
file output_2_2[];
file output_2_3[];
file output_2_4[];
foreach i in [1:N] {
file output_2_1_i <single_file_mapper; file=strcat("output_2_1_",i,".txt")>;
file output_2_2_i <single_file_mapper; file=strcat("output_2_2_",i,".txt")>;
file output_2_3_i <single_file_mapper; file=strcat("output_2_3_",i,".txt")>;
file output_2_4_i <single_file_mapper; file=strcat("output_2_4_",i,".txt")>;
if (verb == 1) {
# trace("stage 2");
# trace(filename(input_shared_1_3));
# trace(filename(input_shared_1_4));
# trace(filename(output_1_1[i]));
}
(output_2_1_i,
output_2_2_i,
output_2_3_i,
output_2_4_i) = stage_2(i,
input_shared_1_3,
input_shared_1_4,
output_1_1[i]);
output_2_1[i] = output_2_1_i;
output_2_2[i] = output_2_2_i;
output_2_3[i] = output_2_3_i;
output_2_4[i] = output_2_4_i;
}
# -----------------------------------------------------------------------------
#
# Stage 3
#
app (file[] output_3_1) stage_3 (int chunk,
int chunksize,
file input_shared_1_3,
file[] output_2_2)
{
# N cores
stage_3_exe chunk
chunksize
filename(input_shared_1_3)
@output_2_2;
}
# we run stage_3 in chunks of C cores each, so we nee dto subdivide the file
# list into such chunks
# string[] output_3_1_s; # output files for all chunks
# foreach i in [1:N] {
# output_3_1_s[i] = strcat("output_3_1_",i,".txt");
# }
file[] output_3_1;
# over all chunks
foreach c in [0:(n_chunks-1)] {
# file lists for chunk
file[] output_2_2_c; # input files for this chunk
string[] output_3_1_c_s; # output files for this chunk
# over all chunk elements
foreach i in [1:chunk_size] {
# global index
int j = c*chunk_size + i;
output_2_2_c[i] = output_2_2[j];
output_3_1_c_s[i] = strcat("output_3_1_",j,".txt");
}
# convert into file sets
file[] output_3_1_c <array_mapper; files=output_3_1_c_s>;
# run this chunk
if (verb == 1) {
string tmp = sprintf("stage 3: %s : %s : %s -> %s", c,
filename(input_shared_1_3),
strjoin(output_2_2_c, " "),
strjoin(output_3_1_c_s, " "));
trace(tmp);
}
output_3_1_c = stage_3(c, chunk_size,
input_shared_1_3,
output_2_2_c);
# now merge the received files from the chunk into the global thing
foreach i in [1:chunk_size] {
# global index
int j = c*chunk_size + i;
output_3_1[j] = output_3_1_c[i];
}
}
# -----------------------------------------------------------------------------
#
# Stage 4
#
app (file output_4_1) stage_4 (file input_shared_1_5,
file[] output_3_1)
{
# 1 core
stage_4_exe filename(input_shared_1_5)
@output_3_1;
}
if (1 == 1) {
if (verb == 1) {
trace("stage 4");
trace(filename(input_shared_1_5));
trace(@output_3_1);
}
file output_4_1 <"output_4_1.txt">;
output_4_1 = stage_4(input_shared_1_5,
output_3_1);
}
# -----------------------------------------------------------------------------
| mit | d27a1fa5175cfa3be31b0b78f46ea196 | 27.663551 | 80 | 0.456309 | 3.199791 | false | false | false | false |
CoderXiaoming/Ronaldo | SaleManager/SaleManager/ComOperation/Model/SAMProductRankListModel.swift | 1 | 406 | //
// SAMProductRankListModel.swift
// SaleManager
//
// Created by apple on 17/1/2.
// Copyright © 2017年 YZH. All rights reserved.
//
import UIKit
class SAMProductRankListModel: NSObject {
///客户名称
var CGUnitName = "" {
didSet{
CGUnitName = ((CGUnitName == "") ? "---" : CGUnitName)
}
}
///客户型号销售数量汇总
var countM = 0.0
}
| apache-2.0 | 18fa4711703ff63a84362a86414cab20 | 16.857143 | 66 | 0.570667 | 3.07377 | false | false | false | false |
KrishMunot/swift | test/SILOptimizer/globalopt_global_propagation.swift | 6 | 7229 | // RUN: %target-swift-frontend -O -emit-sil %s | FileCheck %s
// RUN: %target-swift-frontend -O -wmo -emit-sil %s | FileCheck -check-prefix=CHECK-WMO %s
// Check that values of internal and private global variables, which are provably assigned only
// once, are propagated into their uses and enable further optimizations like constant
// propagation, simplifications, etc.
// Define some global variables.
public var VD = 3.1415
public var VI = 100
private var PVD = 3.1415
private var PVI = 100
private var PVIAssignTwice = 1
private var PVITakenAddress = 1
internal var IVD = 3.1415
internal var IVI = 100
internal var IVIAssignTwice = 1
internal var IVITakenAddress = 1
// Taking the address of a global should prevent from performing the propagation of its value.
@inline(never)
@_semantics("optimize.sil.never")
public func takeInout<T>(_ x: inout T) {
}
// Compiler should detect that we assign a global here as well and prevent a global optimization.
public func assignSecondTime() {
PVIAssignTwice = 2
IVIAssignTwice = 2
}
// Having multiple assignments to a global should prevent from performing the propagation of its value.
// Loads from private global variables can be removed,
// because they cannot be changed outside of this source file.
// CHECK-LABEL: sil [noinline] @_TF28globalopt_global_propagation30test_private_global_var_doubleFT_Sd
// CHECK: bb0:
// CHECK-NOT: global_addr
// CHECK: float_literal
// CHECK: struct
// CHECK: return
@inline(never)
public func test_private_global_var_double() -> Double {
return PVD + 1.0
}
// Loads from private global variables can be removed,
// because they cannot be changed outside of this source file.
// CHECK-LABEL: sil [noinline] @_TF28globalopt_global_propagation27test_private_global_var_intFT_Si
// CHECK: bb0:
// CHECK-NOT: global_addr
// CHECK: integer_literal
// CHECK: struct
// CHECK: return
@inline(never)
public func test_private_global_var_int() -> Int {
return PVI + 1
}
// Loads from internal global variables can be removed if this is a WMO compilation, because
// they cannot be changed outside of this module.
// CHECK-WMO-LABEL: sil [noinline] @_TF28globalopt_global_propagation31test_internal_global_var_doubleFT_Sd
// CHECK-WMO: bb0:
// CHECK-WMO-NOT: global_addr
// CHECK-WMO: float_literal
// CHECK-WMO: struct
// CHECK-WMO: return
@inline(never)
public func test_internal_global_var_double() -> Double {
return IVD + 1.0
}
// Loads from internal global variables can be removed if this is a WMO compilation, because
// they cannot be changed outside of this module.
// CHECK-WMO-LABEL: sil [noinline] @_TF28globalopt_global_propagation28test_internal_global_var_intFT_Si
// CHECK_WMO: bb0:
// CHECK-WMO-NOT: global_addr
// CHECK-WMO: integer_literal
// CHECK-WMO: struct
// CHECK_WMO: return
@inline(never)
public func test_internal_global_var_int() -> Int {
return IVI + 1
}
// Loads from public global variables cannot be removed, because their values could be changed elsewhere.
// CHECK-WMO-LABEL: sil [noinline] @_TF28globalopt_global_propagation29test_public_global_var_doubleFT_Sd
// CHECK-WMO: bb0:
// CHECK-WMO-NEXT: global_addr
// CHECK-WMO-NEXT: struct_element_addr
// CHECK-WMO-NEXT: load
@inline(never)
public func test_public_global_var_double() -> Double {
return VD + 1.0
}
// Loads from public global variables cannot be removed, because their values could be changed elsewhere.
// CHECK-LABEL: sil [noinline] @_TF28globalopt_global_propagation26test_public_global_var_intFT_Si
// CHECK: bb0:
// CHECK-NEXT: global_addr
// CHECK-NEXT: struct_element_addr
// CHECK-NEXT: load
@inline(never)
public func test_public_global_var_int() -> Int {
return VI + 1
}
// Values of globals cannot be propagated as there are multiple assignments to it.
// CHECK-WMO-LABEL: sil [noinline] @_TF28globalopt_global_propagation57test_internal_and_private_global_var_with_two_assignmentsFT_Si
// CHECK-WMO: bb0:
// CHECK-WMO: global_addr
// CHECK-WMO: global_addr
// CHECK-WMO: struct_element_addr
// CHECK-WMO: load
// CHECK-WMO: struct_element_addr
// CHECK-WMO: load
// CHECK-WMO: return
@inline(never)
public func test_internal_and_private_global_var_with_two_assignments() -> Int {
return IVIAssignTwice + PVIAssignTwice
}
// Values of globals cannot be propagated as their address was taken and
// therefore their value could have been changed elsewhere.
// CHECK-WMO-LABEL: sil @_TF28globalopt_global_propagation24test_global_take_addressFT_Si
// CHECK-WMO: bb0:
// CHECK-WMO: global_addr
// CHECK-WMO: global_addr
// CHECK-WMO: struct_element_addr
// CHECK-WMO: load
// CHECK-WMO: struct_element_addr
// CHECK-WMO: load
// CHECK-WMO: return
public func test_global_take_address() -> Int {
takeInout(&PVITakenAddress)
takeInout(&IVITakenAddress)
return IVITakenAddress + PVITakenAddress
}
struct IntWrapper1 {
let val: Int
}
struct IntWrapper2 {
let val: IntWrapper1
}
struct IntWrapper3 {
let val: IntWrapper2
}
struct IntWrapper4 {
let val: IntWrapper2
let val2: IntWrapper1
}
let IW3 = IntWrapper3(val: IntWrapper2(val: IntWrapper1(val: 10)))
let IW4 = IntWrapper4(val: IntWrapper2(val: IntWrapper1(val: 10)), val2: IntWrapper1(val: 100))
// Test accessing single Int wrapped into multiple structs, where each struct has only one field.
// CHECK-LABEL: sil [noinline] @_TF28globalopt_global_propagation34test_let_struct_wrapped_single_intFT_Si
// CHECK: bb0:
// CHECK-NOT: global_addr
// CHECK: integer_literal
// CHECK: struct
// CHECK: return
// CHECK-WMO-LABEL: sil [noinline] @_TF28globalopt_global_propagation34test_let_struct_wrapped_single_intFT_Si
// CHECK-WMO: bb0:
// CHECK-WMO-NOT: global_addr
// CHECK-WMO: integer_literal
// CHECK-WMO: struct
// CHECK-WMO: return
@inline(never)
public func test_let_struct_wrapped_single_int() -> Int {
return IW3.val.val.val + 1
}
// Test accessing multiple Int fields wrapped into multiple structs, where each struct may have
// multiple fields.
// CHECK-LABEL: sil [noinline] @_TF28globalopt_global_propagation37test_let_struct_wrapped_multiple_intsFT_Si
// CHECK: bb0:
// CHECK-NOT: global_addr
// CHECK: integer_literal
// CHECK: struct
// CHECK: return
// CHECK-WMO-LABEL: sil [noinline] @_TF28globalopt_global_propagation37test_let_struct_wrapped_multiple_intsFT_Si
// CHECK-WMO: bb0:
// CHECK-WMO-NOT: global_addr
// CHECK-WMO: integer_literal
// CHECK-WMO: struct
// CHECK-WMO: return
@inline(never)
public func test_let_struct_wrapped_multiple_ints() -> Int {
return IW4.val.val.val + IW4.val2.val + 1
}
let IT1 = ((10, 20), 30, 40)
let IT2 = (100, 200, 300)
// Test accessing multiple Int fields wrapped into multiple tuples, where each tuple may have
// multiple fields.
// CHECK-LABEL: sil [noinline] @_TF28globalopt_global_propagation27test_let_tuple_wrapped_intsFT_Si
// CHECK: bb0:
// CHECK-NOT: global_addr
// CHECK: integer_literal
// CHECK: struct
// CHECK: return
// CHECK-WMO-LABEL: sil [noinline] @_TF28globalopt_global_propagation27test_let_tuple_wrapped_intsFT_Si
// CHECK-WMO: bb0:
// CHECK-WMO-NOT: global_addr
// CHECK-WMO: integer_literal
// CHECK-WMO: struct
// CHECK-WMO: return
@inline(never)
public func test_let_tuple_wrapped_ints() -> Int {
return IT1.0.0 + IT2.1
}
| apache-2.0 | 5ea185eb48032fbbe8916cf3feccc700 | 30.567686 | 133 | 0.738138 | 3.36389 | false | true | false | false |
PayPal-Opportunity-Hack-Chennai-2015/No-Food-Waste | ios/NoFoodWaster/NoFoodWaster/DonateViewController.swift | 2 | 6873 | //
// DonateViewController.swift
// NoFoodWaste
//
// Created by Ravi Shankar on 28/11/15.
// Copyright © 2015 Ravi Shankar. All rights reserved.
//
import UIKit
import MapKit
class DonateViewController: UIViewController {
let locationManager = CLLocationManager()
var coordinate: CLLocationCoordinate2D?
var phone:String?
var name:String?
var volunteer:Bool?
var activeField:UITextField?
let donationStatus = "open"
@IBOutlet weak var addressTextView: UITextView!
@IBOutlet weak var foodSegmentControl: UISegmentedControl!
@IBOutlet weak var locSwitch: UISwitch!
@IBOutlet weak var serves: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil);
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil)
if let coordinate = coordinate {
locSwitch.on = false
getPlaceName(coordinate.latitude, longitude: coordinate.longitude)
} else {
getCurrentLocation()
}
serves.delegate = self
populateDefaults()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
navigationItem.title = "Donate Food Now"
}
override func viewDidAppear(animated: Bool) {
super.viewWillAppear(true)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
navigationItem.title = nil
}
func populateDefaults() {
let userDefault = NSUserDefaults(suiteName: "register")
name = userDefault?.objectForKey("name") as? String
phone = userDefault?.objectForKey("phone") as? String
volunteer = userDefault?.boolForKey("isVolunteer")
}
func getPlaceName(latitude: Double, longitude: Double) {
let coordinates = CLLocation(latitude: latitude, longitude: longitude)
coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
CLGeocoder().reverseGeocodeLocation(coordinates, completionHandler: {(placemarks, error)->Void in
if (error != nil) {
print("Reverse geocoder failed with error" + error!.localizedDescription)
return
}
if placemarks!.count > 0 {
let pm = placemarks![0]
self.displayLocationInfo(pm)
} else {
print("Problem with the data received from geocoder")
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
view.endEditing(true)
}
func keyboardWillShow(notification: NSNotification) {
if ((activeField?.isKindOfClass(UITextField)) == nil) {
self.view.frame.origin.y -= 160
}
}
func keyboardWillHide(notification: NSNotification) {
if ((activeField?.isKindOfClass(UITextField)) == nil) {
self.view.frame.origin.y += 160
}
activeField = nil
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self);
}
@IBAction func deliver(sender: AnyObject) {
let selectedIndex = foodSegmentControl.selectedSegmentIndex
let foodType = foodSegmentControl.titleForSegmentAtIndex(selectedIndex)
let serviceMgr = ServiceManager()
serviceMgr.donateFood(phone!, status: donationStatus, foodType:foodType!, quantity: serves.text!, latitude: (coordinate?.latitude)!, longitude: (coordinate?.longitude)!, address: addressTextView.text)
}
}
extension DonateViewController: CLLocationManagerDelegate {
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
coordinate = manager.location?.coordinate
CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)->Void in
if (error != nil) {
print("Reverse geocoder failed with error" + error!.localizedDescription)
return
}
if placemarks!.count > 0 {
let pm = placemarks![0]
self.displayLocationInfo(pm)
} else {
print("Problem with the data received from geocoder")
}
})
}
func displayLocationInfo(placemark: CLPlacemark?) {
if let containsPlacemark = placemark {
//stop updating location to save battery life
locationManager.stopUpdatingLocation()
let locality = (containsPlacemark.locality != nil) ? containsPlacemark.locality : ""
let postalCode = (containsPlacemark.postalCode != nil) ? containsPlacemark.postalCode : ""
let administrativeArea = (containsPlacemark.administrativeArea != nil) ? containsPlacemark.administrativeArea : ""
let country = (containsPlacemark.country != nil) ? containsPlacemark.country : ""
let address = locality! + ", " + administrativeArea! + ", " + postalCode! + ", " + country!
addressTextView.text = address
}
}
@IBAction func currentLocation(sender: AnyObject) {
let locationSwitch = sender as! UISwitch
if locationSwitch.on {
getCurrentLocation()
} else {
mapLocation()
}
}
func getCurrentLocation() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
func mapLocation() {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewControllerWithIdentifier("MapLocationViewController")
navigationController?.pushViewController(controller, animated: true)
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("Error while updating location " + error.localizedDescription)
}
}
extension DonateViewController: UITextFieldDelegate {
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
activeField = textField
return true
}
}
| apache-2.0 | e36bf62a11d4f74c43c0a34e1fe912c1 | 32.521951 | 208 | 0.629075 | 5.769941 | false | false | false | false |
adform/adform-ios-sdk | sample/sample/InlineAdsCollectionViewController.swift | 1 | 4380 | //
// InlineAdsCollectionViewController.swift
// sample
//
// Created by Vladas Drejeris on 17/11/2017.
// Copyright © 2017 adform. All rights reserved.
//
import UIKit
private let reuseIdentifier = "Cell"
private let footerReuseIdentifier = "Footer"
class InlineAdsCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, AFAdInlineDelegate {
lazy var months: [String] = {
let dateFormatter = DateFormatter()
let dates = dateFormatter.monthSymbols!
return dates
}()
var masterTag: Int {
return 142493
}
var footerSize: CGSize = CGSize(width: 1, height: 1)
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.register(BannerFooter.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: footerReuseIdentifier)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 3
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 4
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! MonthCell
let month = months[indexPath.section * 4 + indexPath.row]
cell.set(title: month)
return cell
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let footer = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: footerReuseIdentifier, for: indexPath) as! BannerFooter
footer.loadAd(masterTag: masterTag, presenter: self, delegate: self)
return footer
}
// MARK: UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let dimension = collectionView.bounds.width - 60
return CGSize(width: dimension, height: dimension)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
return footerSize
}
func adInlineWillShow(_ adInline: AFAdInline) {
footerSize = adInline.adSize
UIView.animate(withDuration: 0.3) {
self.collectionView?.collectionViewLayout.invalidateLayout()
}
}
}
class MonthCell: UICollectionViewCell {
@IBOutlet weak var titleLabel: UILabel!
func set(title: String) {
titleLabel.text = title
}
}
class BannerFooter: UICollectionReusableView {
var adInline: AFAdInline?
func loadAd(masterTag: Int, presenter viewController: UIViewController, delegate: AFAdInlineDelegate) {
if self.adInline != nil {
// Only load ad once.
return
}
let adInline = AFAdInline(masterTagId: masterTag, presenting: viewController)
adInline.areAditionalDimmensionsEnabled = true
adInline.delegate = delegate
adInline.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleBottomMargin, .flexibleTopMargin]
adInline.center = CGPoint(x: bounds.size.width / 2, y: bounds.size.height / 2)
addSubview(adInline)
adInline.loadAd()
self.adInline = adInline
}
}
| mit | 814bec79341eaf6611d7594a310b76f2 | 31.679104 | 196 | 0.691939 | 5.480601 | false | false | false | false |
tomasharkema/HoelangTotTrein2.iOS | Packages/Core/Sources/Core/ViewModel/Ticker/TickerViewModel.swift | 1 | 1092 | //
// TickerViewModel.swift
// HoelangTotTreinCore
//
// Created by Tomas Harkema on 08-06-18.
// Copyright © 2018 Tomas Harkema. All rights reserved.
//
import API
import Bindable
import Foundation
public class ListTickerViewModel {
private let stateSource = VariableSource<LoadingState<Advices>>(value: .loading)
public let state: Variable<LoadingState<Advices>>
public let currentAdvice: Variable<LoadingState<Advice?>>
public let currentAdvices: Variable<LoadingState<AdvicesAndRequest>>
public let fromButtonTitle: Variable<String>
public let toButtonTitle: Variable<String>
public let startTime: Variable<Date>
public init(travelService: TravelService) {
state = stateSource.variable
currentAdvice = travelService.currentAdvice
currentAdvices = travelService.currentAdvices
startTime = travelService.currentAdvice.map { _ in
Date()
}
fromButtonTitle = travelService.adviceStations.map {
$0.from ?? "[Pick Station]"
}
toButtonTitle = travelService.adviceStations.map {
$0.to ?? "[Pick Station]"
}
}
}
| mit | 2815647556de98640eec464a6117eeb7 | 24.97619 | 82 | 0.733272 | 4.011029 | false | false | false | false |
yuchuanfeng/MLSwiftBasic | MLSwiftBasic/Classes/Meters/Meters.swift | 1 | 4799 | //
// Meters.swift
// MLSwiftBasic
//
// Created by 张磊 on 15/9/7.
// Copyright (c) 2015年 MakeZL. All rights reserved.
//
import UIKit
extension NSObject{
class func mt_modelForWithDict(dict:[NSObject: AnyObject])->AnyObject{
var object = self.new()
return NSObject.mt_modelValueForDict(object,dict: dict)
}
class func mt_modelValueForDict(object:AnyObject, dict: [NSObject: AnyObject])->AnyObject{
let mirror = Mirror(object)
var ivarCount:UInt32 = 0
let ivars = class_copyIvarList(object_getClass(object), &ivarCount)
for var i = 0; i < Int(ivarCount); i++ {
var keys:String = String.fromCString(ivar_getName(ivars[i]))!
if mirror.types.count > i+1{
var type:Any.Type = mirror.types[i+1]
if dict[keys] != nil {
if let array = dict[keys] as? [AnyObject]{
var optional = "\(type)".convertOptionals()
var swiftObj = optional
var vals:Array<AnyObject> = Array()
var mm = NSObject.cutForArrayString(swiftObj)
if count(mm) > 0 {
if let obj: AnyClass = NSClassFromString(mm) {
for var i = 0; i < count(array); i++ {
let di: AnyObject = array[i]
if let oc = obj.new() as? NSObject {
if (di.allKeys.count > 0) {
var iCount:UInt32 = 0
var iss = class_copyIvarList(object_getClass(oc), &iCount)
for var n = 0; n < Int(iCount); n++ {
let k:String = String.fromCString(ivar_getName(iss[n]))!
// if let value: AnyObject? = di[k] {
oc.setValue(di[k], forKeyPath: k)
// }
}
}
vals.append(oc)
}
}
object.setValue(vals, forKey:keys)
}else{
object.setValue(dict[keys], forKey:keys)
}
}
}else{
if let newObj: AnyObject = NSObject.customObject(mirror, keyValue: mirror.typesShortName[i+1],index: i+1){
var di:[NSObject: AnyObject] = (dict[keys] as? [NSObject: AnyObject])!
NSObject.mt_modelValueForDict(newObj as! NSObject, dict: di)
object.setValue(newObj, forKey:keys)
}
else {
if (dict[keys]?.isKindOfClass(NSNull.self) != nil){
object.setValue(dict[keys], forKey:keys)
}else{
object.setValue("", forKey:keys)
}
}
}
}
}
}
return object
}
class func customObject(mirror:Mirror<AnyObject>,keyValue key:AnyObject,index:Int)->AnyObject?{
var ocKey = NSMutableString(string: "\(mirror.firstName).\(key as! String)")
ocKey.replaceOccurrencesOfString("?", withString: "", options: .CaseInsensitiveSearch, range: NSMakeRange(0, ocKey.length))
if NSClassFromString(ocKey as String) == nil {
return nil
}
return NSClassFromString(ocKey as String).new() as? NSObject
}
class func isArrayForString(str:String) -> Bool {
return str.hasPrefix("Swift.Array<")
}
class func cutForArrayString(str:String) -> String {
var strM = NSMutableString(string: str)
if NSObject.isArrayForString(str) {
strM.replaceOccurrencesOfString("Swift.Array<", withString: "", options: .CaseInsensitiveSearch, range: NSMakeRange(0, strM.length))
strM.replaceOccurrencesOfString("?", withString: "", options: .CaseInsensitiveSearch, range: NSMakeRange(0, strM.length))
strM.replaceOccurrencesOfString(">", withString: "", options: .CaseInsensitiveSearch, range: NSMakeRange(0, strM.length))
}
return strM as String
}
} | mit | 5c34dd3cbce6ff8881555b9983fa96a8 | 44.226415 | 144 | 0.4517 | 5.34933 | false | false | false | false |
hamada147/helpful-functions-website | swift/functions.swift | 1 | 1760 | extension String {
// base64 to string
func fromBase64() -> String? {
guard let data = Data(base64Encoded: self) else {
return nil
}
return String(data: data, encoding: .utf8)
}
// string to base64
func toBase64() -> String {
return Data(self.utf8).base64EncodedString()
}
// string to hex
func StringToHex() -> String {
let hexString = self.data(using: .utf8)!.map{ String(format:"%02x", $0) }.joined()
return "0x" + hexString
}
// hex to string
func HexToString() -> String {
let regex = try! NSRegularExpression(pattern: "(0x)?([0-9A-Fa-f]{2})", options: .caseInsensitive)
let textNS = self as NSString
let matchesArray = regex.matches(in: textNS as String, options: [], range: NSMakeRange(0, textNS.length))
let characters = matchesArray.map {
Character(UnicodeScalar(UInt32(textNS.substring(with: $0.range(at: 2)), radix: 16)!)!)
}
return String(characters)
}
}
public extension UIView {
// pin view to given view using auto layout
public func pin(to view: UIView) {
NSLayoutConstraint.activate([
leadingAnchor.constraint(equalTo: view.leadingAnchor),
trailingAnchor.constraint(equalTo: view.trailingAnchor),
topAnchor.constraint(equalTo: view.topAnchor),
bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
// create border around the UIView with chosen colour and width with a default value of one
public func borderWith(color: UIColor, borderWidth width: CGFloat = 1) {
self.layer.borderWidth = width
self.layer.borderColor = color.cgColor
}
}
| mit | 68281af6cf08157e93c3f209cf9c36d1 | 33.509804 | 113 | 0.616477 | 4.292683 | false | false | false | false |
tkremenek/swift | test/DebugInfo/global_resilience.swift | 30 | 1575 |
// RUN: %empty-directory(%t)
//
// Compile the external swift module.
// RUN: %target-swift-frontend -g -emit-module -enable-library-evolution \
// RUN: -emit-module-path=%t/resilient_struct.swiftmodule \
// RUN: -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
//
// RUN: %target-swift-frontend -g -I %t -emit-ir -enable-library-evolution %s -o - \
// RUN: | %FileCheck %s
import resilient_struct
// Fits in buffer
let small = Size(w: 1, h: 2)
// Needs out-of-line allocation
let large = Rectangle(p: Point(x: 1, y: 2), s: Size(w: 3, h: 4), color: 5)
// CHECK: @"$s17global_resilience5small16resilient_struct4SizeVvp" =
// CHECK-SAME: !dbg ![[SMALL:[0-9]+]]
// CHECK: @"$s17global_resilience5large16resilient_struct9RectangleVvp" =
// CHECK-SAME: !dbg ![[LARGE:[0-9]+]]
// CHECK: ![[SMALL]] = !DIGlobalVariableExpression(
// CHECK-SAME: var: ![[VAR_SMALL:[0-9]+]]
// CHECK-SAME: expr: !DIExpression())
// CHECK: ![[VAR_SMALL]] = distinct !DIGlobalVariable(
// CHECK-SAME: type: ![[SMALL_TY:[0-9]+]]
// CHECK: ![[SMALL_TY]] = !DICompositeType(tag: DW_TAG_structure_type,
// CHECK-SAME: name: "$swift.fixedbuffer",
// CHECK: ![[LARGE]] = !DIGlobalVariableExpression(
// CHECK-SAME: var: ![[VAR_LARGE:[0-9]+]]
// CHECK-SAME: expr: !DIExpression())
// CHECK: ![[VAR_LARGE]] = distinct !DIGlobalVariable(
// CHECK-SAME: type: ![[LARGE_TY:[0-9]+]]
// CHECK: ![[LARGE_TY]] = !DICompositeType(tag: DW_TAG_structure_type,
// CHECK-SAME: name: "$swift.fixedbuffer",
| apache-2.0 | 5258a1a48ff93783a76ec0be0bf63a02 | 41.567568 | 85 | 0.619048 | 3.106509 | false | false | false | false |
programersun/HiChongSwift | HiChongSwift/FindAddImageCell.swift | 1 | 3059 | //
// FindAddImageCell.swift
// HiChongSwift
//
// Created by eagle on 14/12/17.
// Copyright (c) 2014年 多思科技. All rights reserved.
//
import UIKit
class FindAddImageCell: UITableViewCell {
weak var collectionDataSource: FindAddImageSource?
@IBOutlet weak var icyCollectionView: UICollectionView!
class func identifier() -> String {
return "FindAddImageCellIdentifier"
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.backgroundColor = UIColor.LCYThemeColor()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
extension FindAddImageCell: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if let dataSource = self.collectionDataSource {
return 1 + dataSource.addImageCount()
} else {
return 1
}
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(FindAddImageCollectionCell.identifier, forIndexPath: indexPath) as! FindAddImageCollectionCell
if let dataSource = collectionDataSource {
if indexPath.row < dataSource.addImageCount() {
cell.icyImageView.contentMode = UIViewContentMode.ScaleAspectFill
cell.icyImageView.image = dataSource.addImageAt(indexPath.row)
} else {
cell.icyImageView.contentMode = UIViewContentMode.Center
cell.icyImageView.image = UIImage(named: "bigCamera")
}
}
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if let unwrapped = self.collectionDataSource {
if indexPath.row == unwrapped.addImageCount() {
unwrapped.addImageWillTakePicture()
} else {
unwrapped.addImageDidSelect(indexPath.row)
}
}
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let width = UIScreen.mainScreen().bounds.width / 4.0 - 11.0
return CGSize(width: width, height: width)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 4.0, left: 4.0, bottom: 4.0, right: 4.0)
}
}
protocol FindAddImageSource: class {
func addImageCount() -> Int
func addImageAt(index: Int) -> UIImage?
func addImageWillTakePicture()
func addImageDidSelect(index: Int)
}
| apache-2.0 | 5f400aa8d0e96e3d9c4f080408e1c9ac | 37.1125 | 169 | 0.689734 | 5.386926 | false | false | false | false |
Allow2CEO/browser-ios | brave/src/frontend/popups/PopupView.swift | 1 | 21849 | /* 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
import Shared
enum PopupViewDismissType: Int {
case dont
case deny
case noAnimation
case normal
case flyUp
case flyDown
case scaleDown
}
enum PopupViewShowType: Int {
case normal
case flyUp
case flyDown
}
enum PopupViewAlignment: Int {
case top
case middle
case bottom
}
enum PopupViewStyle: Int {
case dialog
case sheet
}
protocol PopupViewDelegate {
func popupViewDidShow(_ popupView: PopupView) -> Void
func popupViewShouldDismiss(_ popupView: PopupView) -> Bool
func popupViewDidDismiss(_ popupView: PopupView) -> Void
}
class ButtonData: NSObject {
var title: String = ""
var isDefault: Bool = true
var button: UIButton?
var handler: (() -> PopupViewDismissType)?
}
class PopupView: UIView, UIGestureRecognizerDelegate {
static let popupView = PopupView()
fileprivate var keyboardState: KeyboardState?
let kPopupDialogPadding: CGFloat = 20.0
let kPopupDialogButtonHeight: CGFloat = 50.0
let kPopupDialogMaxWidth: CGFloat = 390.0
fileprivate let kPopupBackgroundAlpha: CGFloat = 0.6
fileprivate let kPopupBackgroundDismissTouchDuration: Double = 0.005
fileprivate let kPopupDialogShakeAngle: CGFloat = 0.2
fileprivate let kPopupDialogCornerRadius: CGFloat = 12.0
fileprivate let kPopupDialogButtonRadius: CGFloat = 0.0
fileprivate let kPopupDialogButtonPadding: CGFloat = 16.0
fileprivate let kPopupDialogButtonSpacing: CGFloat = 16.0
fileprivate let kPopupDialogButtonTextSize: CGFloat = 17.0
var showHandler: (() -> Void)?
var dismissHandler: (() -> Void)?
var dialogWidth: CGFloat {
get {
return min(UIScreen.main.bounds.width - padding * 2.0, kPopupDialogMaxWidth)
}
}
var dialogView: UIView!
var overlayView: UIView!
var contentView: UIView!
var style: PopupViewStyle!
var verticalAlignment: PopupViewAlignment = .middle
var defaultShowType: PopupViewShowType = .normal
var defaultDismissType: PopupViewDismissType = .normal
var overlayDismisses: Bool = true
var overlayDismissHandler: (() -> Bool)?
var presentsOverWindow: Bool = true
var automaticallyMovesWithKeyboard: Bool = true
var padding: CGFloat = 20.0 {
didSet {
setNeedsLayout()
}
}
var dialogButtons: Array<ButtonData> = []
var dialogButtonsContainer: UIView!
var dialogButtonDefaultTextColor: UIColor = UIColor.white
var dialogButtonDefaultBackgroundColor: UIColor = BraveUX.Blue
var dialogButtonTextColor: UIColor = UIColor.white
var dialogButtonBackgroundColor: UIColor = BraveUX.GreyE
var delegate: PopupViewDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.clear
autoresizingMask = [.flexibleWidth, .flexibleHeight]
let touchRecognizer: UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(backgroundTapped(recognizer:)))
touchRecognizer.minimumPressDuration = kPopupBackgroundDismissTouchDuration
touchRecognizer.delegate = self
overlayView = UIView(frame: bounds)
overlayView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
overlayView.backgroundColor = BraveUX.GreyJ
overlayView.alpha = kPopupBackgroundAlpha
overlayView.addGestureRecognizer(touchRecognizer)
addSubview(overlayView)
dialogButtonsContainer = UIView(frame: CGRect.zero)
dialogButtonsContainer.autoresizingMask = [.flexibleWidth, .flexibleHeight]
dialogView = UIView(frame: CGRect.zero)
dialogView.clipsToBounds = true
dialogView.autoresizingMask = [.flexibleWidth, .flexibleTopMargin, .flexibleBottomMargin]
dialogView.backgroundColor = UIColor.white
setStyle(popupStyle: .dialog)
KeyboardHelper.defaultHelper.addDelegate(self)
}
required init(coder: NSCoder) {
super.init(coder: coder)!
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: Layout
override func layoutSubviews() {
let contentSize: CGSize = contentView.frame.size
let keyboardHeight = keyboardState?.intersectionHeightForView(getApp().window ?? self) ?? 0
dialogView.frame = _dialogFrameWithKeyboardHeight(height: keyboardHeight)
contentView.frame = CGRect(x: 0.0, y: 0.0, width: dialogView.bounds.size.width, height: contentSize.height)
// Add and create buttons as necessary.
if dialogButtons.count > 0 {
var buttonWidth: CGFloat = 0.0
dialogButtonsContainer.frame = CGRect(x: 0.0, y: contentSize.height, width: dialogView.frame.size.width, height: kPopupDialogButtonHeight)
buttonWidth = dialogView.frame.width - (kPopupDialogButtonPadding * 2.0)
buttonWidth -= CGFloat((dialogButtons.count-1)) * kPopupDialogButtonSpacing
buttonWidth = buttonWidth / CGFloat(dialogButtons.count)
buttonWidth = rint(buttonWidth)
var buttonFrame: CGRect = CGRect(x: kPopupDialogButtonPadding, y: 0, width: buttonWidth, height: kPopupDialogButtonHeight)
let defaultButtonFont: UIFont = UIFont.systemFont(ofSize: 17, weight: UIFontWeightSemibold)
let normalButtonFont: UIFont = UIFont.systemFont(ofSize: 17, weight: UIFontWeightSemibold)
for buttonData in dialogButtons {
var button: UIButton? = buttonData.button
if button == nil {
let defaultButton: Bool = buttonData.isDefault
button = UIButton(type: .system)
button!.titleLabel!.font = defaultButton ? defaultButtonFont : normalButtonFont
button!.layer.cornerRadius = buttonFrame.height / 2.0 //kPopupDialogButtonRadius
button!.backgroundColor = defaultButton ? dialogButtonDefaultBackgroundColor : dialogButtonBackgroundColor
button!.setTitle(buttonData.title, for: .normal)
button!.setTitleColor(defaultButton ? dialogButtonDefaultTextColor : dialogButtonTextColor, for: .normal)
button!.addTarget(self, action: #selector(dialogButtonTapped(button:)), for: .touchUpInside)
buttonData.button = button
dialogButtonsContainer.addSubview(button!)
}
button?.frame = buttonFrame
buttonFrame.origin.x += buttonFrame.size.width + kPopupDialogButtonSpacing
}
dialogView.addSubview(dialogButtonsContainer)
}
}
@discardableResult fileprivate func _dialogFrameWithKeyboardHeight(height: CGFloat) -> CGRect {
var visibleFrame: CGRect = bounds
var dialogFrame: CGRect = CGRect.zero
let contentSize: CGSize = contentView.frame.size
var dialogSize: CGSize = CGSize(width: dialogWidth, height: contentSize.height)
if dialogButtons.count > 0 {
dialogSize.height += kPopupDialogButtonHeight
dialogSize.height += kPopupDialogButtonPadding
}
if automaticallyMovesWithKeyboard && height > 0 {
visibleFrame = CGRect(x: 0.0, y: 0.0, width: bounds.size.width, height: UIScreen.main.bounds.height - height)
}
if !dialogView.transform.isIdentity {
dialogSize = dialogSize.applying(dialogView.transform)
}
dialogFrame = CGRect(x: rint(visibleFrame.midX - (dialogSize.width / 2.0)), y: rint(visibleFrame.midY - (dialogSize.height / 2.0)), width: dialogSize.width, height: dialogSize.height)
dialogFrame.origin.y = max(dialogFrame.origin.y, padding)
if verticalAlignment == .top {
dialogFrame.origin.y = visibleFrame.origin.y
}
else if verticalAlignment == .bottom {
dialogFrame.origin.y = visibleFrame.size.height - dialogFrame.size.height
}
return dialogFrame
}
// MARK: Presentation
func show() {
showWithType(showType: defaultShowType)
}
func showWithType(showType: PopupViewShowType) {
if superview != nil { return }
dialogView.removeFromSuperview()
frame = UIScreen.main.bounds
addSubview(dialogView)
setNeedsLayout()
layoutIfNeeded()
if showType == .flyUp {
let finalFrame: CGRect = dialogView.frame
var startFrame: CGRect = dialogView.frame
startFrame.origin.y = frame.maxY
dialogView.frame = startFrame
// For subclasses.
willShowWithType(showType: showType)
UIView.animate(withDuration: 0.2, delay: 0.0, options: [.beginFromCurrentState, .curveEaseInOut], animations: {
self.dialogView.frame = finalFrame
}, completion: nil)
}
else if showType == .flyDown {
let finalFrame: CGRect = dialogView.frame
var startFrame: CGRect = dialogView.frame
startFrame.origin.y = -dialogView.frame.height
dialogView.frame = startFrame
willShowWithType(showType: showType)
UIView.animate(withDuration: 0.2, delay: 0.0, options: [.beginFromCurrentState, .curveEaseInOut], animations: {
self.dialogView.frame = finalFrame
}, completion: nil)
}
overlayView.alpha = 0.0
if presentsOverWindow {
UIApplication.shared.keyWindow?.addSubview(self)
}
else {
let currentViewController: AnyObject = (getApp().window?.rootViewController)!
if currentViewController is UINavigationController {
let navigationController: UINavigationController? = currentViewController as? UINavigationController
navigationController?.visibleViewController?.view.addSubview(self)
}
else if currentViewController is UIViewController {
let viewController: UIViewController? = currentViewController as? UIViewController
viewController?.view.addSubview(self)
}
}
UIView.animate(withDuration: 0.2, delay: 0.0, options: [.curveEaseOut], animations: {
self.overlayView.alpha = self.kPopupBackgroundAlpha
}, completion: nil)
didShowWithType(showType: showType)
showHandler?()
delegate?.popupViewDidShow(self)
}
func dismiss() {
dismissWithType(dismissType: defaultDismissType)
}
func dismissWithType(dismissType: PopupViewDismissType) {
if dismissType == .dont {
return
}
if delegate?.popupViewShouldDismiss(self) == false {
return
}
if dismissType != .deny {
self.endEditing(true)
}
if dismissType == .deny {
let animation: CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "transform")
animation.duration = 0.06
animation.repeatCount = 2
animation.autoreverses = true
animation.isRemovedOnCompletion = true
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
animation.values = [NSValue(caTransform3D: CATransform3DMakeRotation(kPopupDialogShakeAngle, 0.0, 0.0, 1.0)), NSValue(caTransform3D: CATransform3DMakeRotation(-kPopupDialogShakeAngle, 0.0, 0.0, 1.0))]
dialogView.layer.add(animation, forKey: "dialog.shake")
}
else if dismissType == .noAnimation {
willDismissWithType(dismissType: dismissType)
removeFromSuperview()
didDismissWithType(dismissType: dismissType)
delegate?.popupViewDidDismiss(self)
dismissHandler?()
}
else if dismissType == .normal {
willDismissWithType(dismissType: dismissType)
UIView.animate(withDuration: 0.2, delay: 0.0, options: [.beginFromCurrentState, .curveEaseIn], animations: {
self.alpha = 0.0
}, completion: { (finished) in
self.removeFromSuperview()
self.alpha = 1.0
self.didDismissWithType(dismissType: dismissType)
self.delegate?.popupViewDidDismiss(self)
self.dismissHandler?()
})
}
else if dismissType == .scaleDown {
willDismissWithType(dismissType: dismissType)
UIView.animate(withDuration: 0.2, delay: 0.0, options: [.beginFromCurrentState, .curveEaseIn], animations: {
self.alpha = 0.0
self.dialogView.transform = self.dialogView.transform.scaledBy(x: 0.9, y: 0.9)
}, completion: { (finished) in
self.removeFromSuperview()
self.alpha = 1.0
self.dialogView.transform = CGAffineTransform.identity
self.didDismissWithType(dismissType: dismissType)
self.delegate?.popupViewDidDismiss(self)
self.dismissHandler?()
})
}
else if dismissType == .flyUp {
willDismissWithType(dismissType: dismissType)
overlayView.alpha = kPopupBackgroundAlpha
UIView.animate(withDuration: 0.2, delay: 0.0, options: [.beginFromCurrentState, .curveEaseIn], animations: {
var flyawayFrame: CGRect = self.dialogView.frame
flyawayFrame.origin.y = -flyawayFrame.height
flyawayFrame.origin.y -= 20.0
self.dialogView.frame = flyawayFrame
self.overlayView.alpha = 0.0
}, completion: { (finished) in
self.removeFromSuperview()
self.overlayView.alpha = self.kPopupBackgroundAlpha
self.didDismissWithType(dismissType: dismissType)
self.delegate?.popupViewDidDismiss(self)
self.dismissHandler?()
})
}
else if dismissType == .flyDown {
willDismissWithType(dismissType: dismissType)
overlayView.alpha = kPopupBackgroundAlpha
UIView.animate(withDuration: 0.2, delay: 0.0, options: [.beginFromCurrentState, .curveEaseIn], animations: {
var flyawayFrame: CGRect = self.dialogView.frame
flyawayFrame.origin.y = self.overlayView.bounds.height
flyawayFrame.origin.y += 20.0
self.dialogView.frame = flyawayFrame
self.overlayView.alpha = 0.0
}, completion: { (finished) in
self.removeFromSuperview()
self.overlayView.alpha = self.kPopupBackgroundAlpha
self.didDismissWithType(dismissType: dismissType)
self.delegate?.popupViewDidDismiss(self)
self.dismissHandler?()
})
}
}
// MARK: Options
func setStyle(popupStyle: PopupViewStyle) {
style = popupStyle
switch popupStyle {
case .dialog:
dialogView.layer.cornerRadius = kPopupDialogCornerRadius
defaultShowType = .flyUp
defaultDismissType = .flyDown
verticalAlignment = .middle
padding = kPopupDialogPadding
case .sheet:
dialogView.layer.cornerRadius = 0.0
defaultShowType = .flyUp
defaultDismissType = .flyDown
verticalAlignment = .bottom
padding = 0.0
}
setNeedsLayout()
}
func setVerticalAlignment(alignment: PopupViewAlignment) {
verticalAlignment = alignment
setNeedsLayout()
}
func setDialogColor(color: UIColor) {
dialogView.backgroundColor = color
}
func setOverlayColor(color: UIColor, animate: Bool) {
if !animate {
overlayView.backgroundColor = color
}
else {
UIView.animate(withDuration: 0.35, delay: 0.0, options: [.beginFromCurrentState], animations: {
self.overlayView.backgroundColor = color
}, completion: nil)
}
}
func setButtonTextColor(color: UIColor) {
dialogButtonTextColor = color
for buttonData in dialogButtons {
if let button: UIButton = buttonData.button {
button.setTitleColor(color, for: .normal)
}
}
}
func setButtonBackgroundColor(color: UIColor) {
dialogButtonBackgroundColor = color
let fadeTransition: CATransition = CATransition()
fadeTransition.type = kCATransitionFade
fadeTransition.duration = 0.2
dialogButtonsContainer.layer.add(fadeTransition, forKey: kCATransition)
for buttonData in dialogButtons {
if let button: UIButton = buttonData.button {
button.layer.add(fadeTransition, forKey: kCATransition)
button.backgroundColor = color
}
}
}
func setPopupContentView(view: UIView) {
contentView?.removeFromSuperview()
contentView = view
contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
dialogView.addSubview(contentView)
setNeedsLayout()
}
func addDefaultButton(title: String, tapped: (() -> PopupViewDismissType)?) {
let buttonData: ButtonData = ButtonData()
buttonData.title = title
buttonData.isDefault = true
buttonData.handler = tapped
dialogButtons.append(buttonData)
}
func addButton(title: String, tapped: (() -> PopupViewDismissType)?) {
let buttonData: ButtonData = ButtonData()
buttonData.title = title
buttonData.isDefault = false
buttonData.handler = tapped
dialogButtons.append(buttonData)
setNeedsLayout()
}
func setTitle(title: String, buttonIndex: Int) {
if buttonIndex >= dialogButtons.count {
return
}
let buttonData: ButtonData = dialogButtons[buttonIndex]
buttonData.title = title
if let button = buttonData.button {
button.setTitle(title, for: .normal)
}
}
func removeButtonAtIndex(buttonIndex: Int) {
if buttonIndex >= dialogButtons.count {
return
}
let buttonData: ButtonData = dialogButtons[buttonIndex]
if let button = buttonData.button {
button.removeFromSuperview()
}
dialogButtons.remove(at: buttonIndex)
setNeedsLayout()
}
func numberOfButtons() -> Int {
return dialogButtons.count
}
// MARK: Actions
func dialogButtonTapped(button: UIButton) {
var dismissType = defaultDismissType
for buttonData in dialogButtons {
if let target = buttonData.button {
if target == button {
if let handler = buttonData.handler {
dismissType = handler()
break
}
}
}
}
dismissWithType(dismissType: dismissType)
}
// MARK: Background
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
let point: CGPoint = touch.location(in: dialogView)
return dialogView.point(inside: point, with: nil) == false
}
func backgroundTapped(recognizer: AnyObject?) {
if overlayDismisses == false {
return
}
guard let recognizer = recognizer else { return }
if recognizer.state == .began {
if let overlayDismissHandler = overlayDismissHandler, overlayDismissHandler() {
dismiss()
}
}
}
// MARK: Subclass Hooks
func willShowWithType(showType: PopupViewShowType) {}
func didShowWithType(showType: PopupViewShowType) {}
func willDismissWithType(dismissType: PopupViewDismissType) {}
func didDismissWithType(dismissType: PopupViewDismissType) {}
}
extension PopupView: KeyboardHelperDelegate {
func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillShowWithState state: KeyboardState) {
keyboardState = state
if !automaticallyMovesWithKeyboard {
return
}
let keyboardHeight = keyboardState?.intersectionHeightForView(getApp().window ?? self) ?? 0
_dialogFrameWithKeyboardHeight(height: keyboardHeight)
}
func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardDidShowWithState state: KeyboardState) {
}
func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillHideWithState state: KeyboardState) {
keyboardState = nil
if !automaticallyMovesWithKeyboard {
return
}
let keyboardHeight = keyboardState?.intersectionHeightForView(getApp().window ?? self) ?? 0
_dialogFrameWithKeyboardHeight(height: keyboardHeight)
}
}
| mpl-2.0 | 5ae5267f3f6730d897b304f9edf191b2 | 36.412671 | 212 | 0.620074 | 5.312181 | false | false | false | false |
ifabijanovic/swtor-holonet | ios/HoloNet/Module/Forum/Model/ForumThread.swift | 1 | 1516 | //
// ForumThread.swift
// SWTOR HoloNet
//
// Created by Ivan Fabijanovic on 16/10/14.
// Copyright (c) 2014 Ivan Fabijanović. All rights reserved.
//
import UIKit
struct ForumThread: Entity {
let id: Int
var title: String
var lastPostDate: String
var author: String
var replies: Int
var views: Int
var hasBiowareReply: Bool
var isSticky: Bool
var isDevTracker: Bool
var loadIndex: Int
var hashValue: Int { return self.id.hashValue }
init(id: Int, title: String, lastPostDate: String, author: String, replies: Int, views: Int, hasBiowareReply: Bool, isSticky: Bool) {
self.id = id
self.title = title
self.lastPostDate = lastPostDate
self.author = author
self.replies = replies
self.views = views
self.hasBiowareReply = hasBiowareReply
self.isSticky = isSticky
self.isDevTracker = false
self.loadIndex = 0
}
init(id: Int, title: String, lastPostDate: String, author: String, replies: Int, views: Int) {
self.init(id: id, title: title, lastPostDate: lastPostDate, author: author, replies: replies, views: views, hasBiowareReply: false, isSticky: false)
}
static func devTracker() -> ForumThread {
var thread = ForumThread(id: 0, title: NSLocalizedString("forum_developer_tracker_thread_title", comment: ""), lastPostDate: "", author: "", replies: 0, views: 0)
thread.isDevTracker = true
return thread
}
}
| gpl-3.0 | 17942d576aa0130490123dc287e0d9e0 | 30.5625 | 170 | 0.646205 | 3.731527 | false | false | false | false |
zyphs21/HSStockChart | HSStockChart_Demo/ViewController.swift | 1 | 5304 | //
// ViewController.swift
// HSStockChart-Demo
//
// Created by Hanson on 2017/10/12.
// Copyright © 2017年 HansonStudio. All rights reserved.
//
import UIKit
import HSStockChart
public let ScreenWidth = UIScreen.main.bounds.width
public let ScreenHeight = UIScreen.main.bounds.height
public let TimeLineLongpress = "TimeLineLongpress"
public let TimeLineUnLongpress = "TimeLineUnLongpress"
public let TimeLineChartDidTap = "TimeLineChartDidTap"
public let KLineChartLongPress = "kLineChartLongPress"
public let KLineChartUnLongPress = "kLineChartUnLongPress"
public let KLineUperChartDidTap = "KLineUperChartDidTap"
class ViewController: UIViewController {
var segmentMenu: SegmentMenu!
var currentShowingChartVC: UIViewController?
var controllerArray : [UIViewController] = []
// MARK: - Life Circle
override func viewDidLoad() {
super.viewDidLoad()
setUpView()
addNoticficationObserve()
addChartController()
segmentMenu.setSelectButton(index: 0)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override var shouldAutorotate : Bool {
// 确保从横屏展示切换回来,布局仍以竖屏模式展示
return false
}
override var preferredInterfaceOrientationForPresentation : UIInterfaceOrientation {
return UIInterfaceOrientation.portrait
}
// MARK: - Functioin
func setUpView() {
segmentMenu = SegmentMenu(frame: CGRect(x: 0, y: 88, width: ScreenWidth, height: 40))
segmentMenu.menuTitleArray = ["分时", "五日", "日K", "周K", "月K"]
segmentMenu.delegate = self
self.view.addSubview(segmentMenu)
}
func addNoticficationObserve() {
NotificationCenter.default.addObserver(self, selector: #selector(showLongPressView), name: NSNotification.Name(rawValue: TimeLineLongpress), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(showUnLongPressView), name: NSNotification.Name(rawValue: TimeLineUnLongpress), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(showKLineChartLongPressView), name: NSNotification.Name(rawValue: KLineChartLongPress), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(showKLineChartUnLongPressView), name: NSNotification.Name(rawValue: KLineChartUnLongPress), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(showLandScapeChartView), name: NSNotification.Name(rawValue: KLineUperChartDidTap), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(showLandScapeChartView), name: NSNotification.Name(rawValue: TimeLineChartDidTap), object: nil)
}
func addChartController() {
// 分时线
let timeViewcontroller = ChartViewController()
timeViewcontroller.chartType = HSChartType.timeLineForDay
controllerArray.append(timeViewcontroller)
// 五日分时线
let fiveDayTimeViewController = ChartViewController()
fiveDayTimeViewController.chartType = HSChartType.timeLineForFiveday
controllerArray.append(fiveDayTimeViewController)
// 日 K 线
let kLineViewController = ChartViewController()
kLineViewController.chartType = HSChartType.kLineForDay
controllerArray.append(kLineViewController)
// 周 K 线
let weeklyKLineViewController = ChartViewController()
weeklyKLineViewController.chartType = HSChartType.kLineForWeek
controllerArray.append(weeklyKLineViewController)
// 月 K 线
let monthlyKLineViewController = ChartViewController()
monthlyKLineViewController.chartType = HSChartType.kLineForMonth
controllerArray.append(monthlyKLineViewController)
}
// 长按分时线图,显示摘要信息
@objc func showLongPressView(_ notification: Notification) {
}
@objc func showUnLongPressView(_ notification: Notification) {
}
// 长按 K线图,显示摘要信息
@objc func showKLineChartLongPressView(_ notification: Notification) {
}
@objc func showKLineChartUnLongPressView(_ notification: Notification) {
}
// 跳转到横屏页面展示
@objc func showLandScapeChartView(_ notification: Notification) {
}
}
// MARK: - SegmentMenuDelegate
extension ViewController: SegmentMenuDelegate {
func menuButtonDidClick(index: Int) {
currentShowingChartVC?.willMove(toParent: nil)
currentShowingChartVC?.view.removeFromSuperview()
currentShowingChartVC?.removeFromParent()
let selectedVC = self.controllerArray[index] as! ChartViewController
selectedVC.chartRect = CGRect(x: 0, y: 0, width: ScreenWidth, height: 300)
selectedVC.view.frame = CGRect(x: 0, y: segmentMenu.frame.maxY, width: ScreenWidth, height: 300)
addChild(selectedVC)
if (selectedVC.view.superview == nil){
view.addSubview(selectedVC.view)
}
selectedVC.didMove(toParent: self)
currentShowingChartVC = selectedVC
}
}
| mit | 43cdddd2256b4d8a9176e1a2d8668e29 | 35.778571 | 177 | 0.706351 | 4.589127 | false | false | false | false |
jacobwhite/firefox-ios | Shared/UserAgent.swift | 1 | 5561 | /* 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 AVFoundation
import UIKit
open class UserAgent {
private static var defaults = UserDefaults(suiteName: AppInfo.sharedContainerIdentifier)!
private static func clientUserAgent(prefix: String) -> String {
return "\(prefix)/\(AppInfo.appVersion)b\(AppInfo.buildNumber) (\(DeviceInfo.deviceModel()); iPhone OS \(UIDevice.current.systemVersion)) (\(AppInfo.displayName))"
}
open static var syncUserAgent: String {
return clientUserAgent(prefix: "Firefox-iOS-Sync")
}
open static var tokenServerClientUserAgent: String {
return clientUserAgent(prefix: "Firefox-iOS-Token")
}
open static var fxaUserAgent: String {
return clientUserAgent(prefix: "Firefox-iOS-FxA")
}
open static var defaultClientUserAgent: String {
return clientUserAgent(prefix: "Firefox-iOS")
}
/**
* Use this if you know that a value must have been computed before your
* code runs, or you don't mind failure.
*/
open static func cachedUserAgent(checkiOSVersion: Bool = true,
checkFirefoxVersion: Bool = true,
checkFirefoxBuildNumber: Bool = true) -> String? {
let currentiOSVersion = UIDevice.current.systemVersion
let lastiOSVersion = defaults.string(forKey: "LastDeviceSystemVersionNumber")
let currentFirefoxBuildNumber = AppInfo.buildNumber
let currentFirefoxVersion = AppInfo.appVersion
let lastFirefoxVersion = defaults.string(forKey: "LastFirefoxVersionNumber")
let lastFirefoxBuildNumber = defaults.string(forKey: "LastFirefoxBuildNumber")
if let firefoxUA = defaults.string(forKey: "UserAgent") {
if (!checkiOSVersion || (lastiOSVersion == currentiOSVersion))
&& (!checkFirefoxVersion || (lastFirefoxVersion == currentFirefoxVersion)
&& (!checkFirefoxBuildNumber || (lastFirefoxBuildNumber == currentFirefoxBuildNumber))) {
return firefoxUA
}
}
return nil
}
/**
* This will typically return quickly, but can require creation of a UIWebView.
* As a result, it must be called on the UI thread.
*/
open static func defaultUserAgent() -> String {
assert(Thread.current.isMainThread, "This method must be called on the main thread.")
if let firefoxUA = UserAgent.cachedUserAgent(checkiOSVersion: true) {
return firefoxUA
}
let webView = UIWebView()
let appVersion = AppInfo.appVersion
let buildNumber = AppInfo.buildNumber
let currentiOSVersion = UIDevice.current.systemVersion
defaults.set(currentiOSVersion, forKey: "LastDeviceSystemVersionNumber")
defaults.set(appVersion, forKey: "LastFirefoxVersionNumber")
defaults.set(buildNumber, forKey: "LastFirefoxBuildNumber")
let userAgent = webView.stringByEvaluatingJavaScript(from: "navigator.userAgent")!
// Extract the WebKit version and use it as the Safari version.
let webKitVersionRegex = try! NSRegularExpression(pattern: "AppleWebKit/([^ ]+) ", options: [])
let match = webKitVersionRegex.firstMatch(in: userAgent, options: [],
range: NSRange(location: 0, length: userAgent.count))
if match == nil {
print("Error: Unable to determine WebKit version in UA.")
return userAgent // Fall back to Safari's.
}
let webKitVersion = (userAgent as NSString).substring(with: match!.range(at: 1))
// Insert "FxiOS/<version>" before the Mobile/ section.
let mobileRange = (userAgent as NSString).range(of: "Mobile/")
if mobileRange.location == NSNotFound {
print("Error: Unable to find Mobile section in UA.")
return userAgent // Fall back to Safari's.
}
let mutableUA = NSMutableString(string: userAgent)
mutableUA.insert("FxiOS/\(appVersion)b\(AppInfo.buildNumber) ", at: mobileRange.location)
let firefoxUA = "\(mutableUA) Safari/\(webKitVersion)"
defaults.set(firefoxUA, forKey: "UserAgent")
return firefoxUA
}
open static func desktopUserAgent() -> String {
let userAgent = NSMutableString(string: defaultUserAgent())
// Spoof platform section
let platformRegex = try! NSRegularExpression(pattern: "\\([^\\)]+\\)", options: [])
guard let platformMatch = platformRegex.firstMatch(in: userAgent as String, options: [], range: NSRange(location: 0, length: userAgent.length)) else {
print("Error: Unable to determine platform in UA.")
return String(userAgent)
}
userAgent.replaceCharacters(in: platformMatch.range, with: "(Macintosh; Intel Mac OS X 10_11_1)")
// Strip mobile section
let mobileRegex = try! NSRegularExpression(pattern: " FxiOS/[^ ]+ Mobile/[^ ]+", options: [])
guard let mobileMatch = mobileRegex.firstMatch(in: userAgent as String, options: [], range: NSRange(location: 0, length: userAgent.length)) else {
print("Error: Unable to find Mobile section in UA.")
return String(userAgent)
}
userAgent.replaceCharacters(in: mobileMatch.range, with: "")
return String(userAgent)
}
}
| mpl-2.0 | 6bbea07fa94cedb387a401420e958b8d | 41.450382 | 171 | 0.654738 | 4.943111 | false | false | false | false |
jongwonwoo/CodeSamples | ViewController/Transitions/PhotoViewer/LivePhotoPlayground/LivePhotoPlayground/LivePhotoViewController.swift | 1 | 5270 | //
// LivePhotoViewController.swift
// LivePhotoPlayground
//
// Created by jongwon woo on 2016. 10. 28..
// Copyright © 2016년 jongwonwoo. All rights reserved.
//
import UIKit
import PhotosUI
class LivePhotoViewController: UIViewController {
fileprivate let reuseIdentifier = "PhotoCell"
@IBOutlet weak var photosCollectionView: CustomCollectionView!
var selectedIndexPath: IndexPath?
var photos: PHFetchResult<PHAsset>?
private let photoFetcher = PhotoFetcher()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
photosCollectionView.backgroundColor = .red
photosCollectionView.reloadDataWithCompletion {
self.photosCollectionView.reloadDataCompletionBlock = nil
guard let indexPath = self.selectedIndexPath else { return }
self.photosCollectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: false)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
photosCollectionView.isPagingEnabled = true
photosCollectionView.frame = view.frame.insetBy(dx: -20.0, dy: 0.0)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
fileprivate func showTitle(date: Date?) {
guard let dateBind = date else { return }
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .short
self.title = formatter.string(from: dateBind)
}
}
// MARK: - UICollectionViewDataSource
extension LivePhotoViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
var count = 0;
if let photos = self.photos {
count = photos.count
}
return count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
print(#function + " \(indexPath)")
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PhotoCollectionViewCell
if let photos = self.photos {
let asset = photos[indexPath.item]
cell.asset = asset
}
cell.indexPath = indexPath
return cell
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
print(#function + " \(indexPath)")
if let photos = self.photos {
let asset = photos[indexPath.item]
if let creationDate = asset.creationDate {
self.showTitle(date: creationDate)
}
}
}
func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
print(#function + " \(indexPath)")
}
}
// MARK: - UICollectionView delegate
extension LivePhotoViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, targetContentOffsetForProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
guard let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else { return proposedContentOffset }
guard let indexPath = collectionView.indexPathsForVisibleItems.last, let layoutAttributes = flowLayout.layoutAttributesForItem(at: indexPath) else {
return proposedContentOffset
}
return CGPoint(x: layoutAttributes.center.x - (layoutAttributes.size.width / 2.0) - (flowLayout.minimumLineSpacing / 2.0), y: 0)
}
}
// MARK: - UICollectionViewDelegateFlowLayout
extension LivePhotoViewController : UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// print(#function + " \(indexPath)")
return CGSize(width: view.frame.width, height: view.frame.height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
// print(#function)
return UIEdgeInsets(top: 0.0, left: 20.0, bottom: 0.0, right: 20.0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
// print(#function)
return 40
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
}
| mit | 7a21f142da8c9c0d71cca9542df9f806 | 35.075342 | 175 | 0.670211 | 5.898096 | false | false | false | false |
danielsaidi/Vandelay | VandelayDemo/Photos/PhotoViewController.swift | 1 | 2423 | //
// PhotoViewController.swift
// VandelayDemo
//
// Created by Daniel Saidi on 2016-06-21.
// Copyright © 2016 Daniel Saidi. All rights reserved.
//
import UIKit
class PhotoViewController: UICollectionViewController {
// MARK: - View lifecycle
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
collectionView?.backgroundColor = .white
reloadData()
}
// MARK: - Properties
var repository: PhotoRepository!
private var photos = [Photo]()
}
// MARK: - Actions
@objc extension PhotoViewController {
func add() {
let picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = false
picker.sourceType = .photoLibrary
present(picker, animated: true, completion: nil)
}
}
// MARK: - Private Functions
private extension PhotoViewController {
func reloadData() {
photos = repository.getPhotos()
collectionView?.reloadData()
}
}
// MARK: - UICollectionViewDataSource
extension PhotoViewController {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return photos.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell", for: indexPath)
guard let photoCell = cell as? PhotoCollectionViewCell else { return cell }
let photo = photos[indexPath.row]
photoCell.imageView.image = photo.image
return photoCell
}
}
// MARK: - UIImagePickerControllerDelegate
extension PhotoViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
let imageData = info[.originalImage]
guard let image = imageData as? UIImage else { return print("No image data") }
let photo = Photo(image: image.resized(toWidth: 250))
repository.add(photo)
dismiss(animated: true, completion: nil)
reloadData()
}
}
| mit | 068e2f970c6d32549fb4c88042ebd0a2 | 25.911111 | 143 | 0.682081 | 5.467269 | false | false | false | false |
mmuehlberger/tutsplus-whats-new-in-ios10 | RideIntent/RideRequestHandler.swift | 1 | 3416 | //
// RideRequestHandler.swift
// TutsplusCourses
//
// Created by Markus Mühlberger on 02/12/2016.
// Copyright © 2016 Markus Mühlberger. All rights reserved.
//
import Foundation
import Intents
class RideRequestHandler : NSObject, INRequestRideIntentHandling {
let fakeRides : FakeRides
init(fakeRides: FakeRides) {
self.fakeRides = fakeRides
}
// Resolution
func resolvePickupLocation(forRequestRide intent: INRequestRideIntent, with completion: @escaping (INPlacemarkResolutionResult) -> Void) {
switch intent.pickupLocation {
case .none:
completion(.needsValue())
case let .some(location):
completion(.success(with: location))
}
}
func resolveDropOffLocation(forRequestRide intent: INRequestRideIntent, with completion: @escaping (INPlacemarkResolutionResult) -> Void) {
switch intent.dropOffLocation {
case .none:
completion(.needsValue())
case let .some(location):
completion(.success(with: location))
}
}
func resolvePartySize(forRequestRide intent: INRequestRideIntent, with completion: @escaping (INIntegerResolutionResult) -> Void) {
switch intent.partySize {
case .none:
completion(.needsValue())
case let .some(people) where people <= 4:
completion(.success(with: people))
default:
completion(.unsupported())
}
}
// Confirmation
func confirm(requestRide intent: INRequestRideIntent, completion: @escaping (INRequestRideIntentResponse) -> Void) {
let responseCode : INRequestRideIntentResponseCode
switch intent.pickupLocation! {
case let location where fakeRides.pickupWithinRange(location.location!):
responseCode = .ready
default:
responseCode = .failureRequiringAppLaunchNoServiceInArea
}
let response = INRequestRideIntentResponse(code: responseCode, userActivity: .none)
completion(response)
}
// Execution
func handle(requestRide intent: INRequestRideIntent, completion: @escaping (INRequestRideIntentResponse) -> Void) {
guard let pickup = intent.pickupLocation?.location, let dropoff = intent.dropOffLocation?.location else {
let response = INRequestRideIntentResponse(code: .failure, userActivity: .none)
completion(response)
return
}
let response : INRequestRideIntentResponse
if let ride = fakeRides.requestRide(pickup: pickup, dropoff: dropoff) {
let status = INRideStatus()
status.rideIdentifier = ride.driver.name
status.phase = .confirmed
status.vehicle = ride.rideIntentVehicle
status.driver = ride.driver.rideIntentDriver
status.estimatedPickupDate = Date(timeIntervalSinceNow: 7 * 60)
status.pickupLocation = intent.pickupLocation
status.dropOffLocation = intent.dropOffLocation
response = INRequestRideIntentResponse(code: .success, userActivity: .none)
response.rideStatus = status
} else {
response = INRequestRideIntentResponse(code: .failureRequiringAppLaunchNoServiceInArea, userActivity: .none)
}
completion(response)
}
}
| bsd-2-clause | a61c04e6162cf86428a163fae180d6e8 | 34.926316 | 143 | 0.651919 | 4.975219 | false | false | false | false |
TYG1/SwiftLearning | SwiftLearning.playground/Pages/Control Flow.xcplaygroundpage/Contents.swift | 1 | 12834 | /*:
[Table of Contents](@first) | [Previous](@previous) | [Next](@next)
- - -
# Control Flow
* callout(Session Overview): Processing logic is what gives your programs personality. These decision making statements are known as control flow. Control flow statements can fork your execution path or even repeat a series of statements. Please visit the Swift Programming Language Guide section on [Control Flow](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ControlFlow.html#//apple_ref/doc/uid/TP40014097-CH9-ID120) for more details on control flow.
*/
import Foundation
/*:
## The `if` and the `else` conditional statements
The simplest of the control flow statements is the `if` and `else` statements. The `if` conditional statement evaluates a boolean expression (true or false) and executes code if the result of the evaluation is `true`. If `else` is present, code is executed if the `if` statement evaluates to `false`.
*/
var grade = "A"
if grade == "A" {
print("you will get an A")
} else {
print("not an A")
}
grade = "D"
if grade == "D" {
print("you will get a D")
} else {
print("at least not a D")
}
//: You can also combine as many boolean expression on a `if` conditional statement, though using a `switch` statement if recommended for readabiliy.
if grade == "A" || grade == "B" {
print("you will get a good grade")
} else if grade == "A" {
print("you will get an average grade")
} else if grade == "D" || grade == "F" {
print("you will get a bad grade")
}
/*:
## less `if`ing and more `switch`ing
If your code has many boolean expressions to evaluate, a `switch` statement will provide more readabiliy. The `switch` compares a value of a constant or variable against a series of possible outcomes. If there is a match, provide with the `case`, the block of code is executed for the `case` only. The `switch` statement must be *exhaustive*, meaning that every possible value must be matched against one of the `switch` cases.
*/
grade = "B"
switch grade {
case "A":
print("get an A")
case "B":
print("get an B")
case "C":
print("get an C")
case "D":
print("get an D")
default:
print("get an F")
}
switch grade {
case "A", "B":
print("pass")
case "D", "F":
print("repeat")
default:
print("needs to study more")
}
//: The above `switch` statements has the `default` case which will be matched when all other cases fail.
/*:
### Fallthrough
Swift's `switch` statement matches on a single case and ends execution of the `switch` after the case body is executed. There are instances where you would want multiple cases to be matched where it's not appropriate provide the matching on the a single case.
*/
var gradeNumber = 95
var gradeLetter: String = ""
switch gradeNumber {
case 93: fallthrough
case 94: fallthrough
case 95: fallthrough
case 96: fallthrough
case 97: fallthrough
case 98: fallthrough
case 99:
gradeLetter = "A"
case 90:
gradeLetter = "A-"
case 80:
gradeLetter = "B"
case 70:
gradeLetter = "C"
case 60:
gradeLetter = "D"
case 50:
gradeLetter = "F"
default:
break // this break is needed because all cases need a body
}
print(gradeLetter)
//: `fallthrough` doesn't check the following case condition, but causes execution to move to the next statements of the following case.
//: > **Experiment**: Assign gradeNumber equal to 100 and have gradeLetter print A+.
/*:
### Interval Matching
The value in the `switch` case statement can be checked to determine if the value is included in a specified range.
*/
gradeNumber = 100
switch gradeNumber {
case 100:
gradeLetter = "A+"
<<<<<<< .merge_file_uMvodv
case 93..<100:
=======
case 93...99:
>>>>>>> .merge_file_wLLF3O
gradeLetter = "A"
case 90..<93:
gradeLetter = "A-"
case 80..<90:
gradeLetter = "B"
case 70..<80:
gradeLetter = "C"
case 60..<60:
gradeLetter = "D"
case 50..<60:
gradeLetter = "F"
default:
gradeLetter = ""
break // this break is needed because all cases need a body
}
print(gradeLetter)
/*:
The above `switch` case uses grade ranges to determine the grade letter as opposed to specifying each grade number.
*/
/*:
### Working with Tuples
Using the `switch` statement with tuples lets you execute code branches depending on values within the tuple.
*/
let gradeTuple = (gradeNumber, gradeLetter)
switch gradeTuple {
case (100, _):
print("You get an A+")
case (93...99, _):
print("You get an A")
case (90..<93, _):
print("You get an A-")
case (80..<90, _):
print("You get an B")
case (70..<80, _):
print("You get an C")
case (60..<60, _):
print("You get an D")
case (50..<60, _):
print("You get an F")
default:
print("You got an \(gradeTuple.0)%")
}
switch gradeTuple {
case (_, "A+"):
print("You got 100%")
case (_, "A"):
print("You got between 90% - 99%")
case (_, "B"):
print("You got between 80% - 89%")
case (_, "C"):
print("You got between 70% - 79%")
case (_, "D"):
print("You got between 60% - 69%")
case (_, "F"):
print("You got between 50% - 59%")
default:
print("You dont' get a grade")
}
/*:
The first `switch` case statement matches on the grade number providing that the grade number falls within a case range. The second `switch` matches on the grade letter.
*/
/*:
### Value Bindings
The `switch` case statement can store values into constants or variables that are only available to the `switch` case body. This is known as *value binding*, because values are bound to temporary constants or variables when a value or values are match in the case.
*/
switch gradeTuple {
case (90...100, let letter):
print("You got between 90% - 100%, or an \(letter)")
case (80...89, let letter):
print("You got between 80% - 89%, or a \(letter)")
case (70...79, let letter):
print("You got between 70% - 79%, or a \(letter)")
case (60...69, let letter):
print("You got between 60% - 69%, or a \(letter)")
case (50...59, let letter):
print("You got between 50% - 59%, or a \(letter)")
case let (number, letter):
print("You got a \(number)% or a \(letter)")
}
/*:
Here the `switch` matches on the grade number range and prints out the grade letter.
*/
/*:
### Where
You can use a `where` clause to check for even more conditions.
*/
switch gradeTuple {
case (100, _):
print("You aced it!")
<<<<<<< .merge_file_uMvodv
// where String("ABCD").containsString(letter);
case let (number, letter) where ["A", "B", "C", "D"].contains(letter):
=======
case let (number, letter) where "ABCD".containsString(letter):
>>>>>>> .merge_file_wLLF3O
print("You passed!")
default:
print("You failed!")
}
/*:
Above, all we want to do is print a message from one of three cases. We use the `where` clause on the second case to see if the grade letter is contained in the array of grade letters.
*/
/*:
## Iterating using For Loops
Two `for` looping statements that let you execute code blocks a certain number of times are the `for-in` and the `for` loops.
*/
/*:
### For-In
The `for-in` loop executes a set of statements for each item in a list or sequence of items.
*/
//for element in array/tuple
for grade in "ABCDF".characters {
print(grade)
}
for index in 0..<5 {
print(index)
}
/*:
<<<<<<< HEAD
<<<<<<< HEAD
### For
The `for` loop executes a set of statements until a specific condition is met, usually by incrementing a counter each time the loop ends.
*/
var i = 0
for var index = 0; index < 5; i++ {
print(index)
print(i)
}
//: The `for` loop has 3 parts:
/*:
- *Initialization* (`var index = 0`), evaluated once.
- *Condition* (`index < 5`), evaluated at the start of the each loop. If the result is `true` statements in the block are executed, if `false` the loop ends.
- *Increment* (`++index`), evaluated after all the statements in the block are executed.
*/
/*:
=======
>>>>>>> 078125ac870c5bd2d9ab7b9b36ee1180c31f0e68
=======
>>>>>>> b406f302ba0b452c47011ea8bfb178c6973e9f79
## Iterating using While Loops
`while` loops are recommended when the number of iterations is unknown before looping begins.
*/
/*:
### While
The `while` loop evaluates its condition at the beginning of each iteration through the loop.
*/
var index = 0
while (index < 5) {
print(index)
index += 1
}
//: The above `while` loop statement evaluates `index < 5`, if the result is `true` looping continues, if `false` looping ends.
/*:
### Repeat-While
The `repeat-while` loop evaluates its condition at the end of each iteration through the loop.
*/
index = 0
repeat {
print(index)
index += 1
} while (index < 5)
//: The above `repeat-while` loop statement executes the code block first then evaluates `index < 5`, if the result is `true` looping continues, if `false` looping ends.
/*:
## Control Transfer Statements
Control transfer statements change the sequence or order in which your code is executed, by transferring control from one block of code to another. Swift provides five control transfer statements:
- `continue`
- `break`
- `fallthrough`
- `return`, explained in [Functions](Functions)
- `throw`, explained in [Functions](Functions)
*/
/*:
### Continue
The `continue` statement tells a loop to stop and start again at the beginning of the next iteration through the loop.
*/
index = 0
repeat {
index += 1
if index == 3 {
continue
}
print(index)
} while (index < 5)
//: The above `repeat-while` loop statement skips the index 3, moves onto the next iteration of the loop printing 4 and 5, then ends normally.
/*:
### Break
The `break` statement ends the execution of the control flow statement. The `break` statement is used in the `switch` and loop statements to end the control flow earlier than normal.
*/
/*:
**Break in a Loop Statement**
A `break` in a loop exits the loop.
*/
index = 0
repeat {
index += 1
if index == 3 {
break
}
print(index)
} while (index < 5)
//: The above `repeat-while` loop statement loops until index equals 3 and exits the loop all together.
/*:
**Break in a Switch Statement**
A `break` in a `switch` is used to ignore cases.
*/
gradeNumber = 80
switch gradeNumber {
case 100:
print("A+")
case 90:
print("A")
case 80:
print("B")
case 70:
print("C")
case 60:
print("D")
case 50:
print("F")
default:
break // this break is needed because all cases need a body
}
//: The above `switch` statement needs a `break` in the `default` case because the all other values greater than 100 aren't applicable.
/*:
## API Availability
*/
if #available(iOS 9, OSX 10.11, *) {
print("statements will execute for iOS9+ and osx 10.11+")
} else {
print("statements to execute when running on lower platforms.")
}
/*:
- - -
* callout(Exercise): You have a secret message to send. Write a playground that can encrypt strings with an alphabetical [caesar cipher](https://en.wikipedia.org/wiki/Caesar_cipher). This cipher can ignore numbers, symbols, and whitespace.
**Example Output:**
- Decrypted: Nearly all men can stand adversity, but if you want to test a man's character, give him power
- Encrypted: arneyl nyy zra pna fgnaq nqirefvgl, ohg vs lbh jnag gb grfg n zna'f punenpgre, tvir uvz cbjre
**Constraints:**
- The encrypted and decrypted text is case sensitive
- Add a shift variable to indicate how many places to shift
* callout(Checkpoint):At this point, you have learned the majority of the control flow statements that enable you to make decisions and execute a set of statements zero or more times until some condition is met.
**Keywords to remember:**
- `if` = evaluate an express for `true` and execute the following statements
- `else` = execute the following statements when the `if` evaluates an express to false
- `for` = to iterate
- `in` = when used with `for`, iterate over items in *something*
- `while` = execute statements indefinitely until a false expression is met
- `repeat` = used with `while`, execute statments first then loop
- `switch` = the start of matching a value on possible outcomes
- `case` = used with `switch`, a single outcome
- `default` = used with 'switch', the any outcome
- `fallthrough` = used with `switch`, execute the next case's statements
- `continue` = move on to the next iteration and don't execute the following statements
- `break` = when used with looping, stop looping and don't execute the following statements
- `where` = when used with switch, to expand matching conditions
* callout(Supporting Materials): Chapters and sections from the Guide and Vidoes from WWDC
- [Guide: Control Flow](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ControlFlow.html)
- - -
[Table of Contents](@first) | [Previous](@previous) | [Next](@next)
*/
| mit | 8319d5d0944a9be9c25deda36c76db71 | 31.907692 | 517 | 0.685523 | 3.710321 | false | false | false | false |
khoogheem/GenesisKit | Shared/Stack.swift | 1 | 4711 | //
// Stack.swift
// GenesisKit
//
// Created by Kevin A. Hoogheem on 10/14/14.
// Copyright (c) 2014 Kevin A. Hoogheem. 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 Foundation
/** Stack is a simple implimentation of a Stack.
Inspired by the WWDC 2014 Advanced Swift talk.
It can hold any type of object.
*/
public struct Stack<T: Equatable> {
private var items = [T]()
public init () {
}
/**
Creates a Stack Object from the array of items
:param: items An array of objects
*/
public init (items: [T]) {
self.init()
//This ends up being quicker then doing enumerations
items.map { self.push($0) }
}
/** Provides the top most object in the `Stack` */
public var topItem: T? {
return items.isEmpty ? nil : items[items.count - 1]
}
/** Provides the current count of objects in `Stack` */
public var count: Int {
return items.count
}
/** Provides the first object in `Stack` */
public var firstObject: T? {
return items.first
}
/** Provides the last object in `Stack` */
public var lastObject: T? {
return items.last
}
/**
Pushes the passed `item` on top of the `Stack`
:param: item The Item you are pushing onto the stack
*/
public mutating func push(item: T) {
items.append(item)
}
/**
Removes the top most item from the `Stack` and returns it
:returns: The top most object on the `Stack`
*/
public mutating func pop() -> T? {
if items.count != 0{
return items.removeLast()
}
return nil
}
/**
Returns the object at the given `index` in the `Stack`
:param: index - The index of the object in the Stack
:returns: The optional object in the `Stack` at the given `index`
*/
public func objectAtIndex(index: Int) -> T? {
if index < 0 || index >= items.count {
return nil
}
return items[index]
}
/**
Returns the `index` of the object in the `Stack`
:param: object - The object in the Stack
:returns: An optional Int value of the object in the `Stack`
*/
public func indexOfObject(object:T) -> Int? {
for i in 0..<items.endIndex {
if items[i] == object {
return i
}
}
return nil
}
/**
Removes all the objects from the Stack
*/
public mutating func removeAll() {
items.removeAll(keepCapacity: false)
}
/**
Determines equitability of the Stack to the passed in Stack
:param: stack The Stack to evaluate
:returns: A Bool value that represents the equitability of the two Stacks
*/
public func isEqualToStack(stack: Stack) -> Bool {
// check that both Stacks contain the same number of items
if self.count != stack.count {
return false
}
// check each pair of items to see if they are equivalent
for i in 0..<self.count {
if self[i] != stack[i] {
return false
}
}
// all items match, so return true
return true
}
//MARK: Index Subscript
/**
Returns the object at the given subscript `index` in the `Stack`
:param: index - The index of the object in the Stack
:returns: The optional object in the `Stack` at the given `index`
*/
public subscript (index:Int) -> T? {
return self.objectAtIndex(index)
}
//MARK: Range Subscript
/**
Returns the range of objects in the `Stack`
:param: range - The range of the objects in the Stack
:returns: The optional Array of ojects in the `Stack`
*/
public subscript (range: Range<Int>) -> [T]? {
if range.startIndex < 0 || range.endIndex > self.count {
return nil
}
return Array(items[range])
}
}
//MARK: Extensions
extension Stack : SequenceType {
public func generate() -> genericGenerator<T> {
return genericGenerator( items: items[0..<items.endIndex] )
}
}
*/
| mit | 13db5c731b2a33ee6ce5b910709111f7 | 23.794737 | 81 | 0.682233 | 3.502602 | false | false | false | false |
Bunn/firefox-ios | Client/Frontend/Browser/TabLocationView.swift | 1 | 20771 | /* 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
import Shared
import SnapKit
import XCGLogger
private let log = Logger.browserLogger
protocol TabLocationViewDelegate {
func tabLocationViewDidTapLocation(_ tabLocationView: TabLocationView)
func tabLocationViewDidLongPressLocation(_ tabLocationView: TabLocationView)
func tabLocationViewDidTapReaderMode(_ tabLocationView: TabLocationView)
func tabLocationViewDidTapShield(_ tabLocationView: TabLocationView)
func tabLocationViewDidTapPageOptions(_ tabLocationView: TabLocationView, from button: UIButton)
func tabLocationViewDidLongPressPageOptions(_ tabLocationVIew: TabLocationView)
func tabLocationViewDidBeginDragInteraction(_ tabLocationView: TabLocationView)
/// - returns: whether the long-press was handled by the delegate; i.e. return `false` when the conditions for even starting handling long-press were not satisfied
@discardableResult func tabLocationViewDidLongPressReaderMode(_ tabLocationView: TabLocationView) -> Bool
func tabLocationViewLocationAccessibilityActions(_ tabLocationView: TabLocationView) -> [UIAccessibilityCustomAction]?
}
private struct TabLocationViewUX {
static let HostFontColor = UIColor.black
static let BaseURLFontColor = UIColor.Photon.Grey50
static let Spacing: CGFloat = 8
static let StatusIconSize: CGFloat = 18
static let TPIconSize: CGFloat = 44
static let ReaderModeButtonWidth: CGFloat = 34
static let ButtonSize: CGFloat = 44
static let URLBarPadding = 4
}
class TabLocationView: UIView {
var delegate: TabLocationViewDelegate?
var longPressRecognizer: UILongPressGestureRecognizer!
var tapRecognizer: UITapGestureRecognizer!
var contentView: UIStackView!
fileprivate let menuBadge = BadgeWithBackdrop(imageName: "menuBadge", backdropCircleSize: 32)
@objc dynamic var baseURLFontColor: UIColor = TabLocationViewUX.BaseURLFontColor {
didSet { updateTextWithURL() }
}
var url: URL? {
didSet {
let wasHidden = lockImageView.isHidden
lockImageView.isHidden = url?.scheme != "https"
if wasHidden != lockImageView.isHidden {
UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: nil)
}
updateTextWithURL()
pageOptionsButton.isHidden = (url == nil)
trackingProtectionButton.isHidden = !["https", "http"].contains(url?.scheme ?? "")
setNeedsUpdateConstraints()
}
}
var readerModeState: ReaderModeState {
get {
return readerModeButton.readerModeState
}
set (newReaderModeState) {
if newReaderModeState != self.readerModeButton.readerModeState {
let wasHidden = readerModeButton.isHidden
self.readerModeButton.readerModeState = newReaderModeState
readerModeButton.isHidden = (newReaderModeState == ReaderModeState.unavailable)
if wasHidden != readerModeButton.isHidden {
UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: nil)
if !readerModeButton.isHidden {
// Delay the Reader Mode accessibility announcement briefly to prevent interruptions.
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2)) {
UIAccessibility.post(notification: UIAccessibility.Notification.announcement, argument: Strings.ReaderModeAvailableVoiceOverAnnouncement)
}
}
}
UIView.animate(withDuration: 0.1, animations: { () -> Void in
self.readerModeButton.alpha = newReaderModeState == .unavailable ? 0 : 1
})
}
}
}
lazy var placeholder: NSAttributedString = {
let placeholderText = NSLocalizedString("Search or enter address", comment: "The text shown in the URL bar on about:home")
return NSAttributedString(string: placeholderText, attributes: [NSAttributedString.Key.foregroundColor: UIColor.Photon.Grey50])
}()
lazy var urlTextField: UITextField = {
let urlTextField = DisplayTextField()
// Prevent the field from compressing the toolbar buttons on the 4S in landscape.
urlTextField.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 250), for: .horizontal)
urlTextField.attributedPlaceholder = self.placeholder
urlTextField.accessibilityIdentifier = "url"
urlTextField.accessibilityActionsSource = self
urlTextField.font = UIConstants.DefaultChromeFont
urlTextField.backgroundColor = .clear
// Remove the default drop interaction from the URL text field so that our
// custom drop interaction on the BVC can accept dropped URLs.
if let dropInteraction = urlTextField.textDropInteraction {
urlTextField.removeInteraction(dropInteraction)
}
return urlTextField
}()
fileprivate lazy var lockImageView: UIImageView = {
let lockImageView = UIImageView(image: UIImage.templateImageNamed("lock_verified"))
lockImageView.isAccessibilityElement = true
lockImageView.contentMode = .center
lockImageView.accessibilityLabel = NSLocalizedString("Secure connection", comment: "Accessibility label for the lock icon, which is only present if the connection is secure")
return lockImageView
}()
class TrackingProtectionButton: UIButton {
// Disable showing the button if the feature is off in the prefs
override var isHidden: Bool {
didSet {
separatorLine?.isHidden = isHidden
guard !isHidden, let appDelegate = UIApplication.shared.delegate as? AppDelegate, let profile = appDelegate.profile else { return }
if !FirefoxTabContentBlocker.isTrackingProtectionEnabled(prefs: profile.prefs) {
isHidden = true
}
}
}
var separatorLine: UIView?
}
lazy var trackingProtectionButton: TrackingProtectionButton = {
let trackingProtectionButton = TrackingProtectionButton()
trackingProtectionButton.setImage(UIImage.templateImageNamed("tracking-protection"), for: .normal)
trackingProtectionButton.addTarget(self, action: #selector(didPressTPShieldButton(_:)), for: .touchUpInside)
trackingProtectionButton.tintColor = UIColor.Photon.Grey50
trackingProtectionButton.imageView?.contentMode = .scaleAspectFill
trackingProtectionButton.accessibilityIdentifier = "TabLocationView.trackingProtectionButton"
return trackingProtectionButton
}()
fileprivate lazy var readerModeButton: ReaderModeButton = {
let readerModeButton = ReaderModeButton(frame: .zero)
readerModeButton.addTarget(self, action: #selector(tapReaderModeButton), for: .touchUpInside)
readerModeButton.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(longPressReaderModeButton)))
readerModeButton.isAccessibilityElement = true
readerModeButton.isHidden = true
readerModeButton.imageView?.contentMode = .scaleAspectFit
readerModeButton.contentHorizontalAlignment = .left
readerModeButton.accessibilityLabel = NSLocalizedString("Reader View", comment: "Accessibility label for the Reader View button")
readerModeButton.accessibilityIdentifier = "TabLocationView.readerModeButton"
readerModeButton.accessibilityCustomActions = [UIAccessibilityCustomAction(name: NSLocalizedString("Add to Reading List", comment: "Accessibility label for action adding current page to reading list."), target: self, selector: #selector(readerModeCustomAction))]
return readerModeButton
}()
lazy var pageOptionsButton: ToolbarButton = {
let pageOptionsButton = ToolbarButton(frame: .zero)
pageOptionsButton.setImage(UIImage.templateImageNamed("menu-More-Options"), for: .normal)
pageOptionsButton.addTarget(self, action: #selector(didPressPageOptionsButton), for: .touchUpInside)
pageOptionsButton.isAccessibilityElement = true
pageOptionsButton.isHidden = true
pageOptionsButton.imageView?.contentMode = .left
pageOptionsButton.accessibilityLabel = NSLocalizedString("Page Options Menu", comment: "Accessibility label for the Page Options menu button")
pageOptionsButton.accessibilityIdentifier = "TabLocationView.pageOptionsButton"
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(didLongPressPageOptionsButton))
pageOptionsButton.addGestureRecognizer(longPressGesture)
return pageOptionsButton
}()
private func makeSeparator() -> UIView {
let line = UIView()
line.layer.cornerRadius = 2
return line
}
// A vertical separator next to the page options button.
lazy var separatorLineForPageOptions: UIView = makeSeparator()
lazy var separatorLineForTP: UIView = makeSeparator()
override init(frame: CGRect) {
super.init(frame: frame)
register(self, forTabEvents: .didGainFocus, .didToggleDesktopMode, .didChangeContentBlocking)
longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPressLocation))
longPressRecognizer.delegate = self
tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapLocation))
tapRecognizer.delegate = self
addGestureRecognizer(longPressRecognizer)
addGestureRecognizer(tapRecognizer)
let space10px = UIView()
space10px.snp.makeConstraints { make in
make.width.equalTo(10)
}
// Link these so they hide/show in-sync.
trackingProtectionButton.separatorLine = separatorLineForTP
pageOptionsButton.separatorLine = separatorLineForPageOptions
let subviews = [trackingProtectionButton, separatorLineForTP, space10px, lockImageView, urlTextField, readerModeButton, separatorLineForPageOptions, pageOptionsButton]
contentView = UIStackView(arrangedSubviews: subviews)
contentView.distribution = .fill
contentView.alignment = .center
addSubview(contentView)
contentView.snp.makeConstraints { make in
make.edges.equalTo(self)
}
lockImageView.snp.makeConstraints { make in
make.width.equalTo(TabLocationViewUX.StatusIconSize)
make.height.equalTo(TabLocationViewUX.ButtonSize)
}
trackingProtectionButton.snp.makeConstraints { make in
make.width.equalTo(TabLocationViewUX.TPIconSize)
make.height.equalTo(TabLocationViewUX.ButtonSize)
}
separatorLineForTP.snp.makeConstraints { make in
make.width.equalTo(1)
make.height.equalTo(26)
}
pageOptionsButton.snp.makeConstraints { make in
make.size.equalTo(TabLocationViewUX.ButtonSize)
}
separatorLineForPageOptions.snp.makeConstraints { make in
make.width.equalTo(1)
make.height.equalTo(26)
}
readerModeButton.snp.makeConstraints { make in
make.width.equalTo(TabLocationViewUX.ReaderModeButtonWidth)
make.height.equalTo(TabLocationViewUX.ButtonSize)
}
// Setup UIDragInteraction to handle dragging the location
// bar for dropping its URL into other apps.
let dragInteraction = UIDragInteraction(delegate: self)
dragInteraction.allowsSimultaneousRecognitionDuringLift = true
self.addInteraction(dragInteraction)
menuBadge.add(toParent: contentView)
menuBadge.layout(onButton: pageOptionsButton)
menuBadge.show(false)
}
required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private lazy var _accessibilityElements = [urlTextField, readerModeButton, pageOptionsButton, trackingProtectionButton]
override var accessibilityElements: [Any]? {
get {
return _accessibilityElements.filter { !$0.isHidden }
}
set {
super.accessibilityElements = newValue
}
}
func overrideAccessibility(enabled: Bool) {
_accessibilityElements.forEach {
$0.isAccessibilityElement = enabled
}
}
@objc func tapReaderModeButton() {
delegate?.tabLocationViewDidTapReaderMode(self)
}
@objc func longPressReaderModeButton(_ recognizer: UILongPressGestureRecognizer) {
if recognizer.state == .began {
delegate?.tabLocationViewDidLongPressReaderMode(self)
}
}
@objc func didPressPageOptionsButton(_ button: UIButton) {
delegate?.tabLocationViewDidTapPageOptions(self, from: button)
}
@objc func didLongPressPageOptionsButton(_ recognizer: UILongPressGestureRecognizer) {
delegate?.tabLocationViewDidLongPressPageOptions(self)
}
@objc func longPressLocation(_ recognizer: UITapGestureRecognizer) {
if recognizer.state == .began {
delegate?.tabLocationViewDidLongPressLocation(self)
}
}
@objc func tapLocation(_ recognizer: UITapGestureRecognizer) {
delegate?.tabLocationViewDidTapLocation(self)
}
@objc func didPressTPShieldButton(_ button: UIButton) {
delegate?.tabLocationViewDidTapShield(self)
}
@objc func readerModeCustomAction() -> Bool {
return delegate?.tabLocationViewDidLongPressReaderMode(self) ?? false
}
fileprivate func updateTextWithURL() {
if let host = url?.host, AppConstants.MOZ_PUNYCODE {
urlTextField.text = url?.absoluteString.replacingOccurrences(of: host, with: host.asciiHostToUTF8())
} else {
urlTextField.text = url?.absoluteString
}
// remove https:// (the scheme) from the url when displaying
if let scheme = url?.scheme, let range = url?.absoluteString.range(of: "\(scheme)://") {
urlTextField.text = url?.absoluteString.replacingCharacters(in: range, with: "")
}
}
}
extension TabLocationView: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
// When long pressing a button make sure the textfield's long press gesture is not triggered
return !(otherGestureRecognizer.view is UIButton)
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
// If the longPressRecognizer is active, fail the tap recognizer to avoid conflicts.
return gestureRecognizer == longPressRecognizer && otherGestureRecognizer == tapRecognizer
}
}
@available(iOS 11.0, *)
extension TabLocationView: UIDragInteractionDelegate {
func dragInteraction(_ interaction: UIDragInteraction, itemsForBeginning session: UIDragSession) -> [UIDragItem] {
// Ensure we actually have a URL in the location bar and that the URL is not local.
guard let url = self.url, !InternalURL.isValid(url: url), let itemProvider = NSItemProvider(contentsOf: url) else {
return []
}
UnifiedTelemetry.recordEvent(category: .action, method: .drag, object: .locationBar)
let dragItem = UIDragItem(itemProvider: itemProvider)
return [dragItem]
}
func dragInteraction(_ interaction: UIDragInteraction, sessionWillBegin session: UIDragSession) {
delegate?.tabLocationViewDidBeginDragInteraction(self)
}
}
extension TabLocationView: AccessibilityActionsSource {
func accessibilityCustomActionsForView(_ view: UIView) -> [UIAccessibilityCustomAction]? {
if view === urlTextField {
return delegate?.tabLocationViewLocationAccessibilityActions(self)
}
return nil
}
}
extension TabLocationView: Themeable {
func applyTheme() {
backgroundColor = UIColor.theme.textField.background
urlTextField.textColor = UIColor.theme.textField.textAndTint
readerModeButton.selectedTintColor = UIColor.theme.urlbar.readerModeButtonSelected
readerModeButton.unselectedTintColor = UIColor.theme.urlbar.readerModeButtonUnselected
pageOptionsButton.selectedTintColor = UIColor.theme.urlbar.pageOptionsSelected
pageOptionsButton.unselectedTintColor = UIColor.theme.urlbar.pageOptionsUnselected
pageOptionsButton.tintColor = pageOptionsButton.unselectedTintColor
separatorLineForPageOptions.backgroundColor = UIColor.Photon.Grey40
separatorLineForTP.backgroundColor = separatorLineForPageOptions.backgroundColor
lockImageView.tintColor = pageOptionsButton.tintColor
let color = ThemeManager.instance.currentName == .dark ? UIColor(white: 0.3, alpha: 0.6): UIColor.theme.textField.background
menuBadge.badge.tintBackground(color: color)
}
}
extension TabLocationView: TabEventHandler {
func tabDidChangeContentBlocking(_ tab: Tab) {
updateBlockerStatus(forTab: tab)
}
private func updateBlockerStatus(forTab tab: Tab) {
assertIsMainThread("UI changes must be on the main thread")
guard let blocker = tab.contentBlocker else { return }
trackingProtectionButton.alpha = 1.0
switch blocker.status {
case .Blocking:
trackingProtectionButton.setImage(UIImage(imageLiteralResourceName: "tracking-protection-active-block"), for: .normal)
case .NoBlockedURLs:
trackingProtectionButton.setImage(UIImage.templateImageNamed("tracking-protection"), for: .normal)
trackingProtectionButton.alpha = 0.5
case .Whitelisted:
trackingProtectionButton.setImage(UIImage.templateImageNamed("tracking-protection-off"), for: .normal)
case .Disabled:
trackingProtectionButton.isHidden = true
}
}
func tabDidGainFocus(_ tab: Tab) {
updateBlockerStatus(forTab: tab)
menuBadge.show(tab.changedUserAgent)
}
func tabDidToggleDesktopMode(_ tab: Tab) {
menuBadge.show(tab.changedUserAgent)
}
}
class ReaderModeButton: UIButton {
var selectedTintColor: UIColor?
var unselectedTintColor: UIColor?
override init(frame: CGRect) {
super.init(frame: frame)
adjustsImageWhenHighlighted = false
setImage(UIImage.templateImageNamed("reader"), for: .normal)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var isSelected: Bool {
didSet {
self.tintColor = (isHighlighted || isSelected) ? selectedTintColor : unselectedTintColor
}
}
override open var isHighlighted: Bool {
didSet {
self.tintColor = (isHighlighted || isSelected) ? selectedTintColor : unselectedTintColor
}
}
override var tintColor: UIColor! {
didSet {
self.imageView?.tintColor = self.tintColor
}
}
var _readerModeState = ReaderModeState.unavailable
var readerModeState: ReaderModeState {
get {
return _readerModeState
}
set (newReaderModeState) {
_readerModeState = newReaderModeState
switch _readerModeState {
case .available:
self.isEnabled = true
self.isSelected = false
case .unavailable:
self.isEnabled = false
self.isSelected = false
case .active:
self.isEnabled = true
self.isSelected = true
}
}
}
}
private class DisplayTextField: UITextField {
weak var accessibilityActionsSource: AccessibilityActionsSource?
override var accessibilityCustomActions: [UIAccessibilityCustomAction]? {
get {
return accessibilityActionsSource?.accessibilityCustomActionsForView(self)
}
set {
super.accessibilityCustomActions = newValue
}
}
fileprivate override var canBecomeFirstResponder: Bool {
return false
}
override func textRect(forBounds bounds: CGRect) -> CGRect {
return bounds.insetBy(dx: TabLocationViewUX.Spacing, dy: 0)
}
}
| mpl-2.0 | 2d65fe4723cf71cc740693484461b992 | 41.303462 | 270 | 0.697944 | 5.819837 | false | false | false | false |
mumbler/PReVo-iOS | PoshReVo/Motoroj/Pagharo/PaghMotoro.swift | 1 | 1324 | //
// Paghmotoro.swift
// PoshReVo
//
// Created by Robin Hill on 7/6/19.
// Copyright © 2019 Robin Hill. All rights reserved.
//
final class PaghMotoro {
public static let komuna = PaghMotoro()
var paghoj = [Pagho: UIViewController]()
public func ViewControllerPorPagho(paghTipo: Pagho) -> UIViewController {
if let trovitaPagho = paghoj[paghTipo] {
return trovitaPagho
}
else {
let novaPagho: UIViewController
switch paghTipo {
case .Serchi:
novaPagho = SerchPaghoViewController()
break
case .Esplori:
novaPagho = EsplorPaghoViewController(style: .grouped)
break
case .Historio:
novaPagho = HistorioViewController()
break
case .Konservitaj:
novaPagho = KonservitajViewController()
break
case .Agordoj:
novaPagho = AgordojViewController()
break
case .Informoj:
novaPagho = InformojTableViewController(style: .grouped)
break
}
paghoj[paghTipo] = novaPagho
return novaPagho
}
}
}
| mit | c63b435ad6380c43a7640f2030e38f77 | 26 | 77 | 0.517007 | 4.530822 | false | false | false | false |
adelinofaria/Buildasaur | Buildasaur/MenuItemManager.swift | 2 | 2929 | //
// MenuItemManager.swift
// Buildasaur
//
// Created by Honza Dvorsky on 15/05/15.
// Copyright (c) 2015 Honza Dvorsky. All rights reserved.
//
import Cocoa
class MenuItemManager : NSObject, NSMenuDelegate {
private var statusItem: NSStatusItem?
private var firstIndexLastSyncedMenuItem: Int!
func setupMenuBarItem() {
let statusBar = NSStatusBar.systemStatusBar()
let statusItem = statusBar.statusItemWithLength(32)
statusItem.title = ""
let image = NSImage(named: "icon")
image?.setTemplate(true)
statusItem.image = image
statusItem.highlightMode = true
var menu = NSMenu()
menu.addItemWithTitle("Open Buildasaur", action: "showMainWindow", keyEquivalent: "")
menu.addItem(NSMenuItem.separatorItem())
self.firstIndexLastSyncedMenuItem = menu.numberOfItems
statusItem.menu = menu
menu.delegate = self
self.statusItem = statusItem
}
func menuWillOpen(menu: NSMenu) {
//update with last sync/statuses
let syncers = StorageManager.sharedInstance.syncers
//remove items for existing syncers
let itemsForSyncers = menu.numberOfItems - self.firstIndexLastSyncedMenuItem
let diffItems = syncers.count - itemsForSyncers
//this many items need to be created or destroyed
if diffItems > 0 {
for i in 0..<diffItems {
menu.addItemWithTitle("", action: "", keyEquivalent: "")
}
} else if diffItems < 0 {
for i in 0..<abs(diffItems) {
menu.removeItemAtIndex(menu.numberOfItems-1)
}
}
//now we have the right number, update the data
let texts = syncers.map({ (syncer: HDGitHubXCBotSyncer) -> String in
let statusEmoji: String
if syncer.active {
statusEmoji = "✔️"
} else {
statusEmoji = "✖️"
}
let repo: String
if let repoName = syncer.localSource.githubRepoName() {
repo = repoName
} else {
repo = "???"
}
let time: String
if let lastSuccess = syncer.lastSuccessfulSyncFinishedDate where syncer.active {
time = "last synced \(lastSuccess.nicelyFormattedRelativeTimeToNow())"
} else {
time = "is not active"
}
let report = "\(statusEmoji) \(repo) \(time)"
return report
})
//fill into items
for (let i, let text) in enumerate(texts) {
let idx = self.firstIndexLastSyncedMenuItem + i
let item = menu.itemAtIndex(idx)
item?.title = text
}
}
}
| mit | 3a6d117cf4c201abf520ff292764527a | 30.408602 | 93 | 0.551523 | 5.197509 | false | false | false | false |
vbudhram/firefox-ios | XCUITests/TopTabsTest.swift | 1 | 11805 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import XCTest
let url = "www.mozilla.org"
let urlLabel = "Internet for people, not profit — Mozilla"
let urlValue = "mozilla.org"
let urlExample = "example.com"
let urlLabelExample = "Example Domain"
let urlValueExample = "example"
class TopTabsTest: BaseTestCase {
func testAddTabFromSettings() {
navigator.createNewTab()
navigator.openURL(url)
waitForValueContains(app.textFields["url"], value: urlValue)
waitforExistence(app.buttons["Show Tabs"])
let numTab = app.buttons["Show Tabs"].value as? String
XCTAssertEqual("2", numTab)
}
func testAddTabFromTabTray() {
navigator.goto(TabTray)
navigator.openURL(url)
waitUntilPageLoad()
waitForValueContains(app.textFields["url"], value: urlValue)
// The tabs counter shows the correct number
let tabsOpen = app.buttons["Show Tabs"].value
XCTAssertEqual("2", tabsOpen as? String)
// The tab tray shows the correct tabs
navigator.goto(TabTray)
waitforExistence(app.collectionViews.cells[urlLabel])
}
private func checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: Int) {
navigator.goto(TabTray)
let numTabsOpen = userState.numTabs
XCTAssertEqual(numTabsOpen, expectedNumberOfTabsOpen, "The number of tabs open is not correct")
}
private func closeTabTrayView(goBackToBrowserTab: String) {
app.collectionViews.cells[goBackToBrowserTab].firstMatch.tap()
navigator.nowAt(BrowserTab)
}
func testAddTabFromContext() {
navigator.openURL(urlExample)
// Initially there is only one tab open
let tabsOpenInitially = app.buttons["Show Tabs"].value
XCTAssertEqual("1", tabsOpenInitially as? String)
// Open link in a different tab and switch to it
waitforExistence(app.webViews.links.staticTexts["More information..."])
app.webViews.links.staticTexts["More information..."].press(forDuration: 5)
app.buttons["Open in New Tab"].tap()
waitUntilPageLoad()
// Open tab tray to check that both tabs are there
checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: 2)
waitforExistence(app.collectionViews.cells["Example Domain"])
waitforExistence(app.collectionViews.cells["IANA — IANA-managed Reserved Domains"])
}
// This test only runs for iPhone see bug 1409750
func testAddTabByLongPressTabsButton() {
navigator.performAction(Action.OpenNewTabLongPressTabsButton)
checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: 2)
}
// This test only runs for iPhone see bug 1409750
func testAddPrivateTabByLongPressTabsButton() {
navigator.performAction(Action.OpenPrivateTabLongPressTabsButton)
checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: 1)
waitforExistence(app.buttons["TabTrayController.maskButton"])
XCTAssertTrue(app.buttons["TabTrayController.maskButton"].isEnabled)
XCTAssertTrue(userState.isPrivate)
}
func testSwitchBetweenTabs() {
// Open two urls from tab tray and switch between them
navigator.openURL(url)
navigator.goto(TabTray)
navigator.openURL(urlExample)
navigator.goto(TabTray)
waitforExistence(app.collectionViews.cells[urlLabel])
app.collectionViews.cells[urlLabel].tap()
waitForValueContains(app.textFields["url"], value: urlValue)
navigator.nowAt(BrowserTab)
navigator.goto(TabTray)
waitforExistence(app.collectionViews.cells[urlLabelExample])
app.collectionViews.cells[urlLabelExample].tap()
waitForValueContains(app.textFields["url"], value: urlValueExample)
}
// This test is disabled for iPad because the toast menu is not shown there
func testSwitchBetweenTabsToastButton() {
navigator.openURL(url)
waitUntilPageLoad()
app.webViews.links["Rust"].press(forDuration: 1)
waitforExistence(app.sheets.buttons["Open in New Tab"])
app.sheets.buttons["Open in New Tab"].press(forDuration: 1)
waitforExistence(app.buttons["Switch"])
app.buttons["Switch"].tap()
// Check that the tab has changed
waitUntilPageLoad()
waitForValueContains(app.textFields["url"], value: "rust")
XCTAssertTrue(app.staticTexts["Rust language"].exists)
let numTab = app.buttons["Show Tabs"].value as? String
XCTAssertEqual("2", numTab)
// Go to Private mode and do the same
navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode)
navigator.openURL(url)
waitUntilPageLoad()
app.webViews.links["Rust"].press(forDuration: 1)
waitforExistence(app.sheets.buttons["Open in New Private Tab"])
app.sheets.buttons["Open in New Private Tab"].press(forDuration: 1)
waitforExistence(app.buttons["Switch"])
app.buttons["Switch"].tap()
// Check that the tab has changed
waitUntilPageLoad()
waitForValueContains(app.textFields["url"], value: "rust")
XCTAssertTrue(app.staticTexts["Rust language"].exists)
let numPrivTab = app.buttons["Show Tabs"].value as? String
XCTAssertEqual("2", numPrivTab)
}
// This test is disabled for iPad because the toast menu is not shown there
func testSwitchBetweenTabsNoPrivatePrivateToastButton() {
navigator.openURL(url)
waitUntilPageLoad()
app.webViews.links["Rust"].press(forDuration: 1)
waitforExistence(app.sheets.buttons["Open in New Tab"])
app.sheets.buttons["Open in New Private Tab"].press(forDuration: 1)
waitforExistence(app.buttons["Switch"])
app.buttons["Switch"].tap()
// Check that the tab has changed to the new open one and that the user is in private mode
waitUntilPageLoad()
waitForValueContains(app.textFields["url"], value: "rust")
XCTAssertTrue(app.staticTexts["Rust language"].exists)
navigator.goto(TabTray)
XCTAssertTrue(app.buttons["TabTrayController.maskButton"].isEnabled)
}
func testCloseOneTab() {
navigator.openURL(url)
waitUntilPageLoad()
navigator.goto(TabTray)
waitforExistence(app.collectionViews.cells[urlLabel])
// 'x' button to close the tab is not visible, so closing by swiping the tab
app.collectionViews.cells[urlLabel].swipeRight()
// After removing only one tab it automatically goes to HomepanelView
waitforExistence(app.collectionViews.cells["TopSitesCell"])
XCTAssert(app.buttons["HomePanels.TopSites"].exists)
}
func testCloseAllTabsUndo() {
// A different tab than home is open to do the proper checks
navigator.openURL(url)
waitUntilPageLoad()
navigator.createSeveralTabsFromTabTray (numberTabs: 3)
navigator.goto(TabTray)
waitforExistence(app.collectionViews.cells[urlLabel])
checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: 4)
// Close all tabs, undo it and check that the number of tabs is correct
navigator.closeAllTabs()
app.buttons["Undo"].tap()
navigator.nowAt(BrowserTab)
checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: 4)
waitforExistence(app.collectionViews.cells[urlLabel])
}
func testCloseAllTabsPrivateModeUndo() {
// A different tab than home is open to do the proper checks
navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode)
navigator.openURL(url)
waitUntilPageLoad()
navigator.createSeveralTabsFromTabTray (numberTabs: 3)
navigator.goto(TabTray)
waitforExistence(app.collectionViews.cells[urlLabel])
checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: 4)
// Close all tabs, undo it and check that the number of tabs is correct
navigator.closeAllTabs()
XCTAssertTrue(app.staticTexts["Private Browsing"].exists, "Private welcome screen is not shown")
app.buttons["Undo"].tap()
navigator.nowAt(BrowserTab)
checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: 4)
waitforExistence(app.collectionViews.cells[urlLabel])
}
func testCloseAllTabs() {
// A different tab than home is open to do the proper checks
navigator.openURL(url)
waitUntilPageLoad()
// Add several tabs from tab tray menu and check that the number is correct before closing all
navigator.createSeveralTabsFromTabTray (numberTabs: 3)
navigator.goto(TabTray)
waitforExistence(app.collectionViews.cells[urlLabel])
checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: 4)
// Close all tabs and check that the number of tabs is correct
navigator.closeAllTabs()
checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: 1)
waitforNoExistence(app.collectionViews.cells[urlLabel])
}
func testCloseAllTabsPrivateMode() {
// A different tab than home is open to do the proper checks
navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode)
navigator.openURL(url)
waitUntilPageLoad()
// Add several tabs from tab tray menu and check that the number is correct before closing all
navigator.createSeveralTabsFromTabTray (numberTabs: 3)
navigator.goto(TabTray)
waitforExistence(app.collectionViews.cells[urlLabel])
checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: 4)
// Close all tabs and check that the number of tabs is correct
navigator.closeAllTabs()
XCTAssertTrue(app.staticTexts["Private Browsing"].exists, "Private welcome screen is not shown")
}
func testCloseTabFromPageOptionsMenu() {
// Open two websites so that there are two tabs open and the page options menu is available
navigator.openURL(urlValue)
navigator.openNewURL(urlString: urlExample)
checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: 2)
// Go back to one website so that the page options menu is available and close one tab from there
closeTabTrayView(goBackToBrowserTab: urlLabelExample)
navigator.performAction(Action.CloseTabFromPageOptions)
checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: 1)
// Go back to the website left open, close it and check that it has been closed
closeTabTrayView(goBackToBrowserTab: urlLabel)
navigator.performAction(Action.CloseTabFromPageOptions)
checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: 1)
waitforNoExistence(app.collectionViews.cells[urlLabel])
}
func testCloseTabFromLongPressTabsButton() {
// This menu is available in HomeScreen or NewTabScreen, so no need to open new websites
navigator.performAction(Action.OpenNewTabFromTabTray)
checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: 2)
closeTabTrayView(goBackToBrowserTab: "home")
navigator.performAction(Action.CloseTabFromTabTrayLongPressMenu)
checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: 1)
closeTabTrayView(goBackToBrowserTab: "home")
navigator.performAction(Action.CloseTabFromTabTrayLongPressMenu)
checkNumberOfTabsExpectedToBeOpen(expectedNumberOfTabsOpen: 1)
closeTabTrayView(goBackToBrowserTab: "home")
}
}
| mpl-2.0 | 574a1a0a4f3a5b916b2163e1510f0f3e | 41.602888 | 105 | 0.705279 | 5.356786 | false | true | false | false |
practicalswift/swift | test/Compatibility/MixAndMatch/Inputs/witness_change_swift4_leaf.swift | 35 | 2941 |
// Swift 4 sees the ObjC class NSRuncibleSpoon as the class, and uses methods
// with type signatures involving NSRuncibleSpoon to conform to protocols
// across the language boundary. Swift 5 sees the type as bridged to
// a RuncibleSpoon value type, but still needs to be able to use conformances
// declared by Swift 4.
// Swift 4, importing Swift 4 and Swift 5 code
import SomeObjCModule
import SomeSwift4Module
import SomeSwift5Module
func testMatchAndMix(bridged: RuncibleSpoon, unbridged: NSRuncibleSpoon) {
let objcInstanceViaClass
= SomeObjCClass(someSwiftInitRequirement: unbridged)
let objcClassAsS4Protocol: SomeSwift4Protocol.Type = SomeObjCClass.self
let objcInstanceViaS4Protocol
= objcClassAsS4Protocol.init(someSwiftInitRequirement: unbridged)
let objcClassAsS5Protocol: SomeSwift5Protocol.Type = SomeObjCClass.self
let objcInstanceViaS5Protocol
= objcClassAsS5Protocol.init(someSwiftInitRequirement: bridged)
var bridgedSink: RuncibleSpoon
var unbridgedSink: NSRuncibleSpoon
let swiftPropertyViaClass = objcInstanceViaClass.someSwiftPropertyRequirement
unbridgedSink = swiftPropertyViaClass
let swiftPropertyViaS4Protocol = objcInstanceViaS4Protocol.someSwiftPropertyRequirement
unbridgedSink = swiftPropertyViaS4Protocol
let swiftPropertyViaS5Protocol = objcInstanceViaS5Protocol.someSwiftPropertyRequirement
bridgedSink = swiftPropertyViaS5Protocol
objcInstanceViaClass.someSwiftMethodRequirement(unbridged)
objcInstanceViaS4Protocol.someSwiftMethodRequirement(unbridged)
objcInstanceViaS5Protocol.someSwiftMethodRequirement(bridged)
let swift4InstanceViaClass
= SomeSwift4Class(someObjCInitRequirement: unbridged)
let swift4ClassAsProtocol: SomeObjCProtocol.Type = SomeSwift4Class.self
let swift4InstanceViaProtocol
= swift4ClassAsProtocol.init(someObjCInitRequirement: unbridged)
let objcPropertyViaClassS4 = swift4InstanceViaClass.someObjCPropertyRequirement
unbridgedSink = objcPropertyViaClassS4
let objcPropertyViaProtocolS4 = swift4InstanceViaProtocol.someObjCPropertyRequirement
unbridgedSink = objcPropertyViaProtocolS4
swift4InstanceViaClass.someObjCMethodRequirement(unbridged)
swift4InstanceViaProtocol.someObjCMethodRequirement(unbridged)
let swift5InstanceViaClass
= SomeSwift5Class(someObjCInitRequirement: bridged)
let swift5ClassAsProtocol: SomeObjCProtocol.Type = SomeSwift5Class.self
let swift5InstanceViaProtocol
= swift5ClassAsProtocol.init(someObjCInitRequirement: unbridged)
let objcPropertyViaClassS5 = swift5InstanceViaClass.someObjCPropertyRequirement
bridgedSink = objcPropertyViaClassS5
let objcPropertyViaProtocolS5 = swift5InstanceViaProtocol.someObjCPropertyRequirement
unbridgedSink = objcPropertyViaProtocolS5
swift5InstanceViaClass.someObjCMethodRequirement(bridged)
swift5InstanceViaProtocol.someObjCMethodRequirement(unbridged)
_ = bridgedSink
_ = unbridgedSink
}
| apache-2.0 | caa664e1d227cc7d1fee79ed4610b2a6 | 40.422535 | 89 | 0.849371 | 4.274709 | false | false | false | false |
AlexZd/SwiftUtils | Pod/Utils/UIView+Helpers/UILabel+Helpers.swift | 1 | 2926 | //
// UILabel+Helpers.swift
// GPSChat
//
// Created by Alex on 08.06.15.
// Copyright (c) 2015 AlexZd. All rights reserved.
//
import UIKit
extension UILabel{
/** Width for current text in label */
public var labelWidth: CGFloat {
let rect = self.text?.boundingRect(with: CGSize(width: .greatestFiniteMagnitude, height: frame.size.height),
options: .usesLineFragmentOrigin,
attributes: [.font: font],
context: nil) ?? .zero
return rect.size.width
}
/** Height for current text in label */
public var labelHeight: CGFloat {
let rect = self.text?.boundingRect(with: CGSize(width: frame.size.width, height: .greatestFiniteMagnitude),
options: .usesLineFragmentOrigin,
attributes: [.font: font],
context: nil) ?? .zero
return rect.size.height
}
/** Width for current text in label with SizeToFit method */
public var labelWidthSizeToFit: CGFloat {
let sizeNew = self.sizeThatFits(CGSize(width: .greatestFiniteMagnitude, height: frame.size.height))
return sizeNew.width
}
/** Height for current text in label with SizeToFit method */
public var labelHeightSizeToFit: CGFloat {
let sizeNew = self.sizeThatFits(CGSize(width: frame.size.width, height: .greatestFiniteMagnitude))
return sizeNew.height
}
/** Changes width constraint to fit text*/
public func widthToFitConstraint(update: Bool) {
self.setWidth(width: self.labelWidthSizeToFit, update: update)
}
/** Get size for current text in label with max and min size */
public func getLabelSize(maxSize: CGSize, minSize: CGSize) -> CGSize {
var sizeNew = sizeThatFits(maxSize)
if sizeNew.height < minSize.height {
sizeNew.height = minSize.height
}
if sizeNew.width < minSize.width {
sizeNew.width = minSize.width
}
return sizeNew
}
/** Get CGRect of substring */
public func boundingRectForCharacterRange(range: NSRange) -> CGRect {
let textStorage = NSTextStorage(attributedString: self.attributedText!)
let layoutManager = NSLayoutManager()
textStorage.addLayoutManager(layoutManager)
let textContainer = NSTextContainer(size: self.bounds.size)
textContainer.lineFragmentPadding = 0
layoutManager.addTextContainer(textContainer)
var glyphRange: NSRange = NSRange(location: 0, length: 1)
layoutManager.characterRange(forGlyphRange: range, actualGlyphRange: &glyphRange)
return layoutManager.boundingRect(forGlyphRange: glyphRange, in: textContainer)
}
}
| mit | 8a1b892dda513bab72a2065c2c67b1a2 | 37.5 | 116 | 0.612782 | 5.169611 | false | true | false | false |
iOSWizards/AwesomeMedia | Example/Pods/AwesomeCore/AwesomeCore/Classes/DataAccess/QuestCategoryDA.swift | 1 | 3410 | //
// QuestCategoryDA.swift
// AwesomeCore
//
// Created by Antonio on 1/9/18.
//
//import Foundation
//
//class QuestCategoryDA {
//
// // MARK: - Parser
//
// func parseToCoreData(_ questCategory: QuestCategory, result: @escaping (CDCategory) -> Void) {
// AwesomeCoreDataAccess.shared.backgroundContext.perform {
// let cdCategory = self.parseToCoreData(questCategory)
// result(cdCategory)
// }
// }
//
// func parseToCoreData(_ questCategory: QuestCategory) -> CDCategory {
//
// guard let categoryId = questCategory.id else {
// fatalError("CDCategory object can't be created without id.")
// }
// let p = predicate(categoryId, questCategory.questId ?? "")
// let cdCategory = CDCategory.getObjectAC(predicate: p, createIfNil: true) as! CDCategory
//
// cdCategory.id = questCategory.id
// cdCategory.name = questCategory.name
// return cdCategory
// }
//
// func parseFromCoreData(_ cdCategory: CDCategory) -> QuestCategory {
//
// /**
// * As we have a relationship QuestCategory to Many Quests we have to go through
// * both relationships looking for a combination.
// */
// var questId: String? {
// guard let quests = cdCategory.quests else { return nil }
// for cdQuest in quests.allObjects {
// if (cdQuest as! CDQuest).categories == nil { continue }
// for categories in (cdQuest as! CDQuest).categories!.allObjects where (categories as! CDCategory) == cdCategory {
// return (cdQuest as! CDQuest).id
// }
// }
// return nil
// }
//
// return QuestCategory(id: cdCategory.id, name: cdCategory.name, questId: questId)
// }
//
// // MARK: - Fetch
//
// func loadBy(categoryId: String, questId: String, result: @escaping (CDCategory?) -> Void) {
// func perform() {
// let p = predicate(categoryId, questId)
// guard let cdCategory = CDCategory.listAC(predicate: p).first as? CDCategory else {
// result(nil)
// return
// }
// result(cdCategory)
// }
// AwesomeCoreDataAccess.shared.performBackgroundBatchOperation({ (workerContext) in
// perform()
// })
// }
//
// // MARK: - Helpers
//
// func extractCDCategories(_ questCategories: [QuestCategory]?) -> NSSet {
// var categories = NSSet()
// guard let questCategories = questCategories else { return categories }
// for qc in questCategories {
// categories = categories.adding(parseToCoreData(qc)) as NSSet
// }
// return categories
// }
//
// func extractQuestCategories(_ questCategories: NSSet?) -> [QuestCategory] {
// var categories = [QuestCategory]()
// guard let questCategories = questCategories else { return categories }
// for qc in questCategories {
// categories.append(parseFromCoreData(qc as! CDCategory))
// }
// return categories
// }
//
// private func predicate(_ categoryId: String, _ questId: String) -> NSPredicate {
// return NSPredicate(format: "id == %@ AND quests.id CONTAINS[cd] %@", categoryId, questId)
// }
//
//}
| mit | 1f220b2765ef1541dd95fdcb9ad21f76 | 35.276596 | 130 | 0.573314 | 3.960511 | false | false | false | false |
fthomasmorel/FBSideMenuViewController | FBNavigationPattern/Pod/FBSideMenuViewController.swift | 1 | 6324 | //
// FBSideMenuViewController.swift
// FBNavigationPattern
//
// Created by Florent TM on 31/07/2015.
// Copyright © 2015 Florent THOMAS-MOREL. All rights reserved.
//
import Foundation
import UIKit
//MARK: - Enum
public enum FBSideMenuMode:Int{
case SwipeToReach
case SwipeFromScratch
}
//MARK: - FBSideMenuViewController Class
public class FBSideMenuViewController: UIViewController, FBMenuDelegate, UINavigationControllerDelegate, UITableViewDataSource, UITableViewDelegate{
//MARK: - Attributes
@IBOutlet weak var tableView: UITableView!
private var images:[UIImage]!
private var viewControllers:[UIViewController]!
private var animator:UIDynamicAnimator!
public var navigationContainer:FBNavigationController!
public var pictoAnimation:((desactive:UIImageView?, active:UIImageView?, index:Int) -> Void)?
//MARK: - Init
public init(viewsControllers:[UIViewController], withImages images:[UIImage], forLimit limit:CGFloat, withMode mode:FBSideMenuMode){
self.images = images
self.viewControllers = viewsControllers
super.init(nibName: "FBSideMenuViewController", bundle: NSBundle(forClass: FBSideMenuViewController.self))
self.navigationContainer = FBNavigationController(numberOfItem: min(images.count,viewControllers.count), withMaxLimit: limit, andMode: mode)
self.navigationContainer.menuDelegate = self
self.navigationContainer.delegate = self
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
//MARK: - Override
override public func viewWillAppear(animated: Bool) {
self.tableView.backgroundColor = self.view.backgroundColor
self.view.addSubview(navigationContainer.view)
self.addChildViewController(navigationContainer)
self.navigationContainer.view.addSubview(viewControllers.first!.view)
}
override public func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.registerNib(UINib(nibName: "FBTableViewCell", bundle: NSBundle(forClass: FBTableViewCell.self)), forCellReuseIdentifier: kFBCellIdentifier)
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - FBMenuDelegate
func didChangeCurrentIndex(lastIndex lastIndex: Int, toNewIndex index: Int) {
let lastCell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: lastIndex, inSection: 0)) as? FBTableViewCell
let newCell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: index, inSection: 0)) as? FBTableViewCell
if let _ = pictoAnimation {
UIView.animateWithDuration(0.25) { () -> Void in
self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: index, inSection: 0), atScrollPosition: .Middle, animated: true)
self.pictoAnimation!(desactive: lastCell?.pictoView, active: newCell?.pictoView, index:index)
}
}else{
UIView.animateWithDuration(0.25) { () -> Void in
lastCell?.pictoView.alpha = 0.2
newCell?.pictoView.alpha = 1
lastCell?.pictoView.transform = CGAffineTransformMakeScale(0.8,0.8);
newCell?.pictoView.transform = CGAffineTransformMakeScale(1,1);
}
}
if lastIndex < index || self.navigationContainer.mode == .SwipeFromScratch {
self.navigationContainer.view.addSubview(self.viewControllers[index].view)
}else if !(lastIndex == index) {
self.viewControllers[lastIndex].view.removeFromSuperview()
}
}
func didFailToOpenMenu(){
self.animator = UIDynamicAnimator(referenceView: self.view)
let collisionBehaviour = UICollisionBehavior(items: [self.navigationContainer.view])
collisionBehaviour.addBoundaryWithIdentifier("frame-left", fromPoint: CGPointMake(-1, 0), toPoint: CGPointMake(-1, self.view.frame.size.height))
self.animator.addBehavior(collisionBehaviour)
let gravityBehaviour = UIGravityBehavior(items: [self.navigationContainer.view])
gravityBehaviour.gravityDirection = CGVectorMake(-3, 0)
self.animator.addBehavior(gravityBehaviour)
let itemBehaviour = UIDynamicItemBehavior(items: [self.navigationContainer.view])
itemBehaviour.elasticity = 0.50
self.animator.addBehavior(itemBehaviour)
}
//MARK: - UINavigationControllerDelegate
public func navigationController(navigationController: UINavigationController, didShowViewController viewController: UIViewController, animated: Bool) {
let gesture = UIPanGestureRecognizer(target: self.navigationContainer, action: "handlePan:")
viewController.view.addGestureRecognizer(gesture)
}
//MARK: - UITableViewDataSource
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:FBTableViewCell!
if let tmp = tableView.dequeueReusableCellWithIdentifier(kFBCellIdentifier) as? FBTableViewCell{
cell = tmp
}else{
cell = FBTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: kFBCellIdentifier)
}
cell.pictoView.contentMode = .ScaleAspectFill
cell.pictoView.image = images[indexPath.row]
if let _ = pictoAnimation {
self.pictoAnimation!(desactive: cell.pictoView, active: nil, index:indexPath.row)
}else{
cell.pictoView.alpha = 0.2
cell.pictoView.transform = CGAffineTransformMakeScale(0.8,0.8);
}
cell.backgroundColor = self.view.backgroundColor
return cell
}
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.images.count
}
//MARK: - UITableViewDelegate
public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 100
}
} | mit | 66647806b5cad24a22e740960d8e79ef | 38.279503 | 162 | 0.688123 | 5.11156 | false | false | false | false |
vector-im/riot-ios | Riot/Modules/KeyVerification/User/SessionsStatus/UserVerificationSessionStatusCell.swift | 2 | 2478 | /*
Copyright 2020 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import Reusable
struct UserVerificationSessionStatusViewData {
let deviceId: String
let sessionName: String
let isTrusted: Bool
}
final class UserVerificationSessionStatusCell: UITableViewCell, NibReusable, Themable {
// MARK: - Properties
// MARK: Outlets
@IBOutlet private weak var statusImageView: UIImageView!
@IBOutlet private weak var sessionNameLabel: UILabel!
@IBOutlet private weak var statusTextLabel: UILabel!
// MARK: Private
private var viewData: UserVerificationSessionStatusViewData?
private var theme: Theme?
// MARK: - Public
func fill(viewData: UserVerificationSessionStatusViewData) {
self.viewData = viewData
let statusText: String
let statusImage: UIImage
if viewData.isTrusted {
statusImage = Asset.Images.encryptionTrusted.image
statusText = VectorL10n.userVerificationSessionsListSessionTrusted
} else {
statusImage = Asset.Images.encryptionWarning.image
statusText = VectorL10n.userVerificationSessionsListSessionUntrusted
}
self.statusImageView.image = statusImage
self.statusTextLabel.text = statusText
self.sessionNameLabel.text = viewData.sessionName
self.updateStatusTextColor()
}
func update(theme: Theme) {
self.theme = theme
self.backgroundColor = theme.headerBackgroundColor
self.sessionNameLabel.textColor = theme.textPrimaryColor
self.updateStatusTextColor()
}
// MARK: - Private
private func updateStatusTextColor() {
guard let viewData = self.viewData, let theme = self.theme else {
return
}
self.statusTextLabel.textColor = viewData.isTrusted ? theme.tintColor : theme.warningColor
}
}
| apache-2.0 | 2eb9cbde4f806486d150fdffd60fe170 | 30.367089 | 98 | 0.690476 | 5.216842 | false | false | false | false |
RoverPlatform/rover-ios | Sources/UI/Services/Router/RouterService.swift | 1 | 2444 | //
// RouterService.swift
// RoverUI
//
// Created by Sean Rucker on 2018-04-22.
// Copyright © 2018 Rover Labs Inc. All rights reserved.
//
import Foundation
#if !COCOAPODS
import RoverFoundation
#endif
class RouterService: Router {
let associatedDomains: [String]
let urlSchemes: [String]
let dispatcher: Dispatcher
var handlers = [RouteHandler]()
init(associatedDomains: [String], urlSchemes: [String], dispatcher: Dispatcher) {
self.associatedDomains = associatedDomains
self.urlSchemes = urlSchemes
self.dispatcher = dispatcher
}
func addHandler(_ handler: RouteHandler) {
handlers.append(handler)
}
func handle(_ userActivity: NSUserActivity) -> Bool {
guard let action = action(for: userActivity) else {
return false
}
dispatcher.dispatch(action, completionHandler: nil)
return true
}
func action(for userActivity: NSUserActivity) -> Action? {
guard userActivity.activityType == NSUserActivityTypeBrowsingWeb, let url = userActivity.webpageURL else {
return nil
}
return action(for: url)
}
func handle(_ url: URL) -> Bool {
guard let action = action(for: url) else {
return false
}
dispatcher.dispatch(action, completionHandler: nil)
return true
}
func action(for url: URL) -> Action? {
if isUniversalLink(url: url) {
for handler in handlers {
if let action = handler.universalLinkAction(url: url) {
return action
}
}
} else if isDeepLink(url: url) {
for handler in handlers {
if let action = handler.deepLinkAction(url: url) {
return action
}
}
}
return nil
}
func isUniversalLink(url: URL) -> Bool {
guard let scheme = url.scheme, ["http", "https"].contains(scheme) else {
return false
}
guard let host = url.host, associatedDomains.contains(host) else {
return false
}
return true
}
func isDeepLink(url: URL) -> Bool {
guard let scheme = url.scheme else {
return false
}
return urlSchemes.contains(scheme)
}
}
| apache-2.0 | 0e8d4719632992c53585136bed87e855 | 24.715789 | 114 | 0.559558 | 4.925403 | false | false | false | false |
joeyg/ios_yelp_swift | Yelp/Business.swift | 3 | 3202 | //
// Business.swift
// Yelp
//
// Created by Timothy Lee on 4/23/15.
// Copyright (c) 2015 Timothy Lee. All rights reserved.
//
import UIKit
class Business: NSObject {
let name: String?
let address: String?
let imageURL: NSURL?
let categories: String?
let distance: String?
let ratingImageURL: NSURL?
let reviewCount: NSNumber?
init(dictionary: NSDictionary) {
name = dictionary["name"] as? String
let imageURLString = dictionary["image_url"] as? String
if imageURLString != nil {
imageURL = NSURL(string: imageURLString!)!
} else {
imageURL = nil
}
let location = dictionary["location"] as? NSDictionary
var address = ""
if location != nil {
let addressArray = location!["address"] as? NSArray
var street: String? = ""
if addressArray != nil && addressArray!.count > 0 {
address = addressArray![0] as! String
}
var neighborhoods = location!["neighborhoods"] as? NSArray
if neighborhoods != nil && neighborhoods!.count > 0 {
if !address.isEmpty {
address += ", "
}
address += neighborhoods![0] as! String
}
}
self.address = address
let categoriesArray = dictionary["categories"] as? [[String]]
if categoriesArray != nil {
var categoryNames = [String]()
for category in categoriesArray! {
var categoryName = category[0]
categoryNames.append(categoryName)
}
categories = ", ".join(categoryNames)
} else {
categories = nil
}
let distanceMeters = dictionary["distance"] as? NSNumber
if distanceMeters != nil {
let milesPerMeter = 0.000621371
distance = String(format: "%.2f mi", milesPerMeter * distanceMeters!.doubleValue)
} else {
distance = nil
}
let ratingImageURLString = dictionary["rating_img_url_large"] as? String
if ratingImageURLString != nil {
ratingImageURL = NSURL(string: ratingImageURLString!)
} else {
ratingImageURL = nil
}
reviewCount = dictionary["review_count"] as? NSNumber
}
class func businesses(#array: [NSDictionary]) -> [Business] {
var businesses = [Business]()
for dictionary in array {
var business = Business(dictionary: dictionary)
businesses.append(business)
}
return businesses
}
class func searchWithTerm(term: String, completion: ([Business]!, NSError!) -> Void) {
YelpClient.sharedInstance.searchWithTerm(term, completion: completion)
}
class func searchWithTerm(term: String, sort: YelpSortMode?, categories: [String]?, deals: Bool?, completion: ([Business]!, NSError!) -> Void) -> Void {
YelpClient.sharedInstance.searchWithTerm(term, sort: sort, categories: categories, deals: deals, completion: completion)
}
}
| mit | 942add4f22b318547cabf9faa282e455 | 32.705263 | 156 | 0.564335 | 4.979782 | false | false | false | false |
vanyaland/Tagger | Tagger/Sources/Model/PlainObjects/Flickr/FlickrUser.swift | 1 | 2546 | /**
* Copyright (c) 2016 Ivan Magda
*
* 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
// MARK: Types
private enum CoderKey: String {
case fullname
case username
case userID
}
// MARK: - FlickrUser: NSObject, NSCoding
class FlickrUser: NSObject, NSCoding {
// MARK: - Properties
let fullname: String
let username: String
let userID: String
override var description: String {
return "FlickrUser {\n\tFullname: \(fullname)\n\tUsername: \(username)\n\tUserID: \(userID).\n}"
}
// MARK: Init
init(fullname: String, username: String, userID: String) {
self.fullname = fullname
self.username = username
self.userID = userID
}
// MARK: NSCoding
required convenience init?(coder aDecoder: NSCoder) {
guard let fullname = aDecoder.decodeObject(forKey: CoderKey.fullname.rawValue) as? String,
let username = aDecoder.decodeObject(forKey: CoderKey.username.rawValue) as? String,
let userID = aDecoder.decodeObject(forKey: CoderKey.userID.rawValue) as? String else {
return nil
}
self.init(fullname: fullname, username: username, userID: userID)
}
func encode(with aCoder: NSCoder) {
aCoder.encode(fullname, forKey: CoderKey.fullname.rawValue)
aCoder.encode(username, forKey: CoderKey.username.rawValue)
aCoder.encode(userID, forKey: CoderKey.userID.rawValue)
}
}
| mit | 07d795f9c98d73be8e7da99f4a8006da | 33.876712 | 104 | 0.691673 | 4.506195 | false | false | false | false |
ncalexan/firefox-ios | Client/Frontend/Browser/ReaderModeBarView.swift | 2 | 6534 | /* 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
import SnapKit
import Shared
import XCGLogger
private let log = Logger.browserLogger
enum ReaderModeBarButtonType {
case markAsRead, markAsUnread, settings, addToReadingList, removeFromReadingList
fileprivate var localizedDescription: String {
switch self {
case .markAsRead: return NSLocalizedString("Mark as Read", comment: "Name for Mark as read button in reader mode")
case .markAsUnread: return NSLocalizedString("Mark as Unread", comment: "Name for Mark as unread button in reader mode")
case .settings: return NSLocalizedString("Display Settings", comment: "Name for display settings button in reader mode. Display in the meaning of presentation, not monitor.")
case .addToReadingList: return NSLocalizedString("Add to Reading List", comment: "Name for button adding current article to reading list in reader mode")
case .removeFromReadingList: return NSLocalizedString("Remove from Reading List", comment: "Name for button removing current article from reading list in reader mode")
}
}
fileprivate var imageName: String {
switch self {
case .markAsRead: return "MarkAsRead"
case .markAsUnread: return "MarkAsUnread"
case .settings: return "SettingsSerif"
case .addToReadingList: return "addToReadingList"
case .removeFromReadingList: return "removeFromReadingList"
}
}
fileprivate var image: UIImage? {
let image = UIImage(named: imageName)
image?.accessibilityLabel = localizedDescription
return image
}
}
protocol ReaderModeBarViewDelegate {
func readerModeBar(_ readerModeBar: ReaderModeBarView, didSelectButton buttonType: ReaderModeBarButtonType)
}
struct ReaderModeBarViewUX {
static let Themes: [String: Theme] = {
var themes = [String: Theme]()
var theme = Theme()
theme.backgroundColor = UIConstants.PrivateModeAssistantToolbarBackgroundColor
theme.buttonTintColor = UIColor.white
themes[Theme.PrivateMode] = theme
theme = Theme()
theme.backgroundColor = UIColor.white
theme.buttonTintColor = UIColor.darkGray
themes[Theme.NormalMode] = theme
return themes
}()
}
class ReaderModeBarView: UIView {
var delegate: ReaderModeBarViewDelegate?
var readStatusButton: UIButton!
var settingsButton: UIButton!
var listStatusButton: UIButton!
dynamic var buttonTintColor: UIColor = UIColor.clear {
didSet {
readStatusButton.tintColor = self.buttonTintColor
settingsButton.tintColor = self.buttonTintColor
listStatusButton.tintColor = self.buttonTintColor
}
}
override init(frame: CGRect) {
super.init(frame: frame)
readStatusButton = createButton(.markAsRead, action: #selector(ReaderModeBarView.SELtappedReadStatusButton(_:)))
readStatusButton.accessibilityIdentifier = "ReaderModeBarView.readStatusButton"
readStatusButton.snp.makeConstraints { (make) -> Void in
make.left.equalTo(self)
make.height.centerY.equalTo(self)
make.width.equalTo(80)
}
settingsButton = createButton(.settings, action: #selector(ReaderModeBarView.SELtappedSettingsButton(_:)))
settingsButton.accessibilityIdentifier = "ReaderModeBarView.settingsButton"
settingsButton.snp.makeConstraints { (make) -> Void in
make.height.centerX.centerY.equalTo(self)
make.width.equalTo(80)
}
listStatusButton = createButton(.addToReadingList, action: #selector(ReaderModeBarView.SELtappedListStatusButton(_:)))
listStatusButton.accessibilityIdentifier = "ReaderModeBarView.listStatusButton"
listStatusButton.snp.makeConstraints { (make) -> Void in
make.right.equalTo(self)
make.height.centerY.equalTo(self)
make.width.equalTo(80)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
super.draw(rect)
guard let context = UIGraphicsGetCurrentContext() else { return }
context.setLineWidth(0.5)
context.setStrokeColor(red: 0.1, green: 0.1, blue: 0.1, alpha: 1.0)
context.setStrokeColor(UIColor.gray.cgColor)
context.beginPath()
context.move(to: CGPoint(x: 0, y: frame.height))
context.addLine(to: CGPoint(x: frame.width, y: frame.height))
context.strokePath()
}
fileprivate func createButton(_ type: ReaderModeBarButtonType, action: Selector) -> UIButton {
let button = UIButton()
addSubview(button)
button.setImage(type.image, for: UIControlState())
button.addTarget(self, action: action, for: .touchUpInside)
return button
}
func SELtappedReadStatusButton(_ sender: UIButton!) {
delegate?.readerModeBar(self, didSelectButton: unread ? .markAsRead : .markAsUnread)
}
func SELtappedSettingsButton(_ sender: UIButton!) {
delegate?.readerModeBar(self, didSelectButton: .settings)
}
func SELtappedListStatusButton(_ sender: UIButton!) {
delegate?.readerModeBar(self, didSelectButton: added ? .removeFromReadingList : .addToReadingList)
}
var unread: Bool = true {
didSet {
let buttonType: ReaderModeBarButtonType = unread && added ? .markAsRead : .markAsUnread
readStatusButton.setImage(buttonType.image, for: UIControlState())
readStatusButton.isEnabled = added
readStatusButton.alpha = added ? 1.0 : 0.6
}
}
var added: Bool = false {
didSet {
let buttonType: ReaderModeBarButtonType = added ? .removeFromReadingList : .addToReadingList
listStatusButton.setImage(buttonType.image, for: UIControlState())
}
}
}
extension ReaderModeBarView: Themeable {
func applyTheme(_ themeName: String) {
guard let theme = ReaderModeBarViewUX.Themes[themeName] else {
log.error("Unable to apply unknown theme \(themeName)")
return
}
backgroundColor = theme.backgroundColor
buttonTintColor = theme.buttonTintColor!
}
}
| mpl-2.0 | a045b904a17e609db9fd6205f832bc94 | 37.435294 | 182 | 0.682583 | 5.124706 | false | false | false | false |
vanshg/MacAssistant | Pods/SwiftProtobuf/Sources/SwiftProtobuf/ExtensionFields.swift | 2 | 20206 | // Sources/SwiftProtobuf/ExtensionFields.swift - Extension support
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Core protocols implemented by generated extensions.
///
// -----------------------------------------------------------------------------
#if !swift(>=4.2)
private let i_2166136261 = Int(bitPattern: 2166136261)
private let i_16777619 = Int(16777619)
#endif
//
// Type-erased Extension field implementation.
// Note that it has no "self or associated type" references, so can
// be used as a protocol type. (In particular, although it does have
// a hashValue property, it cannot be Hashable.)
//
// This can encode, decode, return a hashValue and test for
// equality with some other extension field; but it's type-sealed
// so you can't actually access the contained value itself.
//
public protocol AnyExtensionField: CustomDebugStringConvertible {
#if swift(>=4.2)
func hash(into hasher: inout Hasher)
#else
var hashValue: Int { get }
#endif
var protobufExtension: AnyMessageExtension { get }
func isEqual(other: AnyExtensionField) -> Bool
/// Merging field decoding
mutating func decodeExtensionField<T: Decoder>(decoder: inout T) throws
/// Fields know their own type, so can dispatch to a visitor
func traverse<V: Visitor>(visitor: inout V) throws
/// Check if the field is initialized.
var isInitialized: Bool { get }
}
public extension AnyExtensionField {
// Default implementation for extensions fields. The message types below provide
// custom versions.
var isInitialized: Bool { return true }
}
///
/// The regular ExtensionField type exposes the value directly.
///
public protocol ExtensionField: AnyExtensionField, Hashable {
associatedtype ValueType
var value: ValueType { get set }
init(protobufExtension: AnyMessageExtension, value: ValueType)
init?<D: Decoder>(protobufExtension: AnyMessageExtension, decoder: inout D) throws
}
///
/// Singular field
///
public struct OptionalExtensionField<T: FieldType>: ExtensionField {
public typealias BaseType = T.BaseType
public typealias ValueType = BaseType
public var value: ValueType
public var protobufExtension: AnyMessageExtension
public static func ==(lhs: OptionalExtensionField,
rhs: OptionalExtensionField) -> Bool {
return lhs.value == rhs.value
}
public init(protobufExtension: AnyMessageExtension, value: ValueType) {
self.protobufExtension = protobufExtension
self.value = value
}
public var debugDescription: String {
get {
return String(reflecting: value)
}
}
#if swift(>=4.2)
public func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
#else // swift(>=4.2)
public var hashValue: Int {
get { return value.hashValue }
}
#endif // swift(>=4.2)
public func isEqual(other: AnyExtensionField) -> Bool {
let o = other as! OptionalExtensionField<T>
return self == o
}
public mutating func decodeExtensionField<D: Decoder>(decoder: inout D) throws {
var v: ValueType?
try T.decodeSingular(value: &v, from: &decoder)
if let v = v {
value = v
}
}
public init?<D: Decoder>(protobufExtension: AnyMessageExtension, decoder: inout D) throws {
var v: ValueType?
try T.decodeSingular(value: &v, from: &decoder)
if let v = v {
self.init(protobufExtension: protobufExtension, value: v)
} else {
return nil
}
}
public func traverse<V: Visitor>(visitor: inout V) throws {
try T.visitSingular(value: value, fieldNumber: protobufExtension.fieldNumber, with: &visitor)
}
}
///
/// Repeated fields
///
public struct RepeatedExtensionField<T: FieldType>: ExtensionField {
public typealias BaseType = T.BaseType
public typealias ValueType = [BaseType]
public var value: ValueType
public var protobufExtension: AnyMessageExtension
public static func ==(lhs: RepeatedExtensionField,
rhs: RepeatedExtensionField) -> Bool {
return lhs.value == rhs.value
}
public init(protobufExtension: AnyMessageExtension, value: ValueType) {
self.protobufExtension = protobufExtension
self.value = value
}
#if swift(>=4.2)
public func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
#else // swift(>=4.2)
public var hashValue: Int {
get {
var hash = i_2166136261
for e in value {
hash = (hash &* i_16777619) ^ e.hashValue
}
return hash
}
}
#endif // swift(>=4.2)
public func isEqual(other: AnyExtensionField) -> Bool {
let o = other as! RepeatedExtensionField<T>
return self == o
}
public var debugDescription: String {
return "[" + value.map{String(reflecting: $0)}.joined(separator: ",") + "]"
}
public mutating func decodeExtensionField<D: Decoder>(decoder: inout D) throws {
try T.decodeRepeated(value: &value, from: &decoder)
}
public init?<D: Decoder>(protobufExtension: AnyMessageExtension, decoder: inout D) throws {
var v: ValueType = []
try T.decodeRepeated(value: &v, from: &decoder)
self.init(protobufExtension: protobufExtension, value: v)
}
public func traverse<V: Visitor>(visitor: inout V) throws {
if value.count > 0 {
try T.visitRepeated(value: value, fieldNumber: protobufExtension.fieldNumber, with: &visitor)
}
}
}
///
/// Packed Repeated fields
///
/// TODO: This is almost (but not quite) identical to RepeatedFields;
/// find a way to collapse the implementations.
///
public struct PackedExtensionField<T: FieldType>: ExtensionField {
public typealias BaseType = T.BaseType
public typealias ValueType = [BaseType]
public var value: ValueType
public var protobufExtension: AnyMessageExtension
public static func ==(lhs: PackedExtensionField,
rhs: PackedExtensionField) -> Bool {
return lhs.value == rhs.value
}
public init(protobufExtension: AnyMessageExtension, value: ValueType) {
self.protobufExtension = protobufExtension
self.value = value
}
#if swift(>=4.2)
public func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
#else // swift(>=4.2)
public var hashValue: Int {
get {
var hash = i_2166136261
for e in value {
hash = (hash &* i_16777619) ^ e.hashValue
}
return hash
}
}
#endif // swift(>=4.2)
public func isEqual(other: AnyExtensionField) -> Bool {
let o = other as! PackedExtensionField<T>
return self == o
}
public var debugDescription: String {
return "[" + value.map{String(reflecting: $0)}.joined(separator: ",") + "]"
}
public mutating func decodeExtensionField<D: Decoder>(decoder: inout D) throws {
try T.decodeRepeated(value: &value, from: &decoder)
}
public init?<D: Decoder>(protobufExtension: AnyMessageExtension, decoder: inout D) throws {
var v: ValueType = []
try T.decodeRepeated(value: &v, from: &decoder)
self.init(protobufExtension: protobufExtension, value: v)
}
public func traverse<V: Visitor>(visitor: inout V) throws {
if value.count > 0 {
try T.visitPacked(value: value, fieldNumber: protobufExtension.fieldNumber, with: &visitor)
}
}
}
///
/// Enum extensions
///
public struct OptionalEnumExtensionField<E: Enum>: ExtensionField where E.RawValue == Int {
public typealias BaseType = E
public typealias ValueType = E
public var value: ValueType
public var protobufExtension: AnyMessageExtension
public static func ==(lhs: OptionalEnumExtensionField,
rhs: OptionalEnumExtensionField) -> Bool {
return lhs.value == rhs.value
}
public init(protobufExtension: AnyMessageExtension, value: ValueType) {
self.protobufExtension = protobufExtension
self.value = value
}
public var debugDescription: String {
get {
return String(reflecting: value)
}
}
#if swift(>=4.2)
public func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
#else // swift(>=4.2)
public var hashValue: Int {
get { return value.hashValue }
}
#endif // swift(>=4.2)
public func isEqual(other: AnyExtensionField) -> Bool {
let o = other as! OptionalEnumExtensionField<E>
return self == o
}
public mutating func decodeExtensionField<D: Decoder>(decoder: inout D) throws {
var v: ValueType?
try decoder.decodeSingularEnumField(value: &v)
if let v = v {
value = v
}
}
public init?<D: Decoder>(protobufExtension: AnyMessageExtension, decoder: inout D) throws {
var v: ValueType?
try decoder.decodeSingularEnumField(value: &v)
if let v = v {
self.init(protobufExtension: protobufExtension, value: v)
} else {
return nil
}
}
public func traverse<V: Visitor>(visitor: inout V) throws {
try visitor.visitSingularEnumField(
value: value,
fieldNumber: protobufExtension.fieldNumber)
}
}
///
/// Repeated Enum fields
///
public struct RepeatedEnumExtensionField<E: Enum>: ExtensionField where E.RawValue == Int {
public typealias BaseType = E
public typealias ValueType = [E]
public var value: ValueType
public var protobufExtension: AnyMessageExtension
public static func ==(lhs: RepeatedEnumExtensionField,
rhs: RepeatedEnumExtensionField) -> Bool {
return lhs.value == rhs.value
}
public init(protobufExtension: AnyMessageExtension, value: ValueType) {
self.protobufExtension = protobufExtension
self.value = value
}
#if swift(>=4.2)
public func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
#else // swift(>=4.2)
public var hashValue: Int {
get {
var hash = i_2166136261
for e in value {
hash = (hash &* i_16777619) ^ e.hashValue
}
return hash
}
}
#endif // swift(>=4.2)
public func isEqual(other: AnyExtensionField) -> Bool {
let o = other as! RepeatedEnumExtensionField<E>
return self == o
}
public var debugDescription: String {
return "[" + value.map{String(reflecting: $0)}.joined(separator: ",") + "]"
}
public mutating func decodeExtensionField<D: Decoder>(decoder: inout D) throws {
try decoder.decodeRepeatedEnumField(value: &value)
}
public init?<D: Decoder>(protobufExtension: AnyMessageExtension, decoder: inout D) throws {
var v: ValueType = []
try decoder.decodeRepeatedEnumField(value: &v)
self.init(protobufExtension: protobufExtension, value: v)
}
public func traverse<V: Visitor>(visitor: inout V) throws {
if value.count > 0 {
try visitor.visitRepeatedEnumField(
value: value,
fieldNumber: protobufExtension.fieldNumber)
}
}
}
///
/// Packed Repeated Enum fields
///
/// TODO: This is almost (but not quite) identical to RepeatedEnumFields;
/// find a way to collapse the implementations.
///
public struct PackedEnumExtensionField<E: Enum>: ExtensionField where E.RawValue == Int {
public typealias BaseType = E
public typealias ValueType = [E]
public var value: ValueType
public var protobufExtension: AnyMessageExtension
public static func ==(lhs: PackedEnumExtensionField,
rhs: PackedEnumExtensionField) -> Bool {
return lhs.value == rhs.value
}
public init(protobufExtension: AnyMessageExtension, value: ValueType) {
self.protobufExtension = protobufExtension
self.value = value
}
#if swift(>=4.2)
public func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
#else // swift(>=4.2)
public var hashValue: Int {
get {
var hash = i_2166136261
for e in value {
hash = (hash &* i_16777619) ^ e.hashValue
}
return hash
}
}
#endif // swift(>=4.2)
public func isEqual(other: AnyExtensionField) -> Bool {
let o = other as! PackedEnumExtensionField<E>
return self == o
}
public var debugDescription: String {
return "[" + value.map{String(reflecting: $0)}.joined(separator: ",") + "]"
}
public mutating func decodeExtensionField<D: Decoder>(decoder: inout D) throws {
try decoder.decodeRepeatedEnumField(value: &value)
}
public init?<D: Decoder>(protobufExtension: AnyMessageExtension, decoder: inout D) throws {
var v: ValueType = []
try decoder.decodeRepeatedEnumField(value: &v)
self.init(protobufExtension: protobufExtension, value: v)
}
public func traverse<V: Visitor>(visitor: inout V) throws {
if value.count > 0 {
try visitor.visitPackedEnumField(
value: value,
fieldNumber: protobufExtension.fieldNumber)
}
}
}
//
// ========== Message ==========
//
public struct OptionalMessageExtensionField<M: Message & Equatable>:
ExtensionField {
public typealias BaseType = M
public typealias ValueType = BaseType
public var value: ValueType
public var protobufExtension: AnyMessageExtension
public static func ==(lhs: OptionalMessageExtensionField,
rhs: OptionalMessageExtensionField) -> Bool {
return lhs.value == rhs.value
}
public init(protobufExtension: AnyMessageExtension, value: ValueType) {
self.protobufExtension = protobufExtension
self.value = value
}
public var debugDescription: String {
get {
return String(reflecting: value)
}
}
#if swift(>=4.2)
public func hash(into hasher: inout Hasher) {
value.hash(into: &hasher)
}
#else // swift(>=4.2)
public var hashValue: Int {return value.hashValue}
#endif // swift(>=4.2)
public func isEqual(other: AnyExtensionField) -> Bool {
let o = other as! OptionalMessageExtensionField<M>
return self == o
}
public mutating func decodeExtensionField<D: Decoder>(decoder: inout D) throws {
var v: ValueType? = value
try decoder.decodeSingularMessageField(value: &v)
if let v = v {
self.value = v
}
}
public init?<D: Decoder>(protobufExtension: AnyMessageExtension, decoder: inout D) throws {
var v: ValueType?
try decoder.decodeSingularMessageField(value: &v)
if let v = v {
self.init(protobufExtension: protobufExtension, value: v)
} else {
return nil
}
}
public func traverse<V: Visitor>(visitor: inout V) throws {
try visitor.visitSingularMessageField(
value: value, fieldNumber: protobufExtension.fieldNumber)
}
public var isInitialized: Bool {
return value.isInitialized
}
}
public struct RepeatedMessageExtensionField<M: Message & Equatable>:
ExtensionField {
public typealias BaseType = M
public typealias ValueType = [BaseType]
public var value: ValueType
public var protobufExtension: AnyMessageExtension
public static func ==(lhs: RepeatedMessageExtensionField,
rhs: RepeatedMessageExtensionField) -> Bool {
return lhs.value == rhs.value
}
public init(protobufExtension: AnyMessageExtension, value: ValueType) {
self.protobufExtension = protobufExtension
self.value = value
}
#if swift(>=4.2)
public func hash(into hasher: inout Hasher) {
for e in value {
e.hash(into: &hasher)
}
}
#else // swift(>=4.2)
public var hashValue: Int {
get {
var hash = i_2166136261
for e in value {
hash = (hash &* i_16777619) ^ e.hashValue
}
return hash
}
}
#endif // swift(>=4.2)
public func isEqual(other: AnyExtensionField) -> Bool {
let o = other as! RepeatedMessageExtensionField<M>
return self == o
}
public var debugDescription: String {
return "[" + value.map{String(reflecting: $0)}.joined(separator: ",") + "]"
}
public mutating func decodeExtensionField<D: Decoder>(decoder: inout D) throws {
try decoder.decodeRepeatedMessageField(value: &value)
}
public init?<D: Decoder>(protobufExtension: AnyMessageExtension, decoder: inout D) throws {
var v: ValueType = []
try decoder.decodeRepeatedMessageField(value: &v)
self.init(protobufExtension: protobufExtension, value: v)
}
public func traverse<V: Visitor>(visitor: inout V) throws {
if value.count > 0 {
try visitor.visitRepeatedMessageField(
value: value, fieldNumber: protobufExtension.fieldNumber)
}
}
public var isInitialized: Bool {
return Internal.areAllInitialized(value)
}
}
//
// ======== Groups within Messages ========
//
// Protoc internally treats groups the same as messages, but
// they serialize very differently, so we have separate serialization
// handling here...
public struct OptionalGroupExtensionField<G: Message & Hashable>:
ExtensionField {
public typealias BaseType = G
public typealias ValueType = BaseType
public var value: G
public var protobufExtension: AnyMessageExtension
public static func ==(lhs: OptionalGroupExtensionField,
rhs: OptionalGroupExtensionField) -> Bool {
return lhs.value == rhs.value
}
public init(protobufExtension: AnyMessageExtension, value: ValueType) {
self.protobufExtension = protobufExtension
self.value = value
}
#if swift(>=4.2)
public func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
#else // swift(>=4.2)
public var hashValue: Int {return value.hashValue}
#endif // swift(>=4.2)
public var debugDescription: String { get {return value.debugDescription} }
public func isEqual(other: AnyExtensionField) -> Bool {
let o = other as! OptionalGroupExtensionField<G>
return self == o
}
public mutating func decodeExtensionField<D: Decoder>(decoder: inout D) throws {
var v: ValueType? = value
try decoder.decodeSingularGroupField(value: &v)
if let v = v {
value = v
}
}
public init?<D: Decoder>(protobufExtension: AnyMessageExtension, decoder: inout D) throws {
var v: ValueType?
try decoder.decodeSingularGroupField(value: &v)
if let v = v {
self.init(protobufExtension: protobufExtension, value: v)
} else {
return nil
}
}
public func traverse<V: Visitor>(visitor: inout V) throws {
try visitor.visitSingularGroupField(
value: value, fieldNumber: protobufExtension.fieldNumber)
}
public var isInitialized: Bool {
return value.isInitialized
}
}
public struct RepeatedGroupExtensionField<G: Message & Hashable>:
ExtensionField {
public typealias BaseType = G
public typealias ValueType = [BaseType]
public var value: ValueType
public var protobufExtension: AnyMessageExtension
public static func ==(lhs: RepeatedGroupExtensionField,
rhs: RepeatedGroupExtensionField) -> Bool {
return lhs.value == rhs.value
}
public init(protobufExtension: AnyMessageExtension, value: ValueType) {
self.protobufExtension = protobufExtension
self.value = value
}
#if swift(>=4.2)
public func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
#else // swift(>=4.2)
public var hashValue: Int {
get {
var hash = i_2166136261
for e in value {
hash = (hash &* i_16777619) ^ e.hashValue
}
return hash
}
}
#endif // swift(>=4.2)
public var debugDescription: String {
return "[" + value.map{$0.debugDescription}.joined(separator: ",") + "]"
}
public func isEqual(other: AnyExtensionField) -> Bool {
let o = other as! RepeatedGroupExtensionField<G>
return self == o
}
public mutating func decodeExtensionField<D: Decoder>(decoder: inout D) throws {
try decoder.decodeRepeatedGroupField(value: &value)
}
public init?<D: Decoder>(protobufExtension: AnyMessageExtension, decoder: inout D) throws {
var v: ValueType = []
try decoder.decodeRepeatedGroupField(value: &v)
self.init(protobufExtension: protobufExtension, value: v)
}
public func traverse<V: Visitor>(visitor: inout V) throws {
if value.count > 0 {
try visitor.visitRepeatedGroupField(
value: value, fieldNumber: protobufExtension.fieldNumber)
}
}
public var isInitialized: Bool {
return Internal.areAllInitialized(value)
}
}
| mit | 2e30ac1878037ea49f40cf397a6240a6 | 27.539548 | 99 | 0.677522 | 4.289111 | false | false | false | false |
GianniCarlo/Audiobook-Player | BookPlayer/Settings/Cells/ContributorCellView.swift | 1 | 1956 | //
// ContributorCellView.swift
// BookPlayer
//
// Created by Gianni Carlo on 2/22/19.
// Copyright © 2019 Tortuga Power. All rights reserved.
//
import UIKit
class ContributorCellView: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
}
}
class CollectionViewRow {
var attributes = [UICollectionViewLayoutAttributes]()
var spacing: CGFloat = 0
init(spacing: CGFloat) {
self.spacing = spacing
}
func add(attribute: UICollectionViewLayoutAttributes) {
self.attributes.append(attribute)
}
var rowWidth: CGFloat {
return self.attributes.reduce(0) { result, attribute -> CGFloat in
result + attribute.frame.width
} + CGFloat(self.attributes.count - 1) * self.spacing
}
func centerLayout(collectionViewWidth: CGFloat) {
let padding = (collectionViewWidth - self.rowWidth) / 2
var offset = padding
for attribute in self.attributes {
attribute.frame.origin.x = offset
offset += attribute.frame.width + self.spacing
}
}
}
class UICollectionViewCenterLayout: UICollectionViewFlowLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let attributes = super.layoutAttributesForElements(in: rect) else {
return nil
}
var rows = [CollectionViewRow]()
var currentRowY: CGFloat = -1
for attribute in attributes {
if currentRowY != attribute.frame.origin.y {
currentRowY = attribute.frame.origin.y
rows.append(CollectionViewRow(spacing: 10))
}
rows.last?.add(attribute: attribute)
}
rows.forEach { $0.centerLayout(collectionViewWidth: collectionView?.frame.width ?? 0) }
return rows.flatMap { $0.attributes }
}
}
| gpl-3.0 | 479483e42623e96dbcd10a4628e176ad | 28.179104 | 103 | 0.646036 | 4.768293 | false | false | false | false |
zenangst/Tailor | Sources/Shared/Protocols/PathAccessible.swift | 1 | 3525 | public protocol PathAccessible {
/**
- Parameter name: The key path, separated by dot
- Returns: A child dictionary for that path, otherwise it returns nil
*/
func resolve(keyPath path: String) -> [String : Any]?
}
public extension PathAccessible {
fileprivate func internalResolve<T>(_ path: [SubscriptKind]) -> T? {
var castedPath = path.dropFirst()
castedPath.append(.key(""))
let pairs = zip(path, Array(castedPath))
var result: Any = self
for (kind, castedKind) in pairs {
switch (kind, castedKind) {
case (let .key(name), .key):
result = (result as? [String : Any])?.dictionary(name) ?? [:]
case (let .key(name), .index):
result = (result as? [String : Any])?.array(name) ?? [:]
case (let .index(index), .key):
result = (result as? [[String : Any]])?.dictionary(index) ?? [:]
case (let .index(index), .index):
result = (result as? [[String : Any]])?.array(index) ?? [:]
}
}
return result as? T
}
fileprivate func resolveSubscript<T>(_ key: String) -> T? {
if let index = Int(key) {
return [index] as? T
} else {
return (self as? [String : Any])?[key] as? T
}
}
fileprivate func internalResolve<T>(_ path: String) -> T? {
let kinds: [SubscriptKind] = path.components(separatedBy: ".").map {
if let index = Int($0) {
return .index(index)
} else {
return .key($0)
}
}
return internalResolve(kinds)
}
/**
Extract last key from key path
- Parameter path: A key path
- Returns: A tuple with the first key and the remaining key path
*/
fileprivate func extractKey(_ path: String) -> (key: String, keyPath: String)? {
guard let lastSplit = path.split(".").last, path.contains(".") else { return nil }
return (key: lastSplit,
keyPath: Array(path.split(".").dropLast()).joined(separator: "."))
}
@available(*, deprecated: 1.1.3, message: "Use resolve(keyPath:)")
public func path(_ path: [SubscriptKind]) -> [String : Any]? { return internalResolve(path) }
@available(*, deprecated: 1.1.3, message: "Use resolve(keyPath:)")
public func path<T>(_ path: String) -> T? { return resolve(keyPath: path) as? T }
@available(*, deprecated: 1.1.3, message: "Use resolve(keyPath:)")
public func path(_ path: String) -> String? { return resolve(keyPath: path) }
@available(*, deprecated: 1.1.3, message: "Use resolve(keyPath:)")
public func path(_ path: String) -> Int? { return resolve(keyPath: path) }
@available(*, deprecated: 1.1.3, message: "Use resolve(keyPath:)")
public func path(_ path: String) -> [[String : Any]]? { return resolve(keyPath: path) }
@available(*, deprecated: 1.1.3, message: "Use resolve(keyPath:)")
public func path(_ path: String) -> [String : Any]? { return resolve(keyPath: path) }
/**
Resolve key path to Dictionary
- Parameter path: A key path string
- Returns: An Optional [String : Any]
*/
func resolve(keyPath path: String) -> [String : Any]? {
return internalResolve(path)
}
/**
Resolve key path to Generic type
- Parameter path: A key path string
- Returns: An generic type
*/
func resolve<T>(keyPath path: String) -> T? {
guard let (key, keyPath) = extractKey(path) else {
return resolveSubscript(path)
}
let result: [String : Any]? = internalResolve(keyPath)
return result?.property(key)
}
}
extension Dictionary: PathAccessible {}
extension Array: PathAccessible {}
| mit | 1d8035152325dabbfc3907502db6f478 | 31.638889 | 95 | 0.618723 | 3.786251 | false | false | false | false |
shnhrrsn/ImagePalette | demo/Palette/AlbumLoader.swift | 1 | 2395 | //
// AlbumLoader.swift
// Palette
//
// Created by Shaun Harrison on 8/16/17.
// Copyright © 2017 shnhrrsn. All rights reserved.
//
import UIKit
private let topAlbums = URL(string: "https://itunes.apple.com/us/rss/topalbums/limit=25/json")!
private typealias JsonObject = [String: Any]
struct AlbumLoader {
typealias Completion = ([Album]?) -> Void
static func load(_ completion: @escaping Completion) {
let mainCompletion: Completion = { images in
DispatchQueue.main.async {
completion(images)
}
}
URLSession.shared.dataTask(with: topAlbums) { (data, response, error) in
guard let data = data, let response = (response as? HTTPURLResponse), response.statusCode == 200 else {
print("Failed to load album JSON: \(String(describing: error))")
return mainCompletion(nil)
}
guard let json = try? JSONSerialization.jsonObject(with: data, options: [ ]) as? JsonObject else {
print("Failed to parse album JSON")
return mainCompletion(nil)
}
guard let entries = (json?["feed"] as? JsonObject)?["entry"] as? [JsonObject], entries.count > 0 else {
print("Failed to detect albums")
return mainCompletion(nil)
}
var rank = 0
let albums: [Album] = entries.flatMap {
guard let artwork = ($0["im:image"] as? [JsonObject])?.first?["label"] as? String else {
return nil
}
guard let name = ($0["im:name"] as? JsonObject)?["label"] as? String else {
return nil
}
guard let url = URL(string: artwork) else {
return nil
}
rank += 1
return Album(name: name, rank: rank, artworkUrl: url, artwork: nil)
}
self.load(albums: albums, completion: mainCompletion)
}.resume()
}
private static func load(albums: [Album], completion: @escaping Completion) {
guard albums.count > 0 else {
print("No valid albums to load")
return completion(nil)
}
var loadedAlbums = [Album]()
let group = DispatchGroup()
for album in albums {
group.enter()
album.loadArtwork {
defer {
group.leave()
}
guard let artwork = $0 else {
return
}
var album = album
album.artwork = artwork
loadedAlbums.append(album)
}
}
group.notify(queue: DispatchQueue.main, work: DispatchWorkItem {
guard loadedAlbums.count > 0 else {
print("Failed to load any albums")
return completion(nil)
}
completion(loadedAlbums)
})
}
}
| apache-2.0 | 004582c8d4e0c4d33cd9d887f9563734 | 22.70297 | 106 | 0.653718 | 3.464544 | false | false | false | false |
codestergit/swift | test/SILGen/newtype.swift | 2 | 3270 | // RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | %FileCheck %s -check-prefix=CHECK-RAW
// RUN: %target-swift-frontend -emit-sil -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | %FileCheck %s -check-prefix=CHECK-CANONICAL
// REQUIRES: objc_interop
import Newtype
// CHECK-CANONICAL-LABEL: sil hidden @_T07newtype17createErrorDomain{{[_0-9a-zA-Z]*}}F
// CHECK-CANONICAL: bb0([[STR:%[0-9]+]] : $String)
func createErrorDomain(str: String) -> ErrorDomain {
// CHECK-CANONICAL: [[BRIDGE_FN:%[0-9]+]] = function_ref @{{.*}}_bridgeToObjectiveC
// CHECK-CANONICAL-NEXT: [[BRIDGED:%[0-9]+]] = apply [[BRIDGE_FN]]([[STR]])
// CHECK-CANONICAL: struct $ErrorDomain ([[BRIDGED]] : $NSString)
return ErrorDomain(rawValue: str)
}
// CHECK-RAW-LABEL: sil shared [transparent] [serializable] @_T0SC11ErrorDomainVABSS8rawValue_tcfC
// CHECK-RAW: bb0([[STR:%[0-9]+]] : $String,
// CHECK-RAW: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var ErrorDomain }, var, name "self"
// CHECK-RAW: [[SELF:%[0-9]+]] = project_box [[SELF_BOX]]
// CHECK-RAW: [[UNINIT_SELF:%[0-9]+]] = mark_uninitialized [rootself] [[SELF]]
// CHECK-RAW: [[BRIDGE_FN:%[0-9]+]] = function_ref @{{.*}}_bridgeToObjectiveC
// CHECK-RAW: [[BORROWED_STR:%.*]] = begin_borrow [[STR]]
// CHECK-RAW: [[BRIDGED:%[0-9]+]] = apply [[BRIDGE_FN]]([[BORROWED_STR]])
// CHECK-RAW: end_borrow [[BORROWED_STR]] from [[STR]]
// CHECK-RAW: [[RAWVALUE_ADDR:%[0-9]+]] = struct_element_addr [[UNINIT_SELF]]
// CHECK-RAW: assign [[BRIDGED]] to [[RAWVALUE_ADDR]]
func getRawValue(ed: ErrorDomain) -> String {
return ed.rawValue
}
// CHECK-RAW-LABEL: sil shared [serializable] @_T0SC11ErrorDomainV8rawValueSSfg
// CHECK-RAW: bb0([[SELF:%[0-9]+]] : $ErrorDomain):
// CHECK-RAW: [[FORCE_BRIDGE:%[0-9]+]] = function_ref @_forceBridgeFromObjectiveC_bridgeable
// CHECK-RAW: [[STRING_RESULT_ADDR:%[0-9]+]] = alloc_stack $String
// CHECK-RAW: [[STORED_VALUE:%[0-9]+]] = struct_extract [[SELF]] : $ErrorDomain, #ErrorDomain._rawValue
// CHECK-RAW: [[STORED_VALUE_COPY:%.*]] = copy_value [[STORED_VALUE]]
// CHECK-RAW: [[STRING_META:%[0-9]+]] = metatype $@thick String.Type
// CHECK-RAW: apply [[FORCE_BRIDGE]]<String>([[STRING_RESULT_ADDR]], [[STORED_VALUE_COPY]], [[STRING_META]])
// CHECK-RAW: [[STRING_RESULT:%[0-9]+]] = load [take] [[STRING_RESULT_ADDR]]
// CHECK-RAW: return [[STRING_RESULT]]
class ObjCTest {
// CHECK-RAW-LABEL: sil hidden @_T07newtype8ObjCTestC19optionalPassThroughSC11ErrorDomainVSgAGF : $@convention(method) (@owned Optional<ErrorDomain>, @guaranteed ObjCTest) -> @owned Optional<ErrorDomain> {
// CHECK-RAW: sil hidden [thunk] @_T07newtype8ObjCTestC19optionalPassThroughSC11ErrorDomainVSgAGFTo : $@convention(objc_method) (Optional<ErrorDomain>, ObjCTest) -> Optional<ErrorDomain> {
@objc func optionalPassThrough(_ ed: ErrorDomain?) -> ErrorDomain? {
return ed
}
// CHECK-RAW-LABEL: sil hidden @_T07newtype8ObjCTestC18integerPassThroughSC5MyIntVAFF : $@convention(method) (MyInt, @guaranteed ObjCTest) -> MyInt {
// CHECK-RAW: sil hidden [thunk] @_T07newtype8ObjCTestC18integerPassThroughSC5MyIntVAFFTo : $@convention(objc_method) (MyInt, ObjCTest) -> MyInt {
@objc func integerPassThrough(_ ed: MyInt) -> MyInt {
return ed
}
}
| apache-2.0 | ce0ed517500364c9de330ce022ff03a6 | 55.37931 | 207 | 0.679817 | 3.367662 | false | true | false | false |
debugsquad/nubecero | nubecero/View/Home/VHomeCell.swift | 1 | 528 | import UIKit
class VHomeCell:UICollectionViewCell
{
weak var controller:CHome?
private let kAlphaSelected:CGFloat = 0.3
private let kAlphaNotSelected:CGFloat = 1
override init(frame:CGRect)
{
super.init(frame:frame)
clipsToBounds = true
backgroundColor = UIColor.clear
}
required init?(coder:NSCoder)
{
fatalError()
}
//MARK: public
func config(controller:CHome, model:MHomeItem)
{
self.controller = controller
}
}
| mit | 7702979b18146f1bc36298575484601b | 18.555556 | 50 | 0.621212 | 4.551724 | false | false | false | false |
ZwxWhite/V2EX | V2EX/Pods/Ji/Source/JiNode.swift | 4 | 16378 | //
// JiNode.swift
// Ji
//
// Created by Honghao Zhang on 2015-07-20.
// Copyright (c) 2015 Honghao Zhang (张宏昊)
//
// 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
public typealias 戟节点 = JiNode
/**
JiNode types, these match element types in tree.h
*/
public enum JiNodeType: Int {
case Element = 1
case Attribute = 2
case Text = 3
case CDataSection = 4
case EntityRef = 5
case Entity = 6
case Pi = 7
case Comment = 8
case Document = 9
case DocumentType = 10
case DocumentFrag = 11
case Notation = 12
case HtmlDocument = 13
case DTD = 14
case ElementDecl = 15
case AttributeDecl = 16
case EntityDecl = 17
case NamespaceDecl = 18
case XIncludeStart = 19
case XIncludeEnd = 20
case DocbDocument = 21
}
/// Ji node
public class JiNode {
/// The xmlNodePtr for this node.
public let xmlNode: xmlNodePtr
/// The Ji document contians this node.
public unowned let document: Ji
/// Node type.
public let type: JiNodeType
/// A helper flag to get whether keepTextNode has been changed.
private var _keepTextNodePrevious = false
/// Whether should remove text node. By default, keepTextNode is false.
public var keepTextNode = false
/**
Initializes a JiNode object with the supplied xmlNodePtr, Ji document and keepTextNode boolean flag.
- parameter xmlNode: The xmlNodePtr for a node.
- parameter jiDocument: The Ji document contains this node.
- parameter keepTextNode: Whether it should keep text node, by default, it's false.
- returns: The initialized JiNode object.
*/
init(xmlNode: xmlNodePtr, jiDocument: Ji, keepTextNode: Bool = false) {
self.xmlNode = xmlNode
document = jiDocument
type = JiNodeType(rawValue: Int(xmlNode.memory.type.rawValue))!
self.keepTextNode = keepTextNode
}
/// The tag name of this node.
public var tag: String? { return name }
/// The tag name of this node.
public var tagName: String? { return name }
/// The tag name of this node.
public lazy var name: String? = {
return String.fromXmlChar(self.xmlNode.memory.name)
}()
/// Helper property for avoiding unneeded calculations.
private var _children: [JiNode] = []
/// A helper flag for avoiding unneeded calculations.
private var _childrenHasBeenCalculated = false
/// The children of this node. keepTextNode property affects the results
public var children: [JiNode] {
if _childrenHasBeenCalculated && keepTextNode == _keepTextNodePrevious {
return _children
} else {
_children = [JiNode]()
for var childNodePointer = xmlNode.memory.children;
childNodePointer != nil;
childNodePointer = childNodePointer.memory.next
{
if keepTextNode || xmlNodeIsText(childNodePointer) == 0 {
let childNode = JiNode(xmlNode: childNodePointer, jiDocument: document, keepTextNode: keepTextNode)
_children.append(childNode)
}
}
_childrenHasBeenCalculated = true
_keepTextNodePrevious = keepTextNode
return _children
}
}
/// The first child of this node, nil if the node has no child.
public var firstChild: JiNode? {
var first = xmlNode.memory.children
if first == nil { return nil }
if keepTextNode {
return JiNode(xmlNode: first, jiDocument: document, keepTextNode: keepTextNode)
} else {
while xmlNodeIsText(first) != 0 {
first = first.memory.next
if first == nil { return nil }
}
return JiNode(xmlNode: first, jiDocument: document, keepTextNode: keepTextNode)
}
}
/// The last child of this node, nil if the node has no child.
public var lastChild: JiNode? {
var last = xmlNode.memory.last
if last == nil { return nil }
if keepTextNode {
return JiNode(xmlNode: last, jiDocument: document, keepTextNode: keepTextNode)
} else {
while xmlNodeIsText(last) != 0 {
last = last.memory.prev
if last == nil { return nil }
}
return JiNode(xmlNode: last, jiDocument: document, keepTextNode: keepTextNode)
}
}
/// Whether this node has children.
public var hasChildren: Bool {
return firstChild != nil
}
/// The parent of this node.
public lazy var parent: JiNode? = {
if self.xmlNode.memory.parent == nil { return nil }
return JiNode(xmlNode: self.xmlNode.memory.parent, jiDocument: self.document)
}()
/// The next sibling of this node.
public var nextSibling: JiNode? {
var next = xmlNode.memory.next
if next == nil { return nil }
if keepTextNode {
return JiNode(xmlNode: next, jiDocument: document, keepTextNode: keepTextNode)
} else {
while xmlNodeIsText(next) != 0 {
next = next.memory.next
if next == nil { return nil }
}
return JiNode(xmlNode: next, jiDocument: document, keepTextNode: keepTextNode)
}
}
/// The previous sibling of this node.
public var previousSibling: JiNode? {
var prev = xmlNode.memory.prev
if prev == nil { return nil }
if keepTextNode {
return JiNode(xmlNode: prev, jiDocument: document, keepTextNode: keepTextNode)
} else {
while xmlNodeIsText(prev) != 0 {
prev = prev.memory.prev
if prev == nil { return nil }
}
return JiNode(xmlNode: prev, jiDocument: document, keepTextNode: keepTextNode)
}
}
/// Raw content of this node. Children, tags are also included.
public lazy var rawContent: String? = {
let buffer = xmlBufferCreate()
if self.document.isXML {
xmlNodeDump(buffer, self.document.xmlDoc, self.xmlNode, 0, 0)
} else {
htmlNodeDump(buffer, self.document.htmlDoc, self.xmlNode)
}
let result = String.fromXmlChar(buffer.memory.content)
xmlBufferFree(buffer)
return result
}()
/// Content of this node. Tags are removed, leading/trailing white spaces, new lines are kept.
public lazy var content: String? = {
let contentChars = xmlNodeGetContent(self.xmlNode)
if contentChars == nil { return nil }
let contentString = String.fromXmlChar(contentChars)
free(contentChars)
return contentString
}()
/// Raw value of this node. Leading/trailing white spaces, new lines are kept.
public lazy var value: String? = {
let valueChars = xmlNodeListGetString(self.document.xmlDoc, self.xmlNode.memory.children, 1)
if valueChars == nil { return nil }
let valueString = String.fromXmlChar(valueChars)
free(valueChars)
return valueString
}()
/**
Get attribute value with key.
- parameter key: An attribute key string.
- returns: The attribute value for the key.
*/
public subscript(key: String) -> String? {
get {
for var attribute: xmlAttrPtr = self.xmlNode.memory.properties; attribute != nil; attribute = attribute.memory.next {
if key == String.fromXmlChar(attribute.memory.name) {
let contentChars = xmlNodeGetContent(attribute.memory.children)
if contentChars == nil { return nil }
let contentString = String.fromXmlChar(contentChars)
free(contentChars)
return contentString
}
}
return nil
}
}
/// The attributes dictionary of this node.
public lazy var attributes: [String: String] = {
var result = [String: String]()
for var attribute: xmlAttrPtr = self.xmlNode.memory.properties;
attribute != nil;
attribute = attribute.memory.next
{
let key = String.fromXmlChar(attribute.memory.name)
assert(key != nil, "key doesn't exist")
let valueChars = xmlNodeGetContent(attribute.memory.children)
var value: String? = ""
if valueChars != nil {
value = String.fromXmlChar(valueChars)
assert(value != nil, "value doesn't exist")
}
free(valueChars)
result[key!] = value!
}
return result
}()
// MARK: - XPath query
/**
Perform XPath query on this node.
- parameter xPath: XPath query string.
- returns: An array of JiNode, an empty array will be returned if XPath matches no nodes.
*/
public func xPath(xPath: String) -> [JiNode] {
let xPathContext = xmlXPathNewContext(self.document.xmlDoc)
if xPathContext == nil {
// Unable to create XPath context.
return []
}
xPathContext.memory.node = self.xmlNode
let xPathObject = xmlXPathEvalExpression(UnsafePointer<xmlChar>(xPath.cStringUsingEncoding(NSUTF8StringEncoding)!), xPathContext)
xmlXPathFreeContext(xPathContext)
if xPathObject == nil {
// Unable to evaluate XPath.
return []
}
let nodeSet = xPathObject.memory.nodesetval
if nodeSet == nil || nodeSet.memory.nodeNr == 0 || nodeSet.memory.nodeTab == nil {
// NodeSet is nil.
xmlXPathFreeObject(xPathObject)
return []
}
var resultNodes = [JiNode]()
for i in 0 ..< Int(nodeSet.memory.nodeNr) {
let jiNode = JiNode(xmlNode: nodeSet.memory.nodeTab[i], jiDocument: self.document, keepTextNode: keepTextNode)
resultNodes.append(jiNode)
}
xmlXPathFreeObject(xPathObject)
return resultNodes
}
// MARK: - Handy search methods: Children
/**
Find the first child with the tag name of this node.
- parameter name: A tag name string.
- returns: The JiNode object found or nil if it doesn't exist.
*/
public func firstChildWithName(name: String) -> JiNode? {
var node = firstChild
while (node != nil) {
if node!.name == name {
return node
}
node = node?.nextSibling
}
return nil
}
/**
Find the children with the tag name of this node.
- parameter name: A tag name string.
- returns: An array of JiNode.
*/
public func childrenWithName(name: String) -> [JiNode] {
return children.filter { $0.name == name }
}
/**
Find the first child with the attribute name and value of this node.
- parameter attributeName: An attribute name.
- parameter attributeValue: The attribute value for the attribute name.
- returns: The JiNode object found or nil if it doesn't exist.
*/
public func firstChildWithAttributeName(attributeName: String, attributeValue: String) -> JiNode? {
var node = firstChild
while (node != nil) {
if let value = node![attributeName] where value == attributeValue {
return node
}
node = node?.nextSibling
}
return nil
}
/**
Find the children with the attribute name and value of this node.
- parameter attributeName: An attribute name.
- parameter attributeValue: The attribute value for the attribute name.
- returns: An array of JiNode.
*/
public func childrenWithAttributeName(attributeName: String, attributeValue: String) -> [JiNode] {
return children.filter { $0.attributes[attributeName] == attributeValue }
}
// MARK: - Handy search methods: Descendants
/**
Find the first descendant with the tag name of this node.
- parameter name: A tag name string.
- returns: The JiNode object found or nil if it doesn't exist.
*/
public func firstDescendantWithName(name: String) -> JiNode? {
return firstDescendantWithName(name, node: self)
}
/**
Helper method: Find the first descendant with the tag name of the node provided.
- parameter name: A tag name string.
- parameter node: The node from which to find.
- returns: The JiNode object found or nil if it doesn't exist.
*/
private func firstDescendantWithName(name: String, node: JiNode) -> JiNode? {
if !node.hasChildren {
return nil
}
for child in node {
if child.name == name {
return child
}
if let nodeFound = firstDescendantWithName(name, node: child) {
return nodeFound
}
}
return nil
}
/**
Find the descendant with the tag name of this node.
- parameter name: A tag name string.
- returns: An array of JiNode.
*/
public func descendantsWithName(name: String) -> [JiNode] {
return descendantsWithName(name, node: self)
}
/**
Helper method: Find the descendant with the tag name of the node provided.
- parameter name: A tag name string.
- parameter node: The node from which to find.
- returns: An array of JiNode.
*/
private func descendantsWithName(name: String, node: JiNode) -> [JiNode] {
if !node.hasChildren {
return []
}
var results = [JiNode]()
for child in node {
if child.name == name {
results.append(child)
}
results.appendContentsOf(descendantsWithName(name, node: child))
}
return results
}
/**
Find the first descendant with the attribute name and value of this node.
- parameter attributeName: An attribute name.
- parameter attributeValue: The attribute value for the attribute name.
- returns: The JiNode object found or nil if it doesn't exist.
*/
public func firstDescendantWithAttributeName(attributeName: String, attributeValue: String) -> JiNode? {
return firstDescendantWithAttributeName(attributeName, attributeValue: attributeValue, node: self)
}
/**
Helper method: Find the first descendant with the attribute name and value of the node provided.
- parameter attributeName: An attribute name.
- parameter attributeValue: The attribute value for the attribute name.
- parameter node: The node from which to find.
- returns: The JiNode object found or nil if it doesn't exist.
*/
private func firstDescendantWithAttributeName(attributeName: String, attributeValue: String, node: JiNode) -> JiNode? {
if !node.hasChildren {
return nil
}
for child in node {
if child[attributeName] == attributeValue {
return child
}
if let nodeFound = firstDescendantWithAttributeName(attributeName, attributeValue: attributeValue, node: child) {
return nodeFound
}
}
return nil
}
/**
Find the descendants with the attribute name and value of this node.
- parameter attributeName: An attribute name.
- parameter attributeValue: The attribute value for the attribute name.
- returns: An array of JiNode.
*/
public func descendantsWithAttributeName(attributeName: String, attributeValue: String) -> [JiNode] {
return descendantsWithAttributeName(attributeName, attributeValue: attributeValue, node: self)
}
/**
Helper method: Find the descendants with the attribute name and value of the node provided.
- parameter attributeName: An attribute name.
- parameter attributeValue: The attribute value for the attribute name.
- parameter node: The node from which to find.
- returns: An array of JiNode.
*/
private func descendantsWithAttributeName(attributeName: String, attributeValue: String, node: JiNode) -> [JiNode] {
if !node.hasChildren {
return []
}
var results = [JiNode]()
for child in node {
if child[attributeName] == attributeValue {
results.append(child)
}
results.appendContentsOf(descendantsWithAttributeName(attributeName, attributeValue: attributeValue, node: child))
}
return results
}
}
// MARK: - Equatable
extension JiNode: Equatable { }
public func ==(lhs: JiNode, rhs: JiNode) -> Bool {
if lhs.document == rhs.document && lhs.xmlNode != nil && rhs.xmlNode != nil {
return xmlXPathCmpNodes(lhs.xmlNode, rhs.xmlNode) == 0
}
return false
}
// MARK: - SequenceType
extension JiNode: SequenceType {
public func generate() -> JiNodeGenerator {
return JiNodeGenerator(node: self)
}
}
/// JiNodeGenerator
public class JiNodeGenerator: GeneratorType {
private var node: JiNode?
private var started = false
public init(node: JiNode) {
self.node = node
}
public func next() -> JiNode? {
if !started {
node = node?.firstChild
started = true
} else {
node = node?.nextSibling
}
return node
}
}
// MARK: - CustomStringConvertible
extension JiNode: CustomStringConvertible {
public var description: String {
return rawContent ?? "nil"
}
}
| mit | 325dd21e4246da98aff144aeb380f267 | 27.762742 | 131 | 0.707442 | 3.65966 | false | false | false | false |
bengottlieb/ios | FiveCalls/FiveCalls/IssuesManager.swift | 1 | 2374 | //
// IssuesManager.swift
// FiveCalls
//
// Created by Ben Scheirman on 2/2/17.
// Copyright © 2017 5calls. All rights reserved.
//
import Foundation
enum IssuesLoadResult {
case success
case serverError(Error)
case offline
}
class IssuesManager {
enum Query {
case active
case inactive
}
var issuesList: IssuesList?
var issues: [Issue] {
return issuesList?.issues ?? []
}
var isSplitDistrict: Bool { return self.issuesList?.splitDistrict == true }
func issue(withId id: String) -> Issue? {
return issuesList?.issues.filter { $0.id == id }.first
}
func fetchIssues(forQuery query: Query, location: UserLocation?, completion: @escaping (IssuesLoadResult) -> Void) {
let operation = FetchIssuesOperation(query: query, location: location)
operation.completionBlock = { [weak self, weak operation] in
if let issuesList = operation?.issuesList {
self?.issuesList = issuesList
// notification!
DispatchQueue.main.async {
completion(.success)
}
} else {
let error = operation?.error
print("Could not load issues..")
DispatchQueue.main.async {
if let e = error {
print(e.localizedDescription)
if self?.isOfflineError(error: e) == true {
completion(.offline)
} else {
completion(.serverError(e))
}
} else {
// souldn't happen, but let's just assume connection error
completion(.offline)
}
}
}
}
OperationQueue.main.addOperation(operation)
}
private func isOfflineError(error: Error) -> Bool {
let e = error as NSError
guard e.domain == NSURLErrorDomain else { return false }
return e.code == NSURLErrorNetworkConnectionLost ||
e.code == NSURLErrorNotConnectedToInternet ||
e.code == NSURLErrorSecureConnectionFailed
}
}
| mit | 68af2621ec07b7963592482e9cd8abf7 | 28.6625 | 120 | 0.50906 | 5.518605 | false | false | false | false |
artemnovichkov/Carting | Sources/CartingCore/Extensions/PBXShellScriptBuildPhase+Paths.swift | 1 | 1840 | //
// Copyright © 2019 Artem Novichkov. All rights reserved.
//
import XcodeProj
extension PBXShellScriptBuildPhase {
@discardableResult
func update(shellScript: String) -> Bool {
if self.shellScript != shellScript {
self.shellScript = shellScript
return true
}
return false
}
@discardableResult
func update(inputPaths: [String], outputPaths: [String]) -> Bool {
var scriptHasBeenUpdated = false
if inputFileListPaths?.isEmpty == false {
inputFileListPaths?.removeAll()
scriptHasBeenUpdated = true
}
if self.inputPaths != inputPaths {
self.inputPaths = inputPaths
scriptHasBeenUpdated = true
}
if outputFileListPaths?.isEmpty == false {
outputFileListPaths?.removeAll()
scriptHasBeenUpdated = true
}
if self.outputPaths != outputPaths {
self.outputPaths = outputPaths
scriptHasBeenUpdated = true
}
return scriptHasBeenUpdated
}
@discardableResult
func update(inputFileListPath: String, outputFileListPath: String) -> Bool {
var scriptHasBeenUpdated = false
if !inputPaths.isEmpty {
inputPaths.removeAll()
scriptHasBeenUpdated = true
}
if inputFileListPaths?.first != inputFileListPath {
inputFileListPaths = [inputFileListPath]
scriptHasBeenUpdated = true
}
if outputFileListPaths?.first != outputFileListPath {
outputFileListPaths = [outputFileListPath]
scriptHasBeenUpdated = true
}
if !outputPaths.isEmpty {
outputPaths.removeAll()
scriptHasBeenUpdated = true
}
return scriptHasBeenUpdated
}
}
| mit | 33866912edfa6c29c772785933a15b41 | 29.147541 | 80 | 0.607395 | 5.440828 | false | false | false | false |
dulingkang/RealmDemo | RealmDemo/RealmDemo/MaterialModel.swift | 1 | 1085 | //
// MaterialModel.swift
// XiaoKa
//
// Created by ShawnDu on 15/12/16.
// Copyright © 2015年 SmarterEye. All rights reserved.
//
import Foundation
class OneItem: RLMObject {
var id: String?
dynamic var category: String?
dynamic var thumbnailUrl: String?
dynamic var bigPicUrl: String?
override init() {
super.init()
}
override static func primaryKey() -> String? {
return "id"
}
convenience init(id: String, category: String, thumb: String, big: String) {
self.init()
self.id = id
self.category = category
self.thumbnailUrl = thumb
self.bigPicUrl = big
}
}
class OneCategory: RLMObject {
dynamic var category: String?
dynamic var thumbnailUrl: String?
override init() {
super.init()
}
override static func primaryKey() -> String? {
return "category"
}
convenience init(category: String, thumb: String) {
self.init()
self.category = category
self.thumbnailUrl = thumb
}
}
| mit | 5f60f2f7e0379d94a79b4218f7f08ea9 | 18.672727 | 80 | 0.593346 | 4.177606 | false | false | false | false |
mrdepth/EVEUniverse | Legacy/Neocom/Neocom/NCJumpClonesViewController.swift | 2 | 4495 | //
// NCJumpClonesViewController.swift
// Neocom
//
// Created by Artem Shimanski on 02.05.17.
// Copyright © 2017 Artem Shimanski. All rights reserved.
//
import UIKit
import EVEAPI
import Futures
class NCJumpClonesViewController: NCTreeViewController {
override func viewDidLoad() {
super.viewDidLoad()
accountChangeAction = .reload
tableView.register([Prototype.NCHeaderTableViewCell.default,
Prototype.NCDefaultTableViewCell.attribute,
Prototype.NCDefaultTableViewCell.placeholder])
}
private var clones: CachedValue<ESI.Clones.JumpClones>?
override func load(cachePolicy: URLRequest.CachePolicy) -> Future<[NCCacheRecord]> {
return dataManager.clones().then(on: .main) { result -> [NCCacheRecord] in
self.clones = result
return [result.cacheRecord(in: NCCache.sharedCache!.viewContext)]
}
}
override func content() -> Future<TreeNode?> {
return DispatchQueue.global(qos: .utility).async { () -> TreeNode? in
guard let value = self.clones?.value else {throw NCTreeViewControllerError.noResult}
let locationIDs = value.jumpClones.compactMap {$0.locationID}
let locations = try? self.dataManager.locations(ids: Set(locationIDs)).get()
return try NCDatabase.sharedDatabase!.performTaskAndWait { managedObjectContext -> TreeNode? in
let invTypes = NCDBInvType.invTypes(managedObjectContext: managedObjectContext)
let t = 3600 * 24 + (value.lastCloneJumpDate ?? .distantPast).timeIntervalSinceNow
let s = String(format: NSLocalizedString("Clone jump availability: %@", comment: ""), t > 0 ? NCTimeIntervalFormatter.localizedString(from: t, precision: .minutes) : NSLocalizedString("Now", comment: ""))
var sections = [TreeNode]()
sections.append(DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.attribute,
nodeIdentifier: "Jump",
title: NSLocalizedString("Next Clone Jump Availability", comment: "").uppercased(),
subtitle: s))
let list = [(NCDBAttributeID.intelligenceBonus, NSLocalizedString("Intelligence", comment: "")),
(NCDBAttributeID.memoryBonus, NSLocalizedString("Memory", comment: "")),
(NCDBAttributeID.perceptionBonus, NSLocalizedString("Perception", comment: "")),
(NCDBAttributeID.willpowerBonus, NSLocalizedString("Willpower", comment: "")),
(NCDBAttributeID.charismaBonus, NSLocalizedString("Charisma", comment: ""))]
for (i, clone) in value.jumpClones.enumerated() {
let implants = clone.implants.compactMap { implant -> (NCDBInvType, Int)? in
guard let type = invTypes[implant] else {return nil}
return (type, Int(type.allAttributes[NCDBAttributeID.implantness.rawValue]?.value ?? 100))
}.sorted {$0.1 < $1.1}
var rows = implants.map { (type, _) -> TreeRow in
if let enhancer = list.first(where: { (type.allAttributes[$0.0.rawValue]?.value ?? 0) > 0 }) {
return DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.attribute,
nodeIdentifier: "\(type.typeID).\(i)",
image: type.icon?.image?.image ?? NCDBEveIcon.defaultType.image?.image,
title: type.typeName?.uppercased(),
subtitle: "\(enhancer.1) +\(Int(type.allAttributes[enhancer.0.rawValue]!.value))",
accessoryType: .disclosureIndicator,
route: Router.Database.TypeInfo(type))
}
else {
return DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.attribute,
nodeIdentifier: "\(type.typeID).\(i)",
image: type.icon?.image?.image ?? NCDBEveIcon.defaultType.image?.image,
title: type.typeName?.uppercased(),
accessoryType: .disclosureIndicator,
route: Router.Database.TypeInfo(type))
}
}
if rows.isEmpty {
rows.append(DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.placeholder, nodeIdentifier: "NoImplants\(i)", title: NSLocalizedString("No Implants Installed", comment: "").uppercased()))
}
if let title = locations?[clone.locationID]?.displayName.uppercased() {
sections.append(DefaultTreeSection(nodeIdentifier: "\(i)", attributedTitle: title, children: rows))
}
else {
sections.append(DefaultTreeSection(nodeIdentifier: "\(i)", title: NSLocalizedString("Unknown Location", comment: ""), children: rows))
}
}
guard !sections.isEmpty else {throw NCTreeViewControllerError.noResult}
return RootNode(sections)
}
}
}
}
| lgpl-2.1 | 9717d50f8092739a4857821a7e575f93 | 44.393939 | 208 | 0.691811 | 4.418879 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.